"""Lecture 17, three ways to fly the transport (_transport.py) 4000 km at Mach 0.80 from 270 t: constant altitude
(the best altitude at the start), a continuous cruise-climb at the best altitude (C_L = C_L*), and step climbs of
2000 ft whenever the best altitude is 2000 ft higher (flight levels 2000 ft apart, Filippone sec. 12.7). The specific
range is integrated over the weight (flight.performance); fuel burnt is reported. Writes img/anim-17-steps.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
import _transport as T
from _scripts import load
from flight import performance as PF, atmosphere as A
from flight.constants import G0, FT

AL = load("fig-17-altitude")
RANGE = 4.0e6
STEP = 2000 * FT


def fly(policy, n=4000):
    """March in distance; return arrays of distance, altitude, mass. policy(m, h) gives the altitude to fly."""
    m, x = T.M0, 0.0
    h = AL.h_opt(T.M0 / 1000)
    xs, hs, ms = [0.0], [h], [m]
    dx = RANGE / n
    for _ in range(n):
        h = policy(m / 1000, h)
        t, p, rho = A.isa(h)
        V = T.MACH * A.speed_of_sound(t)
        d0, di = PF.level_flight_drag(m * G0, rho, V, T.S, T.CD0, T.K)
        m -= dx / PF.specific_range(V, T.C, d0 + di) / G0
        x += dx
        xs.append(x); hs.append(h); ms.append(m)
    return np.array(xs), np.array(hs), np.array(ms)


H0 = AL.h_opt(T.M0 / 1000)
POLICIES = {"constant altitude": lambda mt, h: H0,
            "continuous cruise-climb": lambda mt, h: AL.h_opt(mt),
            "2000 ft steps": lambda mt, h: h + STEP if AL.h_opt(mt) >= h + STEP else h}
COLORS = {"constant altitude": MAROON, "continuous cruise-climb": BLUE, "2000 ft steps": GREEN}
RUNS = {k: fly(f) for k, f in POLICIES.items()}
FUEL = {k: (T.M0 - r[2][-1]) / 1000 for k, r in RUNS.items()}

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(11, 5.4))
    fig.subplots_adjust(bottom=0.13, top=0.9)
    N = 80
    idx = np.linspace(0, 4000, N).astype(int)

    def frame(k):
        ax.clear()
        j = idx[k]
        for lab, (x, h, m) in RUNS.items():
            ax.plot(x[:j + 1] / 1e3, h[:j + 1] / FT / 1000, color=COLORS[lab], lw=2.5,
                    label=f"{lab}: {(T.M0 - m[j]) / 1000:.2f} t burnt")
            ax.plot(x[j] / 1e3, h[j] / FT / 1000, "o", color=COLORS[lab], ms=7)
        ax.set_xlim(0, 4100); ax.set_ylim(38, 45)
        ax.set_xlabel("distance (km)"); ax.set_ylabel("altitude (1000 ft)")
        ax.set_title(f"Mach 0.80 from 270 t: {RUNS['2000 ft steps'][0][j] / 1e3:.0f} km flown", fontsize=13, loc="left")
        ax.legend(frameon=False, fontsize=12, loc="upper left")
        for s in ("top", "right"):
            ax.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N, 12, "anim-17-steps", dpi=90, hold=2.5)
