"""Lecture 17: the HANSA-3-class trainer's power required at 2 km (data of fig-15-hansa-power). The least-power point
(best endurance of a propeller aircraft) and the tangent from the origin, whose touching point is the least drag (best
range), with the stall speed. Writes img/fig-17-prop-power-tangent.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load
from flight import performance as PF, atmosphere as A
from flight.constants import KT

H15 = load("fig-15-hansa-power")
H = 2000.0
V_STAR = PF.min_drag_speed(H15.W, A.isa(H)[2], H15.S, H15.CD0, H15.K)
V_MP = H15.v_min_power(H)
V_STALL = H15.v_stall(H)

if __name__ == "__main__":
    V = np.linspace(0.97 * V_STALL, 62.0, 300)
    P = np.array([H15.p_required(v, H) for v in V]) / 1e3
    fig, ax = plt.subplots(figsize=(10, 5.0))
    ax.plot(V, P, color=MAROON, lw=2.8, label="power required, 2 km")
    slope = H15.p_required(V_STAR, H) / 1e3 / V_STAR
    ax.plot([0, 55], [0, 55 * slope], color=BLUE, lw=1.6, ls="--", label="tangent from the origin")
    for v, c, lab, off in ((V_MP, GREEN, "least power:\nlongest endurance", (75, 55)), (V_STAR, BLUE, "least drag:\nlongest range", (75, -50))):
        p = H15.p_required(v, H) / 1e3
        ax.plot(v, p, "o", color=c, ms=9, zorder=5)
        ax.annotate(f"{lab}\n{v:.1f} m/s", (v, p), xytext=off, textcoords="offset points", fontsize=11.5, color=c, ha="center",
                    arrowprops=dict(arrowstyle="-", color=c, lw=1))
    ax.axvline(V_STALL, color=GREY, lw=1.4, ls=":")
    ax.text(V_STALL - 0.8, 24, f"stall, {V_STALL:.1f} m/s", rotation=90, fontsize=11.5, color=INK, ha="right", va="bottom")
    ax.set_xlim(0, 62); ax.set_ylim(0, P.max() * 1.05)
    ax.set_xlabel("true airspeed (m/s)"); ax.set_ylabel("power (kW)")
    ax.legend(frameon=False, fontsize=12, loc="upper left")
    despine(ax)
    save(fig, "fig-17-prop-power-tangent")
