"""Lecture 21: the Kiran model (4950 kg, _climb.py) from sea level to its absolute ceiling. Left: power available TV and
power required DV against true airspeed, the gap shaded and its largest value marked. Right: the greatest rate of climb
built up against altitude. Writes img/anim-21-excess-power.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREEN, INK, GREY
import _climb as C
from flight import performance as PF, atmosphere as A
from flight.constants import FT, G0

W = C.M_KIRAN * G0
CD0, K = C.polar(C.KIRAN)
H_ABS = PF.ceiling(lambda h: C.max_roc(C.KIRAN, W, h), 0.0, 5000.0, 16000.0)
H_SERVICE = PF.ceiling(lambda h: C.max_roc(C.KIRAN, W, h), 100 * FT / 60, 5000.0, 16000.0)
HS = np.linspace(0.0, H_ABS, 60)
V = np.linspace(55.0, 330.0, 400)


def powers(h):
    rho = A.isa(h)[2]
    D = np.add(*PF.level_flight_drag(W, rho, V, C.KIRAN.aero.S, CD0, K))
    return C.thrust(C.KIRAN, h) * V, D * V


def best_gap(h):
    """Largest (T - D) V / W over speed: the greatest rate of climb of the shallow-climb model."""
    pa, pr = powers(h)
    i = int(np.argmax(pa - pr))
    return V[i], (pa[i] - pr[i]) / W


ROC = np.array([C.max_roc(C.KIRAN, W, h) for h in HS])

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.9), gridspec_kw=dict(width_ratios=[1.45, 1]))
    fig.subplots_adjust(wspace=0.26, bottom=0.14)

    def frame(k):
        h = HS[k]; pa, pr = powers(h); a.clear(); b.clear()
        a.plot(V, pa / 1e6, color=BLUE, lw=2.5, label="available, $TV$")
        a.plot(V, pr / 1e6, color=MAROON, lw=2.5, label="required, $DV$")
        a.fill_between(V, pr / 1e6, pa / 1e6, where=pa >= pr, color=GREEN, alpha=0.25)
        v, r = best_gap(h); i = int(np.argmin(abs(V - v)))
        a.plot([v, v], [pr[i] / 1e6, pa[i] / 1e6], color=GREEN, lw=3)
        a.set_xlim(55, 330); a.set_ylim(0, 5.5); a.set_xlabel("true airspeed (m/s)"); a.set_ylabel("power (MW)")
        a.set_title(f"altitude {h / 1e3:.1f} km", fontsize=12.5)
        a.legend(frameon=False, fontsize=11, loc="upper left")
        b.plot(ROC[:k + 1], HS[:k + 1] / 1e3, color=GREEN, lw=2.8); b.plot(ROC[k], h / 1e3, "o", color=GREEN, ms=8)
        b.set_xlim(0, 40); b.set_ylim(0, 14.5); b.set_xlabel("greatest rate of climb (m/s)"); b.set_ylabel("altitude (km)")
        b.set_title(f"{max(ROC[k], 0.0):.1f} m/s", fontsize=12.5)
        if h >= H_SERVICE:
            b.axhline(H_SERVICE / 1e3, color=GREY, lw=1.2, ls="--")
            b.text(39, H_SERVICE / 1e3 - 0.3, f"service ceiling {H_SERVICE / 1e3:.2f} km", ha="right", va="top", fontsize=10.5)
        if k == len(HS) - 1:
            b.text(39, H_ABS / 1e3 + 0.25, f"absolute ceiling {H_ABS / 1e3:.2f} km", ha="right", fontsize=10.5)
        despine(a); despine(b)

    save_anim(fig, frame, len(HS), 10, "anim-21-excess-power", dpi=90, hold=2.5)
