"""Lecture 24, specific excess power in a turn at 3 km with full afterburner, for load factors 1, 5 and 9: the Tejas-class
model at 8500 kg (left) and Sadraey's F-16 at 12,331 kg (right), from the partly estimated course datasets with their
Mach-dependent polars (_fighter). The drag at load factor n is that of an aircraft of weight nW, since C_L = nW/(qS);
speeds below the stall at that load factor (C_L > C_Lmax) are not drawn. P_s = (T - D) V / W.
Writes img/fig-24-ps-load.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, GREY
import _fighter as F
from flight import atmosphere as A, performance as PF
from flight.constants import G0

H = 3000.0
SOUND = A.speed_of_sound(A.isa(H)[0])
RHO = A.isa(H)[2]
MACH = np.linspace(0.3, 1.6, 521)
LOADS = [(1, GREEN), (5, BLUE), (9, MAROON)]


def curve(v, m, n):
    W = m * G0
    cl = n * W / (0.5 * RHO * (MACH * SOUND)**2 * v.aero.S)
    ps = np.array([PF.specific_excess_power(F.thrust(v, M, H), F.drag(v, M, n * m, H), M * SOUND, W) for M in MACH])
    return np.where(cl <= v.aero.clmax(0.0), ps, np.nan)


def zero_crossings(ps):
    k = np.where(np.diff(np.sign(ps)) != 0)[0]
    return [float(MACH[i] - ps[i] * (MACH[i + 1] - MACH[i]) / (ps[i + 1] - ps[i])) for i in k
            if np.isfinite(ps[i]) and np.isfinite(ps[i + 1])]


PANELS = []
for name, v, m in (("Tejas-class model", F.TEJ, F.M_REF), ("F-16 (Sadraey)", F.F16, F.F16.info["vehicle"]["reference_mass"])):
    PANELS.append(dict(name=name, v=v, m=m, ps={n: curve(v, m, n) for n, _ in LOADS}))


def ps_at(i, n, M):
    return float(np.interp(M, MACH, PANELS[i]["ps"][n]))


if __name__ == "__main__":
    fig, axs = plt.subplots(1, 2, figsize=(10.5, 5.0), sharey=True)
    fig.subplots_adjust(wspace=0.08)
    for ax, p in zip(axs, PANELS):
        for n, c in LOADS:
            ax.plot(MACH, p["ps"][n], color=c, lw=2.6, label=f"$n$ = {n}")
        ax.axhline(0, color=GREY, lw=1.2)
        ax.set_title(f"{p['name']}, 3 km", fontsize=12)
        ax.set_xlim(0.3, 1.6); ax.set_ylim(-600, 350); ax.set_xlabel("Mach number")
        despine(ax)
    axs[0].set_ylabel("specific excess power $P_s$ (m/s)")
    axs[0].legend(frameon=False, fontsize=12, loc="lower left")
    save(fig, "fig-24-ps-load")
