"""Lecture 23: level-flight envelopes (full thrust at least equal to drag, C_L no more than C_Lmax) on the Mach-altitude
plane for the HANSA-3, the HJT-16 Kiran model, Hull's business jet (also cut at its M_max 0.81) and the Tejas-class
model with afterburner (_fighter). Course datasets, several partly estimated. The HANSA-3 and Kiran data contain no
compressibility drag. The Lecture 17 transport is left out: its data have neither a drag rise nor a Mach limit.
Writes img/fig-23-envelopes-compared.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK
import _fighter as F
import _climb as C
from flight import performance as PF, atmosphere as A, vehicle
from flight.constants import G0, RHO0_SL, T0_SL

MACH = np.linspace(0.05, 2.0, 391)
H = np.linspace(0.0, 21000.0, 211)


def excess_mask(name, m_max=None):
    v = vehicle.load(name)
    eng = v.stages[0].engine
    mass = 11000 * C.LB / G0 if name == "sbj-hull" else v.gross_mass
    cd0, k, clmax, S = float(v.aero.cd0(0.0)), float(v.aero.k(0.0)), float(v.aero.clmax(0.0)), v.aero.S
    out = np.zeros((len(H), len(MACH)), bool)
    for i, h in enumerate(H):
        t, p, rho = A.isa(h)
        a = A.speed_of_sound(t)
        for j, M in enumerate(MACH):
            V = M * a
            cl = mass * G0 / (0.5 * rho * V * V * S)
            if cl > clmax or (m_max and M > m_max):
                continue
            D = sum(PF.level_flight_drag(mass * G0, rho, V, S, cd0, k))
            out[i, j] = eng.thrust(1.0, p, rho, rho / RHO0_SL, t / T0_SL, V, M) >= D
    return out


def fighter_mask():
    out = np.zeros((len(H), len(MACH)), bool)
    for i, h in enumerate(H):
        rho = A.isa(h)[2]; a = A.speed_of_sound(A.isa(h)[0])
        for j, M in enumerate(MACH):
            cl = F.M_REF * G0 / (0.5 * rho * (M * a)**2 * F.TEJ.aero.S)
            out[i, j] = cl <= F.TEJ.aero.clmax(0.0) and F.thrust(F.TEJ, M, h) >= F.drag(F.TEJ, M, F.M_REF, h)
    return out


CASES = [("Tejas-class model, afterburner", fighter_mask(), AMBER), ("Hull's business jet", excess_mask("sbj-hull", 0.81), BLUE),
         ("Kiran model", excess_mask("hjt-16-kiran"), MAROON), ("HANSA-3", excess_mask("hansa-3"), GREEN)]


def top_km(mask):
    return float(H[np.where(mask.any(axis=1))[0].max()]) / 1000


def mach_range(mask, h=0.0):
    row = mask[int(np.argmin(abs(H - h)))]
    return (float(MACH[row].min()), float(MACH[row].max())) if row.any() else None


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    for lab, m, c in CASES:
        ax.contourf(MACH, H / 1000, m.astype(float), levels=[0.5, 1.5], colors=[c], alpha=0.28)
        ax.contour(MACH, H / 1000, m.astype(float), levels=[0.5], colors=[c], linewidths=2.2)
        ax.plot([], [], color=c, lw=6, label=f"{lab}: up to {top_km(m):.1f} km")
    ax.set_xlim(0, 2.0); ax.set_ylim(0, 21); ax.set_xlabel("Mach number"); ax.set_ylabel("altitude (km)")
    fig.legend(frameon=False, fontsize=11.5, ncol=2, loc="upper center", bbox_to_anchor=(0.5, 0.02))
    despine(ax)
    save(fig, "fig-23-envelopes-compared")
