"""Lecture 21: Hull's business jet at 11,000 lb with full thrust on the speed-altitude chart: the two level-flight
speeds (flight.performance.level_speed_ratios), the 1 g stall, and the airspeeds of the steepest and fastest climbs (_climb.py).
Writes img/fig-21-climb-chart.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
import _climb as C
import _turns
from flight import performance as PF
from flight.constants import FT, G0

V_, W = C.SBJ, C.W_SBJ
H_ABS = float(PF.ceiling(lambda h: C.max_roc(V_, W, h), 0.0, 0.0, 20000.0))
H = np.linspace(0, H_ABS - 0.5, 200)


def speeds(h):
    """(low level speed, steepest, fastest, high level speed), m/s."""
    tau, vs, es = C.scales(V_, W, h)
    u1, u2 = PF.level_speed_ratios(max(tau, 1.0))
    return u1 * vs, vs, PF.fastest_climb_u(tau) * vs, u2 * vs


S = np.array([speeds(h) for h in H])
STALL = np.array([_turns.sbj_stall(h) for h in H])

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    ax.plot(np.where(S[:, 0] >= STALL, S[:, 0], np.nan), H / 1000, color=INK, lw=2.8, label="level flight, full thrust")
    ax.plot(STALL, H / 1000, color=GREY, lw=2.2, ls="--", label="1 g stall")
    ax.plot(np.where(S[:, 0] < STALL, S[:, 0], np.nan), H / 1000, color=INK, lw=1.2, ls=":", label="below the stall: not flyable")
    ax.plot(S[:, 3], H / 1000, color=INK, lw=2.8)
    ax.plot(S[:, 1], H / 1000, color=GREEN, lw=2.6, label="steepest climb")
    ax.plot(S[:, 2], H / 1000, color=MAROON, lw=2.6, label="fastest climb")
    ax.plot(speeds(H_ABS - 0.01)[1], H_ABS / 1000, "o", color=INK, ms=9)
    ax.annotate(f"absolute ceiling {H_ABS / 1000:.2f} km", (speeds(H_ABS - 0.01)[1], H_ABS / 1000), xytext=(14, 6), textcoords="offset points", fontsize=11.5)
    ax.set_ylim(0, 15.5); ax.set_xlim(0, None); ax.set_xlabel("true airspeed (m/s)"); ax.set_ylabel("altitude (km)")
    fig.legend(frameon=False, fontsize=11.5, loc="upper center", ncol=3, bbox_to_anchor=(0.5, 0.02))
    despine(ax)
    save(fig, "fig-21-climb-chart")
