"""Lecture 11: how the supersonic pocket opens. An ILLUSTRATIVE upper-surface pressure distribution (a smooth shape,
not computed from any section) with lowest low-speed value Cp0 = -0.43, scaled by Prandtl-Glauert
(flight.gasdynamics) as the Mach number rises from 0.5 to 0.82, against the sonic level C_p* at each Mach number.
Prandtl-Glauert does not hold once there is supersonic flow, so the size of the pocket past M_cr is only qualitative.
Writes img/anim-11-pocket.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, INK, GREY, AMBER
from flight import gasdynamics as GD

CP0_MIN = -0.43
M_CR = float(GD.critical_mach(CP0_MIN))
X = np.linspace(0.005, 1.0, 600)
_S = X**0.35 * (1 - X)**0.85
SHAPE = _S / _S.max()                                          # illustrative, 0 at both ends, 1 at its peak
MS = np.linspace(0.50, 0.82, 65)


def cp(M):
    return GD.prandtl_glauert(CP0_MIN * SHAPE, M)


def pocket(M):
    """(start, end) fractions of chord where the local flow is supersonic, or None."""
    sel = cp(M) < GD.cp_star(M)
    return (float(X[sel][0]), float(X[sel][-1])) if sel.any() else None


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))

    fig.subplots_adjust(bottom=0.13, left=0.09, right=0.97, top=0.97)

    def frame(k):
        M = MS[k]; ax.clear()
        c, star = cp(M), float(GD.cp_star(M))
        ax.plot(X, -c, color=INK, lw=2.8, label="$-C_p$ on the upper surface (illustrative shape)")
        ax.axhline(-star, color=MAROON, lw=2, ls="--", label="$-C_p^*$: local flow exactly sonic")
        ax.fill_between(X, -star, -c, where=c < star, color=AMBER, alpha=0.6, label="supersonic pocket")
        p = pocket(M)
        text = f"$M$ = {M:.2f}" + ("    all subsonic" if p is None else "    a supersonic pocket")
        ax.text(0.5, 1.28, text, ha="center", fontsize=13.5)
        ax.text(0.98, 1.17, f"$M_{{cr}}$ = {M_CR:.2f}", ha="right", fontsize=12.5, color=MAROON)
        ax.set_xlim(0, 1); ax.set_ylim(0, 1.38); ax.set_xlabel("position along the chord, $x/c$"); ax.set_ylabel("$-C_p$")
        ax.legend(frameon=False, fontsize=11, loc="upper left", bbox_to_anchor=(0.01, 0.9))
        despine(ax)
        return []

    save_anim(fig, frame, len(MS), 10, "anim-11-pocket", dpi=90, hold=2.5)
