"""Lecture 29, the velocity budget of the reference PSLV ascent (flight.rocket.velocity_budget): the ideal velocity
int T_vac/m dt, the speed actually gained, and between them the losses stacked: gravity, pressure, drag and steering.
Writes img/fig-29-budget.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, PURPLE, INK
import _ascent as AS

_, TR, B = AS.reference()
KEYS = [("gravity", MAROON, "gravity"), ("pressure", AMBER, "nozzle pressure"), ("drag", BLUE, "drag"), ("steering", PURPLE, "steering")]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.0))
    base = TR.V - TR.V[0]
    ax.plot(TR.t, base / 1e3, color=INK, lw=2.4, label="speed gained (relative to the Earth)")
    for k, c, lab in KEYS:
        top = base + B[k + "_t"]
        ax.fill_between(TR.t, base / 1e3, top / 1e3, color=c, alpha=0.8, lw=0, label=f"{lab}: {B[k]:.0f} m/s")
        base = top
    ax.plot(TR.t, B["ideal_t"] / 1e3, color=GREEN, lw=2, ls="--", label=f"ideal: {B['ideal']:.0f} m/s")
    for t, lab in ((105, "PS1 out"), (253, "PS2 out"), (361, "PS3 out"), (785, "PS4 on")):
        ax.axvline(t, color=INK, lw=0.7, ls=":"); ax.text(t - 24, 10.1, lab, fontsize=10, rotation=90, va="top")
    ax.set_xlabel("time (s)"); ax.set_ylabel("velocity (km/s)"); ax.set_xlim(0, TR.t[-1]); ax.set_ylim(0, 10.3)
    fig.legend(frameon=False, fontsize=11, ncol=3, loc="upper center", bbox_to_anchor=(0.5, 0.0))
    despine(ax)
    save(fig, "fig-29-budget")
