"""Lecture 21, the steepest (minimum-distance) and fastest (minimum-time) climbs of Hull's SBJ from sea level to 35,000 ft
(_climb.py, flight.performance.climb_integrals): altitude against distance (left) and against time (right), with a
hypothetical ridge 2.8 km high, 8 km from the runway. Writes img/anim-21-two-climbs.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREY, INK
import _climb as C
from flight import performance as PF
from flight.constants import FT

HS = np.linspace(0, 35000, 701) * FT
RUNS = {"steepest": (PF.climb_integrals(HS, C.climb_state(C.SBJ, C.W_SBJ, C.STEEPEST)), BLUE),
        "fastest": (PF.climb_integrals(HS, C.climb_state(C.SBJ, C.W_SBJ, C.FASTEST)), MAROON)}
RESULT = {k: (r[0][0][-1], r[0][1][-1], r[0][2][-1]) for k, r in RUNS.items()}      # x (m), t (s), fuel weight (N)
RIDGE_X, RIDGE_H = 8e3, 2800.0
H_AT_RIDGE = {k: float(np.interp(RIDGE_X, r[0][0], HS)) for k, r in RUNS.items()}

if __name__ == "__main__":
    fig, (a0, a1, a2) = plt.subplots(1, 3, figsize=(12, 4.6), gridspec_kw=dict(width_ratios=[0.9, 1.2, 1]))
    fig.subplots_adjust(wspace=0.3, bottom=0.15)
    N = 60
    T_END = max(v[1] for v in RESULT.values())
    TS = np.linspace(0, T_END, N)

    def frame(k):
        for a in (a0, a1, a2):
            a.clear()
        for a in (a0, a1):
            a.fill_between([RIDGE_X / 1e3 - 1.5, RIDGE_X / 1e3, RIDGE_X / 1e3 + 1.5], 0, [0, RIDGE_H / 1e3, 0], color=GREY, alpha=0.5)
        for lab, ((x, t, f), c) in RUNS.items():
            j = min(np.searchsorted(t, TS[k]), len(t) - 1)
            for a in (a0, a1):
                a.plot(x[:j + 1] / 1e3, HS[:j + 1] / 1e3, color=c, lw=2.5,
                       label=f"{lab}: {x[-1] / 1e3:.0f} km, {t[-1] / 60:.2f} min" if a is a1 else None)
                a.plot(x[j] / 1e3, HS[j] / 1e3, "o", color=c, ms=7)
            a2.plot(t[:j + 1] / 60, HS[:j + 1] / 1e3, color=c, lw=2.5)
            a2.plot(t[j] / 60, HS[j] / 1e3, "o", color=c, ms=7)
        a0.set_xlim(0, 12); a0.set_ylim(0, 4.5); a0.set_xlabel("distance (km)"); a0.set_ylabel("altitude (km)")
        a0.set_title("near the ridge", fontsize=12, loc="left")
        a1.set_xlim(0, 85); a1.set_ylim(0, 11.5); a1.set_xlabel("distance (km)")
        a2.set_xlim(0, 10); a2.set_ylim(0, 11.5); a2.set_xlabel("time (min)")
        a1.legend(frameon=False, fontsize=10, loc="lower right")
        a1.set_title(f"{TS[k] / 60:.1f} min", fontsize=12, loc="left")
        for a in (a0, a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 10, "anim-21-two-climbs", dpi=90, hold=2.5)
