"""Lecture 22: the energy-share factor along the 280 kt calibrated airspeed, then Mach 0.78 climb schedule, standard
atmosphere, sea level to 12 km (flight.performance.energy_share_factor, flight.airspeed). Writes
img/fig-22-share-schedule.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import performance as PF, airspeed as AS, atmosphere as A
from flight.constants import KT

VC, MACH = 280 * KT, 0.78
H_X = AS.crossover_altitude(VC, MACH)


def tas(h, seg):
    a = A.speed_of_sound(A.isa(h)[0])
    return (AS.mach_at_cas(VC, h) if seg == "cas" else MACH) * a


def factor(h):
    """Energy-share factor at height h on the schedule (one-sided at the crossover and the tropopause)."""
    seg = "cas" if h < H_X else "mach"
    return PF.energy_share_factor(lambda z: tas(z, seg), h)


SEGMENTS = [(np.linspace(10, H_X - 2, 200), MAROON, "280 kt calibrated"),
            (np.linspace(H_X + 2, 10995, 80), BLUE, "Mach 0.78, below 11 km"),
            (np.linspace(11005, 12000, 60), INK, "Mach 0.78, above 11 km")]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    for hh, c, lab in SEGMENTS:
        ax.plot([factor(h) for h in hh], hh / 1e3, color=c, lw=3, label=lab)
    ax.axvline(1.0, color=GREY, lw=1.2, ls="--")
    for h, text in ((H_X, f"crossover {H_X / 1e3:.2f} km"), (11000.0, "tropopause")):
        ax.axhline(h / 1e3, color=GREY, lw=0.9, ls=":")
        ax.text(0.745, h / 1e3 + 0.12, text, fontsize=11.5)
    for h in (6000.0, 10500.0):
        ax.plot(factor(h), h / 1e3, "o", color=INK, ms=8, zorder=5)
        ax.annotate(f"{factor(h):.3f}", (factor(h), h / 1e3), xytext=(9, -14), textcoords="offset points", fontsize=12)
    ax.text(0.995, 7.6, "some power goes\ninto speed", ha="right", fontsize=11.5)
    ax.text(1.008, 7.6, "slowing down\nadds to the climb", ha="left", fontsize=11.5)
    ax.set_xlim(0.74, 1.14); ax.set_ylim(0, 12.3); ax.set_xlabel("energy-share factor"); ax.set_ylabel("altitude (km)")
    ax.legend(frameon=False, fontsize=11.5, loc="lower right")
    despine(ax)
    save(fig, "fig-22-share-schedule")
