"""Lecture 19, where the Tejas-class model would have to fly for its best lift-to-drag ratio at each Mach number
(omega = omega*, flight.performance.min_drag_wing_loading), at 8500 kg, against its level-flight envelope with
afterburner (fig-18-envelope). Writes img/fig-19-best-altitude.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
import _fighter as F
from _scripts import load
from flight import performance as PF, atmosphere as A
from flight.constants import G0

V, MASS = F.TEJ, F.M_REF
A_ = V.aero
EN = load("fig-18-envelope")
M = np.linspace(0.5, 2.2, 341)


def best_height(x, m=MASS):
    w = PF.min_drag_wing_loading(x, A_.cd0(x), A_.k(x))
    return A.pressure_altitude(2 * m * G0 / (1.4 * A_.S * w))


HB = np.array([best_height(x) for x in M])
H_09, H_15, H_20 = best_height(0.9), best_height(1.5), best_height(2.0)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    ex = EN.excess(EN.HS, True)
    ax.contourf(EN.MS, EN.HS / 1e3, ex > 0, levels=[0.5, 1.5], colors=[BLUE], alpha=0.18)
    ax.contour(EN.MS, EN.HS / 1e3, ex, levels=[0], colors=[BLUE], linewidths=2)
    ax.plot(M, HB / 1e3, color=MAROON, lw=2.6, label="height for $E_{\\max}$, 8500 kg")
    ax.text(1.3, 6, "level flight possible\n(afterburner)", color=BLUE, fontsize=12)
    ax.set_xlim(0.5, 2.2); ax.set_ylim(0, 32); ax.set_xlabel("Mach number"); ax.set_ylabel("altitude (km)")
    ax.legend(frameon=False, fontsize=12, loc="upper left")
    despine(ax)
    save(fig, "fig-19-best-altitude")
