"""Lecture 23, ceilings: the greatest rate of climb of Hull's SBJ (11,000 lb) and of the Kiran model (4950 kg) against
altitude, with the rates that define the combat (500 ft/min), cruise (300 ft/min) and service (100 ft/min) ceilings and the
absolute ceiling (zero), after Sadraey sec. 5.6 (left); the time for the SBJ to climb from sea level along its fastest
climb (right), which grows without bound at the absolute ceiling. Writes img/fig-23-ceilings.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
import _climb as C
from flight import performance as PF
from flight.constants import FT, G0

CASES = {"SBJ": (C.SBJ, C.W_SBJ, MAROON), "Kiran": (C.KIRAN, C.M_KIRAN * G0, BLUE)}
THRESH = {"absolute": 0.0, "service": 100 * FT / 60, "cruise": 300 * FT / 60, "combat": 500 * FT / 60}
CEIL = {k: {lab: PF.ceiling(lambda h, v=v, W=W: C.max_roc(v, W, h), th, 0.0, 20000.0) for lab, th in THRESH.items()}
        for k, (v, W, _) in CASES.items()}
H_T = np.linspace(0, CEIL["SBJ"]["absolute"] - 5.0, 1200)
X_T, T_T, F_T = PF.climb_integrals(H_T, C.climb_state(C.SBJ, C.W_SBJ, C.FASTEST))
T_SERVICE = float(np.interp(CEIL["SBJ"]["service"], H_T, T_T))
T_CRUISE = float(np.interp(CEIL["SBJ"]["cruise"], H_T, T_T))

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.9))
    fig.subplots_adjust(wspace=0.3)
    H = np.linspace(0, 14000, 300)
    for k, (v, W, c) in CASES.items():
        a1.plot([C.max_roc(v, W, h) * 60 / FT for h in H], H / 1e3, color=c, lw=2.5, label=k)
    for (lab, th), y in zip(list(THRESH.items())[1:], (10.2, 8.2, 6.2)):
        a1.axvline(th * 60 / FT, color=GREY, lw=1, ls=":")
        a1.text(th * 60 / FT * 1.08, y, f"{lab}\n{th * 60 / FT:.0f} ft/min", fontsize=10, color=INK, va="bottom")
    for k, (v, W, c) in CASES.items():
        a1.axhline(CEIL[k]["absolute"] / 1e3, color=c, lw=1, ls="--")
    a1.set_xscale("log"); a1.set_xlim(50, 20000)
    a1.set_xlabel("greatest rate of climb (ft/min)"); a1.set_ylabel("altitude (km)"); a1.legend(frameon=False, fontsize=11, loc="upper right")
    a2.plot(T_T / 60, H_T / 1e3, color=MAROON, lw=2.5)
    for lab, c in (("service", GREEN), ("absolute", INK)):
        a2.axhline(CEIL["SBJ"][lab] / 1e3, color=c, lw=1.2, ls="--", label=f"{lab} ceiling {CEIL['SBJ'][lab] / FT:,.0f} ft")
    a2.set_xlabel("time to climb, SBJ (min)"); a2.set_xlim(0, 40); a2.legend(frameon=False, fontsize=10, loc="lower right")
    despine(a1); despine(a2)
    save(fig, "fig-23-ceilings")
