"""Lecture 23, the flight envelope of Hull's SBJ at 11,000 lb on the Mach-altitude plane: the stall line (C_L,max = 1.24,
Hull), the thrust limits of level flight (the two level-flight speeds with full thrust), the dynamic-pressure limit
(300 lb/ft^2) and the Mach limit (0.81), both stated by Hull (sec. 7.7) and held in the course dataset, and the
service ceiling. Writes img/fig-23-sbj-envelope.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _climb as C
from flight import performance as PF, atmosphere as A
from flight.constants import FT, G0

V = C.SBJ
W = C.W_SBJ
LIM = V.info["limits"]
M_MAX, Q_MAX = LIM["mach_max"], LIM["q_max"]
CLMAX = V.aero.clmax(0.0)
CD0, K = C.polar(V)
H = np.linspace(0, 14200, 300)


def a(h):
    return A.speed_of_sound(A.isa(h)[0])


def stall_mach(h):
    return PF.stall_mach(PF.dimensionless_force(W, A.isa(h)[1], V.aero.S), CLMAX)


def q_mach(h):
    return np.sqrt(Q_MAX / (0.7 * A.isa(h)[1]))


def thrust_machs(h):
    tau, vs, es = C.scales(V, W, h)
    if tau < 1:
        return None
    u1, u2 = PF.level_speed_ratios(tau)
    return u1 * vs / a(h), u2 * vs / a(h)


H_Q_M = float(A.pressure_altitude(Q_MAX / (0.7 * M_MAX**2)))          # where the q limit meets the Mach limit
SERVICE = PF.ceiling(lambda h: C.max_roc(V, W, h), 100 * FT / 60, 0.0, 20000.0)
TM = [thrust_machs(h) for h in H]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    lo = np.array([max(stall_mach(h), t[0]) if t else np.nan for h, t in zip(H, TM)])
    hi = np.array([min(q_mach(h), M_MAX, t[1]) if t else np.nan for h, t in zip(H, TM)])
    ok = np.isfinite(lo) & np.isfinite(hi) & (lo < hi)
    ax.fill_betweenx(H[ok] / 1e3, lo[ok], hi[ok], color=BLUE, alpha=0.15)
    ax.plot([stall_mach(h) for h in H], H / 1e3, color=MAROON, lw=2.2, label="stall, $C_{L,\\max}=1.24$")
    th = np.array([t if t else (np.nan, np.nan) for t in TM])
    ax.plot(th[:, 1], H / 1e3, color=GREEN, lw=2.2, label="thrust limit (full thrust)")
    ax.plot(th[:, 0], H / 1e3, color=GREEN, lw=1.6, ls="--")
    ax.plot([q_mach(h) for h in H], H / 1e3, color=AMBER, lw=2.2, label="$q_{\\max}=300$ lb/ft$^2$")
    ax.axvline(M_MAX, color=INK, lw=2.0, label="$M_{\\max}=0.81$")
    ax.axhline(SERVICE / 1e3, color=GREY, lw=1.2, ls=":", label=f"service ceiling {SERVICE / FT:,.0f} ft")
    ax.set_xlim(0, 1.0); ax.set_ylim(0, 15); ax.set_xlabel("Mach number"); ax.set_ylabel("altitude (km)")
    ax.legend(frameon=False, fontsize=11, loc="upper left")
    despine(ax)
    save(fig, "fig-23-sbj-envelope")
