"""Lecture 36: C_malpha of Hull's business jet against the CG position, for the whole aircraft and for the wing-body
alone (_stab.cm_line), with the two neutral points and the static margin at x_cg = 0.30. Writes img/fig-36-cma-cg.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
import _stab as S
from flight import stability as ST

X = np.linspace(0.0, 0.7, 141)


def slope(x, tail=True):
    return float(S.cm_line(x, 1.0, tail=tail, thrust=False) - S.cm_line(x, 0.0, tail=tail, thrust=False))


XNP = ST.neutral_point(S.WING, S.TAIL)
XNP_WB = ST.neutral_point(S.WING)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.0))
    ax.axhspan(-3.0, 0, color="#d8e6d2", zorder=0); ax.axhspan(0, 3.0, color="#e8d7d7", zorder=0)
    ax.plot(X, [slope(x, False) for x in X], color=BLUE, lw=2.8, label="wing and body alone")
    ax.plot(X, [slope(x) for x in X], color=MAROON, lw=2.8, label="with the tail")
    for xn, c in ((XNP_WB, BLUE), (XNP, MAROON)):
        ax.plot(xn, 0, "o", color=c, ms=9, zorder=5)
        ax.annotate(f"neutral point\n{xn:.3f}", (xn, 0), xytext=(-6, 14) if c == BLUE else (8, -34), textcoords="offset points",
                    ha="right" if c == BLUE else "left", fontsize=11.5, color=c)
    ax.annotate("", xy=(XNP, -1.75), xytext=(0.30, -1.75), arrowprops=dict(arrowstyle="<->", color=INK, lw=1.6))
    ax.text((0.30 + XNP) / 2, -1.95, f"static margin at CG 0.30:\n{XNP - 0.30:.3f}", ha="center", va="top", fontsize=11.5)
    ax.plot([0.30, 0.30], [slope(0.30), -1.75], color=GREY, lw=1, ls=":"); ax.plot(0.30, slope(0.30), "o", color=INK, ms=7)
    ax.text(0.69, -2.75, "stable", ha="right", fontsize=12.5); ax.text(0.01, 2.2, "unstable", fontsize=12.5)
    ax.set_xlim(0, 0.7); ax.set_ylim(-3, 2.5); ax.set_xlabel("CG position, in mean chords from its leading edge"); ax.set_ylabel("$C_{m_\\alpha}$ per radian")
    ax.legend(frameon=False, fontsize=11.5, loc="upper center")
    despine(ax)
    save(fig, "fig-36-cma-cg")
