"""Lecture 24, the turn-rate diagram of Hull's SBJ at 20,000 ft and 11,000 lb (Hull Fig. 7.12): the sustained turn rate at
full thrust (P = 0.98), the stall line (C_Lmax = 1.24, Hull eq. 7.55), the limit load factor 4.5 and the speed limits
(300 lb/ft^2 and Mach 0.81, Hull sec. 7.7), with lines of constant radius. The instantaneous corner speed is where the
stall line meets the load-factor limit (Hull eq. 7.57). Writes img/fig-24-doghouse.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY, AMBER
import _turns as T
from flight import performance as PF
from flight.constants import FT

H = 20000 * FT
VS = T.sbj_stall(H)
VC = PF.corner_speed(VS, T.N_LIM_SBJ)
RATE_C = PF.turn_rate_radius(VC, T.N_LIM_SBJ)[0]
V_Q, V_M = T.sbj_limits(H)
V_TOP = min(V_Q, V_M)
V = np.linspace(VS * 1.0005, 300, 1500)
SUST = T.sbj_sustained(H, V)[2]
STALL = PF.turn_rate_radius(V, PF.stall_load_factor(V, VS))[0]
NLIM = PF.turn_rate_radius(V, T.N_LIM_SBJ)[0]
ENV = np.minimum(STALL, NLIM)
# the sustained curve meets the stall line where the full-thrust load factor equals the C_Lmax load factor
i_meet = np.argmax(STALL >= SUST)
V_MEET, RATE_MEET = V[i_meet], SUST[i_meet]
FAST = T.sbj_sustained(H, PF.U_FASTEST_SUSTAINED * T.C.scales(T.SBJ, T.W_SBJ, H)[1])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    d = np.degrees
    m = V <= V_TOP
    ax.fill_between(V[m], 0, d(ENV[m]), color=AMBER, alpha=0.12, lw=0)
    ax.plot(V, d(STALL), color=MAROON, lw=2.0, ls="--")
    ax.plot(V, d(NLIM), color=INK, lw=2.0, ls="--")
    ok = V >= V_MEET
    ax.plot(V[ok], d(SUST[ok]), color=BLUE, lw=2.6)
    ax.plot(V[~ok], d(SUST[~ok]), color=BLUE, lw=1.4, ls=":")
    ax.axvline(V_TOP, color=GREY, lw=1.5)
    for r_km, vv, dy in ((0.5, 128, 0.9), (1.0, 290, -1.6), (2.0, 290, -1.6)):
        ax.plot(V, d(V / (r_km * 1e3)), color=GREY, lw=0.9, ls=":")
        ax.text(vv, d(vv / (r_km * 1e3)) + dy, f"$R$ = {r_km:g} km", color=GREY, fontsize=11, ha="center")
    ax.plot(VC, d(RATE_C), "o", color=INK, ms=9)
    ax.text(VC + 4, d(RATE_C) + 0.6, f"corner: {VC:.0f} m/s, {d(RATE_C):.1f}°/s", fontsize=11)
    ax.plot(V_MEET, d(RATE_MEET), "s", color=BLUE, ms=8)
    ax.text(V_MEET + 6, d(RATE_MEET) - 2.3, f"best sustained: {V_MEET:.0f} m/s, {d(RATE_MEET):.1f}°/s", color=BLUE, fontsize=11)
    ax.text(118, 18.5, "stall ($C_{L\\max}$)", color=MAROON, fontsize=11, ha="right")
    ax.text(240, d(PF.turn_rate_radius(240, T.N_LIM_SBJ)[0]) + 0.6, "$n=4.5$", fontsize=11)
    ax.text(V_TOP - 3, 21.5, "$q_{\\max}$", fontsize=11, ha="right", color=GREY)
    ax.text(200, 3.0, "sustained, full thrust", color=BLUE, fontsize=11)
    ax.set_xlim(60, 300); ax.set_ylim(0, 24)
    ax.set_xlabel("airspeed (m/s)"); ax.set_ylabel("turn rate (deg/s)")
    despine(ax)
    save(fig, "fig-24-doghouse")
