"""Lecture 26, the take-off decision drawn on the runway: Hull's SBJ on a hot May afternoon at Mumbai (_takeoff.MUMBAI,
balanced_field), with an engine failing 10 m/s below V_1, at V_1, and 8 m/s above V_1 (below V_LO). For each case, to scale
along the 2871 m runway: where the engine fails, how far the aircraft needs to reach 35 ft if it goes on with one engine
(GO) and to come to rest if it stops after a 3 s reaction (STOP), all measured from the start of the run.
Writes img/fig-26-go-stop-runway.png."""
import numpy as np
from matplotlib.patches import Rectangle
from _visual import plt, save, MAROON, BLUE, INK, GREY
import _takeoff as T
from flight import performance as PF

RHO = T.airfield_state(T.MUMBAI)[2]
B = T.balanced_field(RHO)
LAPSE = (RHO / T.RHO0_SL)**T.A_LAPSE
CASES = []
for dv, lab in ((-10.0, "fails 10 m/s below $V_1$"), (0.0, "fails at $V_1$"), (8.0, "fails 8 m/s above $V_1$")):
    v = B["v1"] + dv
    x_ef, _ = PF.ground_run_numeric(lambda V: T.net_force(V, RHO, T.T_AVG * LAPSE, T.TO), T.M, 0.0, v)
    CASES.append(dict(v=v, label=lab, x_ef=x_ef, go=B["go"](v), stop=B["stop"](v)))
RUNWAY = T.MUMBAI["runway"]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10.5, 5.4))
    for k, cs in enumerate(CASES):
        y = 2 - k
        ax.add_patch(Rectangle((0, y - 0.32), RUNWAY, 0.64, facecolor="#e6e1d6", edgecolor=GREY, lw=1))
        ax.plot([cs["x_ef"], cs["go"]], [y + 0.12, y + 0.12], color=BLUE, lw=6, solid_capstyle="butt")
        ax.plot([cs["x_ef"], cs["stop"]], [y - 0.12, y - 0.12], color=MAROON, lw=6, solid_capstyle="butt")
        ax.plot([cs["x_ef"]] * 2, [y - 0.32, y + 0.32], color=INK, lw=2)
        longer = "GO" if cs["go"] > cs["stop"] else ("STOP" if cs["stop"] > cs["go"] else "equal")
        ax.text(-60, y, f"{cs['label']}\n({cs['v']:.1f} m/s)", ha="right", va="center", fontsize=11)
        ax.text(max(cs["go"], cs["stop"]) + 40, y, f"GO {cs['go']:.0f} m\nSTOP {cs['stop']:.0f} m", va="center", fontsize=11)
    ax.text(CASES[0]["x_ef"], 2.42, "engine fails", ha="center", fontsize=11)
    ax.text(RUNWAY, -0.55, f"end of runway, {RUNWAY:.0f} m", ha="right", fontsize=11, color=GREY)
    ax.plot([], [], color=BLUE, lw=6, label="GO: continue on one engine to 35 ft")
    ax.plot([], [], color=MAROON, lw=6, label="STOP: 3 s, then brake to rest")
    ax.legend(frameon=False, fontsize=11, loc="lower left", bbox_to_anchor=(0.0, -0.32), ncol=2)
    ax.set_xlim(-1250, 3300); ax.set_ylim(-0.7, 2.6); ax.axis("off")
    save(fig, "fig-26-go-stop-runway")
