"""Lecture 12, what the polar means in newtons: the zero-lift drag, the induced drag and the total drag of the
HANSA-3-class trainer (750 kg, Raol & Singh; polar of fig-12-polar.py) in level flight at sea level, from the stall
speed upward (flight.performance.level_flight_drag). Writes img/fig-12-drag-speed.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load
from flight import aero as AE, performance as PF, atmosphere as A
from flight.constants import G0, KT

P = load("fig-12-polar")
W = 750.0 * G0
RHO = A.isa(0.0)[2]
VS = PF.speed_for_cl(W, RHO, P.S_H, P.CLMAX_H)
V = np.linspace(VS, 75.0, 300)
D0, DI = PF.level_flight_drag(W, RHO, V, P.S_H, P.CD0_H, P.K_H)
CLS, EMAX = AE.max_lift_to_drag(P.CD0_H, P.K_H)
VMD = PF.speed_for_cl(W, RHO, P.S_H, CLS)
DMIN = W / EMAX

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    ax.plot(V / KT, D0, color=BLUE, lw=2.3, label="zero-lift drag $D_0\\propto V^2$")
    ax.plot(V / KT, DI, color=GREEN, lw=2.3, label="induced drag $D_i\\propto 1/V^2$")
    ax.plot(V / KT, D0 + DI, color=MAROON, lw=2.8, label="total drag")
    ax.plot(VMD / KT, DMIN, "o", color=MAROON, ms=8)
    ax.plot([VMD / KT] * 2, [0, DMIN], color=GREY, ls=":", lw=1)
    ax.annotate(f"minimum drag {DMIN:.0f} N\nat {VMD / KT:.0f} kt", (VMD / KT, DMIN), (52, 820), color=MAROON, fontsize=12,
                arrowprops=dict(arrowstyle="->", color=MAROON))
    ax.text(VS / KT + 0.5, 1250, f"stall\n{VS / KT:.0f} kt", fontsize=12, color=GREY)
    ax.set_xlim(45, 150); ax.set_ylim(0, 1400)
    ax.set_xlabel("airspeed (kt)"); ax.set_ylabel("drag (N)")
    ax.legend(frameon=False, fontsize=12, loc="upper center")
    despine(ax)
    save(fig, "fig-12-drag-speed")
