"""Lecture 18, the level-flight envelope of the Tejas-class fighter at 8500 kg: Mach numbers and ISA altitudes where the
thrust available exceeds the thrust required and the wing can carry the weight (C_L <= C_Lmax), with military thrust
and with full afterburner; the fastest point and the two afterburner ceilings are marked, with the sourced Mach 1.8 and
16 km service ceiling for comparison. Writes img/fig-18-envelope.png."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _fighter as F

V, MASS = F.TEJ, F.M_REF
MS = np.linspace(0.15, 2.2, 360)
HS = np.linspace(0.0, 20000.0, 201)


def excess(h, ab):
    return np.array([[F.tau_a(V, x, hh, ab) - F.tau_r(V, x, MASS, hh) if x >= F.stall(V, MASS, hh) else -1.0 for x in MS]
                     for hh in h])


def n_roots(h, ab=True):
    return len(F.level_machs(V, MASS, h, ab))


def top_mach(h, ab=True):
    r = F.level_machs(V, MASS, h, ab)
    return max(r) if r else 0.0


HGRID = np.linspace(0, 20000, 81)
VMAX = np.array([top_mach(h) for h in HGRID])
H_FASTEST = HGRID[np.argmax(VMAX)]
M_FASTEST = VMAX.max()
M_AT_11 = top_mach(11000.0)
M_MIL_11 = top_mach(11000.0, False)
M_SL = top_mach(0.0)


def ceiling(ab, lo, hi, want):
    """Altitude between lo and hi where the number of level-flight solutions changes from `want` (bisection)."""
    for _ in range(40):
        mid = 0.5 * (lo + hi)
        if n_roots(mid, ab) >= want:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def change(lo, hi, pred):
    """Altitude between lo (pred false) and hi (pred true) where pred becomes true (bisection)."""
    for _ in range(40):
        mid = 0.5 * (lo + hi)
        lo, hi = (lo, mid) if pred(mid) else (mid, hi)
    return 0.5 * (lo + hi)


H_FOUR = change(17000.0, 17500.0, lambda h: n_roots(h) == 4)          # four solutions from here
H_SUBSONIC_CEILING = ceiling(True, 17500.0, 18000.0, 4)
H_SUPERSONIC_CEILING = ceiling(True, 18000.0, 20000.0, 2)
H_MIL_CEILING = ceiling(False, 14000.0, 17000.0, 2)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    ex_ab, ex_mil = excess(HS, True), excess(HS, False)
    ax.contourf(MS, HS / 1e3, ex_ab > 0, levels=[0.5, 1.5], colors=[BLUE], alpha=0.18)
    ax.contour(MS, HS / 1e3, ex_ab, levels=[0], colors=[BLUE], linewidths=2.2)
    ax.contourf(MS, HS / 1e3, ex_mil > 0, levels=[0.5, 1.5], colors=[GREEN], alpha=0.25)
    ax.contour(MS, HS / 1e3, ex_mil, levels=[0], colors=[GREEN], linewidths=2.2)
    ax.plot([F.stall(V, MASS, h) for h in HS], HS / 1e3, color=MAROON, lw=1.8, ls="--")
    ax.text(0.33, 17.3, "stall", color=MAROON, fontsize=12)
    ax.plot(M_FASTEST, H_FASTEST / 1e3, "o", color=INK, ms=8)
    ax.annotate(f"Mach {M_FASTEST:.2f}", (M_FASTEST, H_FASTEST / 1e3), (1.75, 7.5), fontsize=12,
                arrowprops=dict(arrowstyle="->", color=INK))
    ax.axvline(1.8, color=GREY, lw=1.2, ls=":"); ax.text(1.82, 1.0, "Mach 1.8\n(Raol)", fontsize=11, color=GREY)
    ax.axhline(16.0, color=GREY, lw=1.2, ls=":"); ax.text(1.45, 16.2, "service ceiling 16 km", fontsize=11, color=GREY)
    ax.text(0.62, 6.0, "military", color=GREEN, fontsize=13); ax.text(1.28, 12.5, "afterburner", color=BLUE, fontsize=13)
    ax.set_xlim(0.15, 2.2); ax.set_ylim(0, 20); ax.set_xlabel("Mach number"); ax.set_ylabel("altitude (km)")
    despine(ax)
    save(fig, "fig-18-envelope")
