"""Lecture 25, the Kiran loop of anim-25-kiran-loop on a V-n diagram of the same model: the positive stall line
n = (V_E/V_s)^2 from the dataset's C_Lmax (partly estimated) at 4500 kg and the Surya Kiran team's +6 and -1.5 g with
their top speed of 600 km/h (Wikipedia, "Surya Kiran", read 2026-11-28), and the loop's load factor against its
equivalent airspeed. Writes img/fig-25-loop-on-vn.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY, GREEN
from _scripts import load
from flight import atmosphere as A
from flight.constants import G0

L = load("anim-25-kiran-loop")
TR, K, M = L.TR, L.KIRAN, L.M
RHO = np.array([A.isa(h)[2] for h in TR.h])
VE = TR.V * np.sqrt(RHO / 1.225)
N = TR.load_factor
CLMAX = K.aero.clmax(0.0)
V_S = np.sqrt(2 * M * G0 / (1.225 * K.aero.S * CLMAX))
N_POS, N_NEG, V_TOP = 6.0, -1.5, 600 / 3.6
V_A = V_S * np.sqrt(N_POS)
RATIO = N / VE**2
SPREAD = RATIO.max() / RATIO.min() - 1
PTS = [(0, "entry"), (L.I_TOP, "top"), (len(VE) - 1, "exit")]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    v = np.linspace(0, V_A, 200)
    ax.plot(v, (v / V_S)**2, color=INK, lw=2.4, label=f"stall line, $C_{{L\\max}}$ = {CLMAX}")
    ax.plot([V_A, V_TOP], [N_POS, N_POS], color=INK, lw=2.4)
    ax.plot([0, V_TOP], [N_NEG, N_NEG], color=INK, lw=1.4, ls=":")
    ax.text(45, N_NEG + 0.15, "-1.5 g limit (the inverted stall line is not drawn)", fontsize=10.5, color=GREY)
    ax.plot([V_TOP, V_TOP], [N_NEG, N_POS], color=INK, lw=2.4)
    ax.text(V_TOP - 2, 0.35, "600 km/h", rotation=90, fontsize=10.5, color=INK, ha="right", va="bottom")
    ax.plot(VE, N, color=MAROON, lw=3, label="the loop")
    PLACE = {0: (131, 3.0), L.I_TOP: (89, 0.65), len(VE) - 1: (142, 6.35)}
    for i, lab in PTS:
        ax.plot(VE[i], N[i], "o", color=BLUE, ms=9, zorder=5)
        ax.text(*PLACE[i], f"{lab}: {N[i]:.2f} g,\n{VE[i]:.0f} m/s EAS", fontsize=11, color=BLUE)
    ax.plot(V_A, N_POS, "s", color=GREEN, ms=9)
    ax.text(V_A - 3, N_POS + 0.18, f"corner, {V_A:.0f} m/s", fontsize=11, ha="right", color=GREEN)
    ax.axhline(0, color=GREY, lw=0.8)
    ax.set_xlim(0, 185); ax.set_ylim(-2.2, 7.0)
    ax.set_xlabel("equivalent airspeed (m/s)"); ax.set_ylabel("load factor $n$")
    ax.legend(frameon=False, fontsize=12, loc="upper left")
    despine(ax)
    save(fig, "fig-25-loop-on-vn")
