"""Lecture 31: height against time for the coast from the assumed 40 km burnout to ISRO's quoted altitudes of three
sounding rockets (_sounding.py), with the time spent above 100 km. Writes img/fig-31-coast.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
import _sounding as S
from flight import rocket as R
from flight.constants import R_EARTH, MU

COLS = [GREEN, BLUE, MAROON]


def coast(apogee, n=400):
    """(t from burnout, height) up and down again to the burnout height."""
    h = np.linspace(S.H_BURNOUT, apogee, n)
    t_up = R.vertical_time_to_apogee(R_EARTH + S.H_BURNOUT, R_EARTH + apogee, MU) - R.vertical_time_to_apogee(R_EARTH + h, R_EARTH + apogee, MU)
    return np.concatenate([t_up, 2 * t_up[-1] - t_up[::-1]]), np.concatenate([h, h[::-1]])


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.2))
    for (name, payload, ha), c in zip(S.ROCKETS, COLS):
        t, h = coast(ha)
        above = S.time_above(S.H_LINE, ha)
        lab = f"{name}: {ha / 1e3:.0f} km" + (f", {above:.0f} s above 100 km" if above else ", never reaches 100 km")
        ax.plot(t, h / 1e3, color=c, lw=2.8, label=lab)
    ax.axhline(100, color=GREY, lw=1.2, ls="--"); ax.text(5, 106, "100 km", fontsize=11.5)
    ax.set_xlim(0, None); ax.set_ylim(40, 660); ax.set_xlabel("time from burnout (s)"); ax.set_ylabel("height (km)")
    ax.legend(frameon=False, fontsize=11.5, loc="upper left")
    despine(ax)
    save(fig, "fig-31-coast")
