"""Lecture 22: a zoom climb of the Tejas-class model (8500 kg, full afterburner) on the course simulator (flat-Earth form,
still air) from 11 km at its top level speed there: a 3 g pull-up to 30 deg, then the lift set to hold the path
(n = cos gamma) until the wing can no longer give it (C_L capped at C_Lmax) and the nose falls to level at the top.
The engine model is used far above its proven range. Writes img/anim-22-zoom.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREEN, INK, GREY, AMBER
import _fighter as F
from flight import simulate, eom, atmosphere as A, performance as PF
from flight.constants import G0

V_ = F.TEJ
H0 = 11000.0
M0 = float(max(F.level_machs(V_, F.M_REF, H0)))
V0 = M0 * A.speed_of_sound(A.isa(H0)[0])
TARGET = np.radians(30.0)
CLMAX = float(V_.aero.clmax(0.0))
OPT = eom.Options(gravity="flat")


def law(n_of_gamma):
    def f(s):
        cl = min(n_of_gamma(s.gamma) * s.m * G0 / (s.q * s.aero.S), CLMAX)
        return s.aero.alpha_for_cl(cl, s.mach), 0.0, 1.0
    return f


def at_angle(t, y):
    return y[4] - TARGET


def level(t, y):
    return y[4]


at_angle.terminal, at_angle.direction = True, 1
level.terminal, level.direction = True, -1
P1 = simulate.simulate(V_, dict(h=H0, V=V0, gamma_deg=0.0, chi_deg=0.0, m=F.M_REF), law(lambda g: 3.0), OPT, t_end=100.0, max_step=0.2, form="flat", stops=(at_angle,))
P2 = simulate.simulate(V_, dict(h=float(P1.h[-1]), V=float(P1.V[-1]), gamma_deg=float(np.degrees(P1.gamma[-1])), chi_deg=0.0, m=float(P1.m[-1])),
                       law(np.cos), OPT, t_end=150.0, max_step=0.2, form="flat", stops=(level,))
T = np.concatenate([P1.t, P1.t[-1] + P2.t[1:] - P2.t[0]])
X = np.concatenate([P1.x, P1.x[-1] + P2.x[1:]])
H = np.concatenate([P1.h, P2.h[1:]]); V = np.concatenate([P1.V, P2.V[1:]])
HE = np.array([PF.energy_height(h, v) for h, v in zip(H, V)])
MACH = V / np.array([A.speed_of_sound(A.isa(h)[0]) for h in H])


def free_zoom_height(mach_top):
    """Drag-free, thrust-free height reached at Mach mach_top with the starting energy height (iterated for the speed of sound)."""
    h = H0
    for _ in range(40):
        h = HE[0] - (mach_top * A.speed_of_sound(A.isa(h)[0]))**2 / (2 * G0)
    return float(h)


if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.9))
    fig.subplots_adjust(wspace=0.28, bottom=0.14)
    idx = np.linspace(0, len(T) - 1, 70).astype(int)

    def frame(k):
        i = idx[k]; a.clear(); b.clear()
        a.plot(X[:i + 1] / 1e3, H[:i + 1] / 1e3, color=MAROON, lw=2.8); a.plot(X[i] / 1e3, H[i] / 1e3, "o", color=MAROON, ms=9)
        a.set_xlim(0, X[-1] / 1e3 * 1.05); a.set_ylim(10, 26); a.set_xlabel("distance (km)"); a.set_ylabel("height (km)")
        b.plot(T[:i + 1], HE[:i + 1] / 1e3, color=BLUE, lw=2.6, label="energy height $h_E$")
        b.plot(T[:i + 1], H[:i + 1] / 1e3, color=MAROON, lw=2.6, label="height $h$")
        b.set_xlim(0, T[-1]); b.set_ylim(10, 26); b.set_xlabel("time (s)"); b.set_ylabel("km")
        b.legend(frameon=False, fontsize=11, loc="lower right")
        a.set_title(f"t = {T[i]:.0f} s,  Mach {MACH[i]:.2f}", fontsize=12.5)
        if k == len(idx) - 1:
            a.text(X[-1] / 1e3, H[-1] / 1e3 - 2.0, f"top: {H[-1] / 1e3:.2f} km\nMach {MACH[-1]:.2f}", ha="right", fontsize=12)
        despine(a); despine(b)
        return []

    save_anim(fig, frame, len(idx), 10, "anim-22-zoom", dpi=90, hold=2.5)
