"""Lecture 1, the point-mass model: the first three minutes of the reference PSLV ascent on the course simulator
(flight/missions.py), drawn as the path of one point, with the vehicle's pointing (pitch = gamma + alpha) shown
every 30 s. Writes img/fig-01-pslv-attitude.png."""
import numpy as np
from _visual import plt, save, despine, INK, MAROON, BLUE, GREY
from flight import missions

tr = missions.fly(missions.pslv_c18_like())
ok = tr.t <= 180.0
x, h = tr.downrange[ok] / 1e3, tr.h[ok] / 1e3
pitch = tr.gamma[ok] + tr.alpha[ok]


def rocket(ax, x0, y0, ang, L=11.0, W=2.6, sx=1.0, color=MAROON):
    """A small rocket outline at (x0, y0) pointing at angle ang (rad, from the horizontal); sx corrects for unequal axes."""
    body = np.array([[-L / 2, -W / 2], [L / 2 - 2.5, -W / 2], [L / 2, 0], [L / 2 - 2.5, W / 2], [-L / 2, W / 2]])
    c, s = np.cos(ang), np.sin(ang)
    pts = body @ np.array([[c, s], [-s, c]])
    ax.fill(x0 + pts[:, 0] * sx, y0 + pts[:, 1], color=color, zorder=5)


fig, ax = plt.subplots(figsize=(7, 7))
ax.plot(x, h, color=BLUE, lw=2.4, label="path of the centre of mass")
for tk in (30, 60, 90, 120, 150, 180):
    i = int(np.argmin(abs(tr.t[ok] - tk)))
    rocket(ax, x[i], h[i], pitch[i])
    ax.annotate(f"{tk:.0f} s", (x[i], h[i]), xytext=(14, -16), textcoords="offset points", fontsize=11, color=GREY)
ev = [(t, n) for t, n in tr.events if t <= 180]
for t, n in ev:
    if n.startswith("separation") or n.startswith("jettison"):
        i = int(np.argmin(abs(tr.t[ok] - t)))
        lab = {"separation:PS1 (S139)": "first stage drops", "jettison:payload fairing": "fairing drops"}.get(n)
        if lab:
            ax.annotate(lab, (x[i], h[i]), xytext=(-150, 4), textcoords="offset points", fontsize=11, color=INK,
                        arrowprops=dict(arrowstyle="->", color=GREY))
ax.set_xlabel("distance downrange (km)")
ax.set_ylabel("altitude (km)")
ax.set_aspect("equal")
ax.set_xlim(-12, 135)
ax.set_ylim(-8, 135)
despine(ax)
ax.legend(loc="lower right", fontsize=11, frameon=False)
save(fig, "fig-01-pslv-attitude")
