"""Lecture 19, specific range of the Tejas-class model at 8500 kg against Mach number at 9, 11 and 13 km: on military
thrust while it suffices (solid), with afterburner beyond (dashed), with the TSFC rising with Mach number
(_fighter.specific_range). Writes img/fig-19-specific-range.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK
import _fighter as F
from flight.constants import G0

V, MASS = F.TEJ, F.M_REF
M = np.linspace(0.4, 1.9, 601)
ALTS = [(9000.0, GREEN), (11000.0, BLUE), (13000.0, MAROON)]


def km_per_100kg(x, h, ab=None):
    return F.specific_range(V, x, MASS, h, ab) * G0 / 1e3 * 100


CURVES = {}
for h, _ in ALTS:
    top = max(F.level_machs(V, MASS, h, False))
    topab = max(F.level_machs(V, MASS, h, True))
    dry = M[M <= top]
    wet = M[(M > top) & (M <= topab)]
    CURVES[h] = (dry, np.array([km_per_100kg(x, h, False) for x in dry]), wet, np.array([km_per_100kg(x, h, True) for x in wet]))
BEST = {h: (c[0][np.argmax(c[1])], c[1].max()) for h, c in CURVES.items()}
SR_15 = km_per_100kg(1.5, 11000.0, True)
SR_105 = km_per_100kg(1.05, 11000.0, False)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5))
    for h, c in ALTS:
        d, sd, w, sw = CURVES[h]
        ax.plot(d, sd, color=c, lw=2.6, label=f"{h / 1e3:.0f} km")
        ax.plot(w, sw, color=c, lw=2.2, ls="--")
        ax.plot(*BEST[h], "o", color=c, ms=7)
    ax.plot([], [], color=INK, lw=2.6, label="military"); ax.plot([], [], color=INK, lw=2.2, ls="--", label="afterburner")
    ax.set_xlabel("Mach number"); ax.set_ylabel("km per 100 kg of fuel"); ax.set_ylim(0, 95)
    ax.legend(frameon=False, fontsize=12, loc="upper right", ncol=2)
    despine(ax)
    save(fig, "fig-19-specific-range")
