"""Lecture 22, three ways from sea level at Mach 0.5 to 11 km at Mach 1.5 for the Tejas-class model with full
afterburner (_energy.py): the minimum-time energy path, the minimum-fuel energy path, and a fastest subsonic climb
followed by level acceleration. The aircraft move along their paths in real (energy-method) time, over the P_s map.
Writes img/anim-22-paths.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load

PM = load("fig-22-ps-map")
T_END = max(r[4][-1] for r, _ in PM.PATHS.values())

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    fig.subplots_adjust(bottom=0.13)
    N = 70
    TS = np.linspace(0, T_END, N)

    def frame(k):
        ax.clear()
        cs = ax.contour(PM.MS, PM.HS / 1e3, PM.PS_AB, levels=PM.LEVELS, colors=[GREY], linewidths=0.9)
        ax.clabel(cs, fmt="%d", fontsize=9)
        for lab, (r, c) in PM.PATHS.items():
            t = r[4]
            j = min(np.searchsorted(t, TS[k]), len(t) - 1)
            done = TS[k] >= t[-1]
            ax.plot(r[1][:j + 1], r[2][:j + 1] / 1e3, color=c, lw=2.5,
                    label=f"{lab}: {t[j]:.0f} s, {r[5][j]:.0f} kg" + (" (there)" if done else ""))
            ax.plot(r[1][j], r[2][j] / 1e3, "o", color=c, ms=8)
        ax.plot(1.5, 11, "*", color=INK, ms=14)
        ax.set_xlim(0.2, 2.0); ax.set_ylim(0, 18); ax.set_xlabel("Mach number"); ax.set_ylabel("altitude (km)")
        ax.set_title(f"{TS[k]:.0f} s", fontsize=13, loc="left")
        ax.legend(frameon=False, fontsize=10, loc="lower right")
        for s in ("top", "right"):
            ax.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 10, "anim-22-paths", dpi=90, hold=2.5)
