"""Lecture 15, power required and power available for the HANSA-3-class trainer (750 kg, Raol & Singh; polar of
fig-12-polar.py; engine of the dataset, 60 kW piston with Gagg and Ferrar lapse and propeller efficiency 0.78, both
ESTIMATED) at sea level, 2 km and 4 km (flight.performance.level_flight_drag, flight.propulsion.Propeller). Marks the
maximum speed and the minimum-power speed at each height. Writes img/fig-15-hansa-power.png."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save, despine, MAROON, BLUE, GREEN, INK, GREY
from _scripts import load
from flight import performance as PF, atmosphere as A, vehicle
from flight.constants import G0, KT, RHO0_SL

P12 = load("fig-12-polar")
W = 750.0 * G0
S, CD0, K, CLMAX = P12.S_H, P12.CD0_H, P12.K_H, P12.CLMAX_H
ENGINE = vehicle.load("hansa-3").stages[0].engine
ALTS = [(0.0, INK), (2000.0, BLUE), (4000.0, GREEN)]


def p_required(V, h):
    rho = A.isa(h)[2]
    d0, di = PF.level_flight_drag(W, rho, V, S, CD0, K)
    return (d0 + di) * V


def p_available(h):
    return ENGINE.eta * ENGINE.power(1.0, A.isa(h)[2] / RHO0_SL)


def v_max(h):
    rho = A.isa(h)[2]
    lo = PF.min_drag_speed(W, rho, S, CD0, K)
    return brentq(lambda v: p_required(v, h) - p_available(h), lo, 150.0)


def v_stall(h):
    return PF.speed_for_cl(W, A.isa(h)[2], S, CLMAX)


def v_min_power(h):
    return PF.U_MIN_POWER * PF.min_drag_speed(W, A.isa(h)[2], S, CD0, K)


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    for h, c in ALTS:
        V = np.linspace(v_stall(h), 75.0, 300)
        ax.plot(V / KT, p_required(V, h) / 1e3, color=c, lw=2.5, label=f"required, {h / 1e3:.0f} km")
        ax.axhline(p_available(h) / 1e3, color=c, lw=1.4, ls="--")
        vm = v_max(h)
        ax.plot(vm / KT, p_available(h) / 1e3, "o", color=c, ms=8)
        ax.text(vm / KT + 0.8, p_available(h) / 1e3 + 0.6, f"{vm / KT:.0f} kt", color=c, fontsize=12)
        vp = v_min_power(h)
        ax.plot(vp / KT, p_required(vp, h) / 1e3, "s", color=c, ms=6)
    ax.text(100, 6, "dashed: available, full throttle", fontsize=11, color=GREY)
    ax.text(100, 3.5, "squares: minimum power required", fontsize=11, color=GREY)
    ax.set_xlim(48, 155); ax.set_ylim(0, 50)
    ax.set_xlabel("true airspeed (kt)"); ax.set_ylabel("power (kW)")
    ax.legend(frameon=False, fontsize=11, loc="lower right", bbox_to_anchor=(1.0, 0.17))
    despine(ax)
    save(fig, "fig-15-hansa-power")
