"""Lecture 15, the two level-flight speeds: as the thrust ratio tau = T/D* falls from 2.5 to 1, the thrust line meets
the drag curve D/D* = (u^2 + 1/u^2)/2 at a low speed u1 and a high speed u2 (flight.performance.level_speed_ratios),
which merge at u = 1 when tau = 1. Writes img/anim-15-two-speeds.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
from flight import performance as PF

U = np.linspace(0.3, 2.6, 400)
TAUS = np.concatenate([np.linspace(2.5, 1.0, 70)])
SPEEDS = np.array([PF.level_speed_ratios(t) for t in TAUS])

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.9), gridspec_kw=dict(width_ratios=[1.3, 1]))
    fig.subplots_adjust(wspace=0.28, bottom=0.14)

    def frame(k):
        a1.clear(); a2.clear()
        t = TAUS[k]; u1, u2 = SPEEDS[k]
        a1.plot(U, PF.drag_ratio(U), color=MAROON, lw=2.6, label="drag")
        a1.axhline(t, color=BLUE, lw=2, label="thrust")
        a1.plot([u1, u2], [t, t], "o", color=INK, ms=8, zorder=5)
        a1.text(u1, t + 0.12, "$u_1$", ha="center", fontsize=13); a1.text(u2, t + 0.12, "$u_2$", ha="center", fontsize=13)
        a1.set_xlim(0.3, 2.6); a1.set_ylim(0, 3.2); a1.set_xlabel("$u=V/V^*$"); a1.set_ylabel("$D/D^*$, $T/D^*$")
        a1.set_title(f"$\\tau=T/D^*={t:.2f}$:  $u_1={u1:.3f}$,  $u_2={u2:.3f}$", fontsize=13, loc="left")
        a1.legend(frameon=False, fontsize=12, loc="upper center")
        a2.plot(TAUS[:k + 1], SPEEDS[:k + 1, 0], color=GREEN, lw=2.5, label="low speed $u_1$")
        a2.plot(TAUS[:k + 1], SPEEDS[:k + 1, 1], color=BLUE, lw=2.5, label="high speed $u_2$")
        a2.set_xlim(2.55, 0.95); a2.set_ylim(0, 2.4); a2.set_xlabel("$\\tau$ (throttle back $\\rightarrow$)"); a2.set_ylabel("$u$")
        a2.legend(frameon=False, fontsize=12, loc="upper left")
        for a in (a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, len(TAUS), 12, "anim-15-two-speeds", dpi=90, hold=2.5)
