"""Lecture 10, the stall speed of a light trainer against altitude: the true stall speed grows as the air thins, the
equivalent stall speed does not change. HANSA-3 class (750 kg from Raol & Singh; wing area 12 m^2 and C_Lmax 1.5
ESTIMATED, as in data/vehicles/hansa-3.toml). From flight.performance.speed_for_cl and flight.airspeed.
Writes img/fig-10-stall-speeds.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, GREEN, INK, GREY
from flight import atmosphere as A, airspeed as AS, vehicle
from flight.performance import speed_for_cl
from flight.constants import G0, KT

V = vehicle.load("hansa-3")
W = V.gross_mass * G0
AERO = V.aero_for(0)
S, CLMAX = AERO.S, AERO.clmax(0.0)
H = np.linspace(0.0, 5000.0, 101)
VS_TAS = np.array([speed_for_cl(W, A.isa(h)[2], S, CLMAX) for h in H])
VS_EAS = np.array([AS.eas_from_tas(v, A.isa(h)[2]) for v, h in zip(VS_TAS, H)])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    ax.plot(VS_TAS / KT, H / 1e3, color=MAROON, lw=2.6, label="true stall speed (TAS)")
    ax.plot(VS_EAS / KT, H / 1e3, color=GREEN, lw=2.6, label="equivalent stall speed (EAS)")
    for h in (0.0, 2500.0, 5000.0):
        k = int(np.argmin(abs(H - h)))
        ax.plot([VS_EAS[k] / KT, VS_TAS[k] / KT], [h / 1e3] * 2, color=GREY, lw=1, ls=":")
        ax.text(VS_TAS[k] / KT + 0.6, h / 1e3, f"{VS_TAS[k] / KT:.1f} kt", va="center", fontsize=12, color=MAROON)
    ax.text(VS_EAS[0] / KT - 0.6, 4.55, f"equivalent stall speed (EAS)\n{VS_EAS[0] / KT:.1f} kt at every height", ha="right", fontsize=12, color=GREEN)
    ax.text(56.0, 1.0, "true stall speed (TAS)", fontsize=12, color=MAROON)
    ax.set_xlim(36, 68)
    ax.set_ylim(-0.2, 5.3)
    ax.set_xlabel("stall speed (kt)")
    ax.set_ylabel("altitude (km)")
    despine(ax)
    save(fig, "fig-10-stall-speeds")
