"""Lecture 25: the load factor of Sadraey's acrobatic aircraft (data and gust_lines of fig-25-vn.py) flying at V_C
(equivalent airspeed) into the 50 ft/s derived gust, sea level to 20,000 ft, and at the sea-level gust alleviation
factor held fixed. Writes img/fig-25-gust-height.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from _scripts import load
from flight import atmosphere as A
from flight.constants import FT

V25 = load("fig-25-vn")
H_FT = np.linspace(0, 20000, 201)


def at(h_ft):
    """(K_g, mass ratio, n at V_C in the +50 ft/s gust) at pressure height h_ft."""
    kg, mu, out = V25.gust_lines(A.isa(h_ft * FT)[2])
    return kg, mu, out["C"][0]


N = np.array([at(h)[2] for h in H_FT])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.9))
    ax.plot(H_FT / 1000, N, color=MAROON, lw=2.8, label="gust load factor at $V_C$, 50 ft/s gust")
    ax.axhline(V25.NPOS, color=BLUE, lw=2, ls="--", label=f"manoeuvre limit $+${V25.NPOS:.0f}")
    for h in (0, 10000, 20000):
        kg, mu, n = at(h)
        ax.plot(h / 1000, n, "o", color=INK, ms=7)
        ax.annotate(f"$n$ = {n:.2f}\n$K_g$ = {kg:.3f}", (h / 1000, n), xytext=(0, -38), textcoords="offset points",
                    ha="left" if h == 0 else ("right" if h == 20000 else "center"), fontsize=11.5)
    ax.set_xlim(0, 20); ax.set_ylim(min(N.min(), V25.NPOS) - 1.2, max(N.max(), V25.NPOS) + 0.5)
    ax.set_xlabel("altitude (thousands of feet)"); ax.set_ylabel("load factor")
    ax.legend(frameon=False, fontsize=11.5, loc="lower right")
    despine(ax)
    save(fig, "fig-25-gust-height")
