"""Lecture 36: the centre of gravity of Hull's business jet moved from 0.15 to 0.65 of the mean chord: above, its
position against the neutral point on the aircraft; below, the pitching-moment line of the whole aircraft, with the
elevator reset at each position so that the aircraft stays in trim at the same angle of attack (Hull's, 2.23 deg). The
line pivots about the trim point from falling through level to rising. Writes img/anim-36-cg.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREEN, INK, GREY
import _stab as S
import _airplane as AP
from flight import stability as ST

XNP = ST.neutral_point(S.WING, S.TAIL)
CG = np.concatenate([np.linspace(0.15, XNP, 50), np.full(14, XNP), np.linspace(XNP, 0.65, 26)])
A = np.linspace(-4, 10, 60)
TRIM = np.radians(2.23)

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10, 6.4), gridspec_kw=dict(height_ratios=[1, 1.6]))
    fig.subplots_adjust(left=0.1, right=0.97, bottom=0.1, top=0.95, hspace=0.12)
    AP.body(a, S.WING.x_ac, S.TAIL.x_ac)
    a.plot([XNP, XNP], [-0.45, 0.45], color=MAROON, lw=2, ls="--")
    a.text(XNP + 0.05, 0.46, "neutral point", color=MAROON, fontsize=11)
    dot, = a.plot([], [], "o", ms=13, mfc="#faf8f2", mec=INK, mew=2, zorder=7)
    tag = a.text(0, -0.40, "CG", ha="center", fontsize=11)
    a.set_xlim(-1.9, S.TAIL.x_ac + 1.1); a.set_ylim(-0.55, 0.65); a.set_aspect("equal"); a.axis("off")
    b.axhline(0, color=INK, lw=0.9); b.axvline(0, color=INK, lw=0.9)
    line, = b.plot([], [], lw=3, color=BLUE)
    b.plot(np.degrees(TRIM), 0, "o", color=INK, ms=9, zorder=5)
    b.annotate("trim", (np.degrees(TRIM), 0), textcoords="offset points", xytext=(6, -16), fontsize=11)
    info = b.text(0.98, 0.95, "", transform=b.transAxes, ha="right", va="top", fontsize=12)
    b.set_xlim(-4, 10); b.set_ylim(-0.25, 0.25); b.set_xlabel("angle of attack (°)"); b.set_ylabel("$C_m$"); despine(b)

    def frame(k):
        x = CG[k]
        cm0, cma, cmd = ST.moment_coefficients(x, S.WING, S.TAIL, S.THRUST)
        cm0 += cmd * ST.elevator_for_zero_moment(TRIM, cm0, cma, cmd)
        sm = ST.static_margin(x, XNP)
        state = "stable" if sm > 0.005 else ("neutral" if sm > -0.005 else "unstable")
        col = {"stable": BLUE, "neutral": GREY, "unstable": MAROON}[state]
        line.set_data(A, cm0 + cma * np.radians(A)); line.set_color(col)
        dot.set_data([x], [0.02]); tag.set_position((x, -0.42))
        info.set_text(f"CG at {x:.2f} c\nstatic margin {sm:+.2f}\n{state}")
    save_anim(fig, frame, len(CG), 12, "anim-36-cg")
