"""Lecture 33: SRE-1 entering at 8 km/s from 100 km at 5 deg (an assumed angle): the path, and the histories of
deceleration and stagnation heat flux as fractions of their peaks. Writes img/anim-33-entry.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, INK, AMBER
import _entry33 as X
from flight.constants import G0

TR = X.sre(-5.0)
P = X.peaks(TR)
A = TR.drag / TR.m / G0
END = TR.t[np.where(A > 0.02 * P["a"])[0][-1]]
N = 90

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10, 4.6), gridspec_kw=dict(wspace=0.28))
    x = TR.downrange / 1e3
    a.set_xlim(0, x[-1] * 1.03); a.set_ylim(0, 105); a.set_xlabel("distance along the ground (km)"); a.set_ylabel("height (km)")
    b.set_xlim(0, END); b.set_ylim(0, 1.3); b.set_xlabel("time (s)"); b.set_ylabel("fraction of the peak value")
    despine(a); despine(b)
    path, = a.plot([], [], color=INK, lw=2.4); dot, = a.plot([], [], "o", color=AMBER, ms=10)
    l1, = b.plot([], [], color=MAROON, lw=2.4, label=f"heat flux (peak {P['q'] / 1e6:.1f} MW/m²)")
    l2, = b.plot([], [], color=BLUE, lw=2.4, label=f"deceleration (peak {P['a']:.0f} g)")
    b.legend(handles=[l1, l2], frameon=False, fontsize=10, loc="upper right")
    info = a.text(0.97, 0.95, "", transform=a.transAxes, ha="right", va="top", fontsize=11)
    fig.subplots_adjust(left=0.08, right=0.98, bottom=0.15, top=0.97)

    def frame(k):
        t = END * k / (N - 1)
        m = TR.t <= t + 1e-9
        path.set_data(x[m], TR.h[m] / 1e3); dot.set_data([x[m][-1]], [TR.h[m][-1] / 1e3])
        l1.set_data(TR.t[m], TR.heat_flux[m] / P["q"]); l2.set_data(TR.t[m], A[m] / P["a"])
        info.set_text(f"t = {t:.0f} s\nV = {TR.V[m][-1] / 1e3:.2f} km/s")
    save_anim(fig, frame, N, 15, "anim-33-entry")
