"""Lecture 22: specific excess power against true airspeed at five altitudes for the Tejas-class model at 8500 kg with
full afterburner (_energy.ps). Speeds below the 1 g stall are not drawn. Writes img/fig-22-ps-speed.png."""
import numpy as np
from _visual import plt, save, despine, INK, GREY
import _energy as EN
import _fighter as F
from flight import atmosphere as A

ALTS = [0.0, 4000.0, 8000.0, 12000.0, 16000.0]
COLS = ["#c9a27e", "#b87a5e", "#9c5243", "#7d3030", "#4a1416"]
MACH = np.linspace(0.25, 1.75, 301)


def curve(h):
    p = np.array([EN.ps(m, h) for m in MACH])
    p[MACH < F.stall(F.TEJ, F.M_REF, h)] = np.nan
    return MACH * EN.a_of(h), p


def best(h):
    V, p = curve(h)
    i = int(np.nanargmax(p))
    return float(V[i]), float(p[i])


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    for h, c in zip(ALTS, COLS):
        V, p = curve(h)
        ax.plot(V, p, color=c, lw=2.8, label=f"{h / 1000:.0f} km: largest {best(h)[1]:.0f} m/s")
        ax.plot(*best(h), "o", color=c, ms=7)
    ax.axhline(0, color=GREY, lw=1.2); ax.set_ylim(-60, None); ax.set_xlim(0, 820)
    ax.set_xlabel("true airspeed (m/s)"); ax.set_ylabel("specific excess power $P_s$ (m/s)")
    ax.legend(frameon=False, fontsize=11.5, loc="upper right")
    despine(ax)
    save(fig, "fig-22-ps-speed")
