"""Lecture 37: the limits on the CG of Hull's business jet. The forward limit (elevator at -20 deg) against the
largest lift coefficient that must be trimmed, with Hull's Mach 0.6 aerodynamics; the neutral points with the stick
fixed and free; and the CG range Hull gives for the aircraft (shaded). Writes img/fig-37-cg-limits.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK
import _stab as S
from flight import stability as ST

CL = np.linspace(0.6, 1.5, 100)
XNP = ST.neutral_point(S.WING, S.TAIL)
XFREE = ST.neutral_point(S.WING, ST.free_tail(S.TAIL, S.HINGE))
FWD = np.array([ST.forward_cg_limit(c, S.DE_MIN, S.WING, S.TAIL, S.THRUST) for c in CL])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.6))
    ax.axvspan(*S.CG_RANGE, color=BLUE, alpha=0.12)
    ax.text(np.mean(S.CG_RANGE), 0.66, "Hull's CG range", ha="center", fontsize=11, color=BLUE)
    ax.plot(FWD, CL, color=MAROON, lw=2.8)
    ax.text(0.02, 1.38, "forward limit\n(full up elevator, −20°)", fontsize=11, color=MAROON, ha="center")
    for x, lab, c, ls in ((XFREE, "neutral point,\nstick free", AMBER, "--"), (XNP, "neutral point,\nstick fixed", INK, "-")):
        ax.axvline(x, color=c, lw=2.2, ls=ls)
        ax.text(x - 0.006 if c == AMBER else x + 0.006, 0.9 if c == AMBER else 1.15, lab, fontsize=11, color=c, ha="right" if c == AMBER else "left")
    ax.set_xlabel("CG position (fraction of the mean chord)"); ax.set_ylabel("largest $C_L$ to be trimmed")
    ax.set_xlim(-0.15, 0.66); ax.set_ylim(0.6, 1.5)
    despine(ax)
    save(fig, "fig-37-cg-limits")
