"""Lecture 15: power required and available for the HANSA-3-class trainer (fig-15-hansa-power data and engine model) at
sea level in the standard atmosphere and at Leh on the 25 deg C day of Lecture 9, with the excess power shaded.
Writes img/fig-15-hansa-leh.png."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load
from flight import atmosphere as A, performance as PF

H = load("fig-15-hansa-power")
LEH_DT = 25.0 + 273.15 - A.ISA.standard_tp(3254.0)[0]
H_DA = float(A.density_altitude(A.at_pressure_altitude(3254.0, LEH_DT)[2]))
PLACES = [("sea level, ISA", 0.0), (f"Leh, 25 °C (density altitude {H_DA / 1000:.1f} km)", H_DA)]


def data(h):
    vs = H.v_stall(h)
    V = np.linspace(vs, 65.0, 600)
    req = np.array([H.p_required(v, h) for v in V])
    av = H.p_available(h)
    i = int(np.argmin(req))
    return dict(V=V, req=req, av=av, vstall=vs, excess=float(av - req[i]), vmax=H.v_max(h))


if __name__ == "__main__":
    fig, axs = plt.subplots(1, 2, figsize=(10.5, 4.6), sharey=True, gridspec_kw=dict(wspace=0.08))
    for ax, (lab, h) in zip(axs, PLACES):
        d = data(h)
        ax.plot(d["V"], d["req"] / 1e3, color=MAROON, lw=2.6, label="required")
        ax.axhline(d["av"] / 1e3, color=BLUE, lw=2.4, label="available")
        ax.fill_between(d["V"], d["req"] / 1e3, d["av"] / 1e3, where=d["req"] <= d["av"], color=GREEN, alpha=0.3)
        ax.axvline(d["vstall"], color=GREY, lw=1.2, ls=":")
        ax.set_title(lab, fontsize=12)
        ax.text(45, 4, f"largest excess: {d['excess'] / 1e3:.1f} kW", ha="center", fontsize=12.5)
        ax.set_xlim(20, 65); ax.set_ylim(0, 72); ax.set_xlabel("true airspeed (m/s)"); despine(ax)
    axs[0].set_ylabel("power (kW)"); axs[0].legend(frameon=False, fontsize=11.5, loc="upper left")
    save(fig, "fig-15-hansa-leh")
