"""Lecture 29, the first 150 s of the reference PSLV ascent (flight.missions.pslv_c18_like) against time:
the flight-path angle; the angle of attack; dynamic pressure q and the bending-load measure q|alpha|. Shaded: the
vertical rise (0-12 s) and the pitch-over (12-27 s); after it the vehicle flies a gravity turn. Writes img/fig-29-phases.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY, AMBER
from flight import missions

TR = missions.fly(missions.pslv_c18_like(), t_end=150.0)
_, U = np.unique(TR.t, return_index=True)                  # drop repeated samples at stage events
T, H, V = TR.t[U], TR.h[U] / 1e3, TR.V[U]
GAM, ALPHA = np.degrees(TR.gamma[U]), np.degrees(TR.alpha[U])
Q, QA = TR.q[U] / 1e3, TR.q[U] * np.abs(np.degrees(TR.alpha[U])) / 1e3
T_VERT, T_PITCH = 12.0, 27.0
I_QMAX, I_QA = int(np.argmax(Q)), int(np.argmax(QA))
BURNOUT = next(t for t, name in TR.events if name == "burnout")
ALPHA_AFTER = float(np.max(np.abs(ALPHA[T > T_PITCH + 0.5])))

if __name__ == "__main__":
    fig, axs = plt.subplots(3, 1, figsize=(10, 8.4), sharex=True)
    fig.subplots_adjust(hspace=0.12)
    a, b, c = axs
    for ax in axs:
        ax.axvspan(0, T_VERT, color=GREY, alpha=0.18)
        ax.axvspan(T_VERT, T_PITCH, color=AMBER, alpha=0.18)
        ax.axvline(T[I_QMAX], color=GREY, lw=1, ls="--")
        ax.axvline(BURNOUT, color=GREY, lw=1, ls=":")
    a.plot(T[T > 0.5], GAM[T > 0.5], color=BLUE, lw=2.6, label="flight-path angle $\\gamma$")
    a.set_ylabel("$\\gamma$ (deg)"); a.set_ylim(0, 100)
    a.text(6, 6, "vertical rise", rotation=90, ha="center", va="bottom", fontsize=11)
    a.text(19.5, 6, "pitch-over", rotation=90, ha="center", va="bottom", fontsize=11)
    a.text(40, 20, "gravity turn", fontsize=11)
    a.text(T[I_QMAX] + 1.5, 90, "max $q$", fontsize=10.5, color=GREY)
    a.text(BURNOUT - 1.5, 90, "PS1 burnout", fontsize=10.5, color=GREY, ha="right")
    b.plot(T, ALPHA, color=MAROON, lw=2.6)
    b.set_ylabel("angle of attack (deg)"); b.set_ylim(-0.3, 1.8)
    c.plot(T, Q, color=INK, lw=2.4, label="$q$ (kPa)")
    c.plot(T, QA, color=MAROON, lw=2.4, label="$q\\,|\\alpha|$ (kPa·deg)")
    c.set_ylim(0, 45); c.set_xlim(0, 150); c.set_xlabel("time after lift-off (s)")
    c.legend(frameon=False, fontsize=11, loc="upper right")
    for ax in axs:
        despine(ax)
    save(fig, "fig-29-phases")
