"""Lecture 25, a whole weightless parabola: a pull-up at 2 g from level flight to 45 deg, the zero-g arc entered at
173 m/s, and a 2 g pull-out back to level, all with thrust equal to drag (flight.performance.pull_arc_speed,
zero_g_arc). Height (above the start) and load factor against time. Writes img/fig-25-parabola-n.png."""
import numpy as np
from scipy.integrate import cumulative_trapezoid
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import performance as PF
from flight.constants import G0

N, GAM0 = 2.0, np.radians(45.0)
T_ZERO = 25.0
V0 = G0 * T_ZERO / (2 * np.sin(GAM0))


def pull(sign=1, npts=2001):
    """Pull-up from level to 45 deg: arrays t, gamma, V, h (h from the level start)."""
    g = np.linspace(0.0, GAM0, npts)
    V = PF.pull_arc_speed(g, N, V0, GAM0)
    dt_dg = V / (G0 * (N - np.cos(g)))
    t = np.concatenate([[0], cumulative_trapezoid(dt_dg, g)])
    h = np.concatenate([[0], cumulative_trapezoid(V * np.sin(g) * dt_dg, g)])
    return t, g, V, h


tu, gu, Vu, hu = pull()
T_PULL, H_PULL, V_ENTRY = tu[-1], hu[-1], Vu[0]
tz = np.linspace(0, T_ZERO, 500)
_, hz, Vz, gz = PF.zero_g_arc(V0, GAM0, tz)
T_ALL = np.concatenate([tu, T_PULL + tz, T_PULL + T_ZERO + (T_PULL - tu[::-1])])
H_ALL = np.concatenate([hu, H_PULL + hz, hu[::-1]])
N_ALL = np.concatenate([np.full(len(tu), N), np.zeros(len(tz)), np.full(len(tu), N)])
H_TOP = H_ALL.max()

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10, 6.0), sharex=True, gridspec_kw=dict(height_ratios=[1.6, 1]))
    fig.subplots_adjust(hspace=0.12)
    a.plot(T_ALL, H_ALL / 1e3, color=MAROON, lw=2.8)
    b.plot(T_ALL, N_ALL, color=BLUE, lw=2.8)
    for ax in (a, b):
        ax.axvspan(T_PULL, T_PULL + T_ZERO, color="#f3e3c3", zorder=0); despine(ax)
    mid = T_PULL + T_ZERO / 2
    a.text(mid, 0.35, f"weightless, {T_ZERO:.0f} s", ha="center", fontsize=12.5)
    a.annotate(f"top: {H_TOP / 1e3:.2f} km above the start", (mid, H_TOP / 1e3), xytext=(0, 9), textcoords="offset points", ha="center", fontsize=11.5)
    a.annotate(f"nose up 45°,\n{V0:.0f} m/s", (T_PULL, H_PULL / 1e3), xytext=(-85, 20), textcoords="offset points", ha="center", fontsize=11.5,
               arrowprops=dict(arrowstyle="-", color=INK, lw=1))
    a.set_ylabel("height gained (km)"); a.set_ylim(0, H_TOP / 1e3 * 1.22); b.set_ylim(-0.25, 2.5); b.set_yticks([0, 1, 2])
    b.set_ylabel("load factor"); b.set_xlabel("time (s)"); b.set_xlim(0, T_ALL[-1])
    b.text(T_PULL / 2, 2.15, "pull-up", ha="center", fontsize=11.5); b.text(T_ALL[-1] - T_PULL / 2, 2.15, "pull-out", ha="center", fontsize=11.5)
    save(fig, "fig-25-parabola-n")
