"""Lecture 31: the return of a payload on a vertical path from the 470 km flight, flown on the course simulator from
100 km with drag only (_entry33.fly, exponential atmosphere) for three HYPOTHETICAL ballistic coefficients, against the
first-order peak deceleration of Lecture 33 at 90 degrees. Left: drag deceleration against height.
Writes img/fig-31-return.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
import _sounding as S
import _entry33 as C
from flight import rocket as R, entry as E
from flight.constants import R_EARTH, MU, G0

APOGEE = S.ROCKETS[2][2]
V100 = float(R.vertical_speed_for_apogee(R_EARTH + S.H_LINE, R_EARTH + APOGEE, MU))
BS = [(100.0, GREEN), (400.0, BLUE), (1600.0, MAROON)]
FORMULA_G = float(E.ballistic_peak_deceleration(V100, np.radians(90.0), C.H)) / G0
RUNS = []
for B, c in BS:
    tr = C.fly(C.glider(0.0, B=B), V100, S.H_LINE, -89.99, h_stop=0.5e3, t_end=1500.0)
    a = tr.drag / tr.m / G0
    i = int(np.argmax(a))
    RUNS.append(dict(B=B, c=c, h=tr.h, a=a, peak=float(a[i]), h_peak=float(tr.h[i])))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.0))
    for r in RUNS:
        ax.plot(r["a"], r["h"] / 1e3, color=r["c"], lw=2.8, label=f"$B$ = {r['B']:.0f} kg/m²: peak {r['peak']:.1f} g at {r['h_peak'] / 1e3:.1f} km")
        ax.plot(r["peak"], r["h_peak"] / 1e3, "o", color=r["c"], ms=8)
    ax.axvline(FORMULA_G, color=INK, lw=1.4, ls="--"); ax.text(FORMULA_G - 0.3, 3, f"first-order peak\n{FORMULA_G:.1f} g", ha="right", fontsize=11.5)
    ax.set_xlim(0, 1.3 * FORMULA_G); ax.set_ylim(0, 112); ax.set_xlabel("drag deceleration ($g_0$)"); ax.set_ylabel("height (km)")
    ax.legend(frameon=False, fontsize=11.5, loc="upper right", bbox_to_anchor=(1.02, 1.04))
    despine(ax)
    save(fig, "fig-31-return")
