"""Lecture 24, turn-rate diagrams of the Tejas-class fighter (8500 kg) and Sadraey's F-16 (12,331 kg) at 3 km with full
afterburner, from the partly estimated course datasets (Mach-dependent polars built by flight.aero.FighterAero,
estimated C_Lmax): the sustained turn rate, the stall line and the +9 g limit (Wikipedia: Tejas Mk-1A +9/-3.5, F-16C +9).
A MODEL comparison, not Tejas or F-16 data. Writes img/fig-24-fighters.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, AMBER
import _turns as T
import _fighter as F
from flight import performance as PF, atmosphere as A
from flight.constants import G0

H = 3000.0
A_H = A.speed_of_sound(A.isa(H)[0])
CASES = [("Tejas class", F.TEJ, F.M_REF, MAROON), ("F-16 (Sadraey)", F.F16, F.F16.info["vehicle"]["reference_mass"], BLUE)]
MACH = np.linspace(0.12, 1.5, 700)
RES = {}
for name, v, m, c in CASES:
    vs = T.fighter_stall(v, m, H)
    V = MACH * A_H
    n_s = np.array([float(T.fighter_sustained(v, m, H, M)) for M in MACH])
    n_cl = PF.stall_load_factor(V, vs)
    n_ok = np.minimum(n_s, np.minimum(n_cl, T.N_LIM_FIGHTER))          # what can be held: thrust, lift and 9 g
    sust = PF.turn_rate_radius(V, np.where(n_ok > 1, n_ok, np.nan))[0]
    inst = PF.turn_rate_radius(V, np.minimum(n_cl, T.N_LIM_FIGHTER))[0]
    vc = PF.corner_speed(vs, T.N_LIM_FIGHTER)
    i = np.nanargmax(sust)
    RES[name] = dict(V=V, sust=sust, inst=inst, vs=vs, vc=vc, rate_c=PF.turn_rate_radius(vc, T.N_LIM_FIGHTER)[0],
                     best=(V[i], sust[i], n_ok[i]), wing_loading=m / v.aero.S, clmax=v.aero.clmax(0.0))

if __name__ == "__main__":
    fig, axs = plt.subplots(1, 2, figsize=(11, 4.8), sharey=True)
    fig.subplots_adjust(wspace=0.1)
    d = np.degrees
    for ax, (name, v, m, c) in zip(axs, CASES):
        r = RES[name]
        ax.fill_between(r["V"], 0, d(r["inst"]), color=AMBER, alpha=0.12, lw=0)
        ax.plot(r["V"], d(r["inst"]), color=INK, lw=1.8, ls="--", label="instantaneous: stall or 9 g")
        ax.plot(r["V"], d(r["sust"]), color=c, lw=2.6, label="sustained, full afterburner")
        ax.plot(r["vc"], d(r["rate_c"]), "o", color=INK, ms=8)
        ax.text(r["vc"] + 8, d(r["rate_c"]) + 0.6, f"corner {r['vc']:.0f} m/s, {d(r['rate_c']):.1f}°/s", fontsize=11)
        b = r["best"]
        ax.plot(b[0], d(b[1]), "s", color=c, ms=8)
        ax.text(240, 6.0, f"best sustained (square):\n{d(b[1]):.1f}°/s at {b[0]:.0f} m/s", color=c, fontsize=11, ha="center")
        ax.set_title(f"{name}, {r['wing_loading']:.0f} kg/m²", fontsize=12)
        ax.set_xlabel("airspeed (m/s)"); ax.set_xlim(0, 500); ax.set_ylim(0, 32)
        despine(ax)
    axs[0].set_ylabel("turn rate (deg/s)")
    h, l = axs[0].get_legend_handles_labels()
    fig.legend(h, l, frameon=False, fontsize=11, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 0.0))
    save(fig, "fig-24-fighters")
