"""Lecture 10: equivalent, calibrated and true airspeed, in knots, for two flights from flight.airspeed (ISA, geopotential heights):
the HJT-36 at Mach 0.75 and 9 km, and the HANSA-3 at 96 kt true airspeed and 2000 m. Instrument and position errors
(indicated to calibrated) depend on the aircraft and are not given a number. Writes img/fig-10-speed-ladder.png."""
import numpy as np
from _visual import plt, save, MAROON, BLUE, GREEN, INK, GREY
from flight import airspeed as AS, atmosphere as A
from flight.constants import KT



def at(V, h):
    """EAS, CAS and TAS (m/s) at true airspeed V and ISA geopotential height h (the note's example)."""
    T, p, rho = A.isa(h)
    M = V / A.speed_of_sound(T)
    return dict(M=M, TAS=V, EAS=AS.eas_from_tas(V, rho), CAS=AS.cas_from_impact(p * AS.impact_ratio(M)))


H36 = at(0.75 * A.speed_of_sound(A.isa(9000.0)[0]), 9000.0)
HAN = at(96 * KT, 2000.0)
CASES = [("HJT-36 at 9 km, Mach 0.75", H36), ("HANSA-3 at 2 km, 96 kt true airspeed", HAN)]


def knots(d):
    return d["EAS"] / KT, d["CAS"] / KT, d["TAS"] / KT


if __name__ == "__main__":
    fig, axs = plt.subplots(2, 1, figsize=(10.5, 5.2))
    fig.subplots_adjust(hspace=0.5)
    for ax, (name, d) in zip(axs, CASES):
        e, c, t = knots(d)
        lo, hi = e - 0.16 * (t - e) - 2, t + 0.08 * (t - e) + 1
        ax.plot([lo, hi], [0, 0], color=INK, lw=1.4)
        for x, lab, col, dy in ((e, "EAS", GREEN, -0.55), (c, "CAS", BLUE, 0.4), (t, "TAS", MAROON, -0.55)):
            ax.plot(x, 0, "|", color=col, ms=26, mew=3)
            ax.text(x + (0.02 * (t - e) if lab == "CAS" else 0), dy, f"{lab} {x:.1f} kt", ha="left" if lab == "CAS" else "center", va="center", fontsize=12.5, color=col)
        for x0, x1, y, text in ((c, e, 1.0, f"compressibility: {c - e:.1f} kt"), (e, t, -1.15, f"density: +{t - e:.1f} kt")):
            ax.annotate("", xy=(x1, y), xytext=(x0, y), arrowprops=dict(arrowstyle="-|>", color=GREY, lw=1.8, shrinkA=0, shrinkB=0))
            ax.text((x0 + x1) / 2, y + 0.3 if y > 0 else y - 0.35, text, ha="center", fontsize=11.5)
        ax.annotate("", xy=(c, 0.35), xytext=(e - 0.16 * (t - e) - 1, 0.35), arrowprops=dict(arrowstyle="-|>", color=GREY, lw=1.4, ls="--"))
        ax.text(e - 0.17 * (t - e) - 1.2, 0.35, "from IAS: instrument\nand position errors", ha="right", va="center", fontsize=10.5)
        ax.set_title(name, fontsize=13)
        ax.set_xlim(lo - 0.28 * (t - e), hi); ax.set_ylim(-1.8, 1.55); ax.axis("off")
    save(fig, "fig-10-speed-ladder")
