"""Checks every number in the answers and solutions of 17-cruise-wind-propeller-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/17-cruise-wind-propeller-questions-verify.py"""
import os, sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import _paths  # noqa
import numpy as np
from scipy.optimize import brentq
import sympy as sp
from _verify import check, truth, sym_zero, Objective, run
from _scripts import load
from flight import performance as PF, atmosphere as A, aero as AE
from flight.constants import G0, KT, P0_SL, RHO0_SL, FT

PAGE = os.path.join(HERE, "..", "17-cruise-wind-propeller-questions.qmd")


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    sr = PF.specific_ground_range(230, 30, 0.6 / 3600, 40000)
    check("Q5 m/N", sr, 30.0)
    q.num(5, sr * G0, "294")
    check("Q5 distractor tailwind", PF.specific_ground_range(230, -30, 0.6 / 3600, 40000) * G0, 382, tol=0.5)
    q.num(6, PF.range_prop_breguet(0.8, 8e-7, 14, 1.1, 1.0) / 1e3, "1334")
    check("Q6 ln 1.1", np.log(1.1), 0.0953)
    d = PF.optimum_pressure_ratio(600e3, 120, 0.78, 0.55)
    q.num(7, d, "0.21", tol=0.005)
    check("Q7 three figures", d, 0.211)
    check("Q7 pressure altitude (km)", A.pressure_altitude(d * P0_SL) / 1e3, 11.4)
    q.num(8, 60 * 3**-0.25, "45.6")
    check("Q8 distractor", 60 * 3**0.25, 79.0)
    u = PF.best_range_u_wind(0.2)
    q.num(9, u, "1.40")
    check("Q9 6 % above still air", (u / 3**0.25 - 1) * 100, 6, tol=0.5)
    q.num(10, (1 / 0.9 - 1) * 100, "11.1")
    check("Q10 distractor", 0.1 / 1.1 * 100, 9.1)
    s2 = A.isa(2000.0)[2] / RHO0_SL
    check("Q11 sigma", s2, 0.8216)
    q.num(11, (1 - np.sqrt(s2)) * 100, "9.4")
    check("Q11 distractor", (1 - s2) * 100, 17.8)
    q.num(12, 3**0.25, "1.32")


def ferry():
    """Drill 1: a ferry flight from Delhi to Mumbai."""
    check("P1 shortfall (km)", 1139 - 1084, 55, tol=0)
    vs = PF.min_drag_speed(750 * G0, A.isa(2000.0)[2], 12.0, 0.03, 0.0447020256)
    check("P1 V* (m/s)", vs, 38.56)
    check("P1 V* (kt)", vs / KT, 74.95)
    f = (74.95 + 15) / 74.95
    check("P1 factor", f, 1.200)
    check("P1 range (km)", 1084 * f, 1301, tol=0.5)
    check("P1 spare (km)", 1301 - 1139, 162, tol=0)
    check("P1 margin (%)", 162 / 1139 * 100, 14, tol=0.5)
    check("P1 flight time (h)", 1139e3 / ((74.95 + 15) * KT) / 3600, 7, tol=0.2)
    check("P1 15 kt as a fraction of airspeed (%)", 15 / 74.95 * 100, 20, tol=0.5)


def steps():
    """Drill 2: step-climb plan."""
    AL = load("fig-17-altitude")
    dh = AL.h_opt(220) - AL.h_opt(270)
    check("P2 rise (km)", dh / 1e3, 1.30)
    check("P2 rise (ft)", dh / FT, 4261, tol=0.5)
    check("P2 steps", dh / FT / 2000, 2.13)
    check("P2 260 t (km)", AL.h_opt(260) / 1e3, 12.33)
    check("P2 230 t (km)", AL.h_opt(230) / 1e3, 13.11)
    h1 = AL.h_opt(270) + 2000 * FT
    h2 = AL.h_opt(270) + 4000 * FT
    check("P2 first step altitude (km)", h1 / 1e3, 12.70)
    check("P2 second step altitude (km)", h2 / 1e3, 13.31)
    m1 = brentq(lambda m: AL.h_opt(m) - h1, 200, 280)
    m2 = brentq(lambda m: AL.h_opt(m) - h2, 200, 280)
    check("P2 first step mass (t)", m1, 245, tol=1)
    check("P2 second step mass (t)", m2, 222, tol=1)


def wind_speed():
    """Extension 3: the best speed in a headwind."""
    w = 0.2
    f = lambda u: u**5 - 2 * w * u**4 - 3 * u + 2 * w
    u = brentq(f, 1.0, 3.0)
    check("P3 root", u, 1.396)
    check("P3 agrees with the engine", PF.best_range_u_wind(w), u, tol=1e-6)
    g = lambda x: (x - w) / PF.drag_ratio(x)
    check("P3 gain (%)", (g(u) / g(3**0.25) - 1) * 100, 0.5, tol=0.05)
    check("P3 6 % faster", (u / 3**0.25 - 1) * 100, 6, tol=0.5)


def wind_rule():
    """Guided derivation 4: add a third of the headwind."""
    u, w = sp.symbols("u w", real=True)
    cond = 2 * u**3 * ((u - u**-3) * (u - w) - (u**2 + u**-2) / 2)
    F = u**5 - 2 * w * u**4 - 3 * u + 2 * w
    sym_zero("P4a F(u,w)", sp.expand(cond - F))
    u0 = 3**sp.Rational(1, 4)
    sym_zero("P4b du/dw at w=0 = 1/3", (-sp.diff(F, w) / sp.diff(F, u)).subs({w: 0, u: u0}) - sp.Rational(1, 3))
    for wv, ex in ((0.1, 1.353), (0.2, 1.396), (0.4, 1.513), (-0.2, 1.260)):
        check(f"P4c exact at w={wv}", PF.best_range_u_wind(wv), ex)
        check(f"P4c rule at w={wv}", 3**0.25 + wv / 3, {0.1: 1.349, 0.2: 1.383, 0.4: 1.449, -0.2: 1.249}[wv])
    check("P4c error at 0.2 (%)", (1 - (3**0.25 + 0.2 / 3) / PF.best_range_u_wind(0.2)) * 100, 1, tol=0.1)
    check("P4c error at 0.4 (%)", (1 - (3**0.25 + 0.4 / 3) / PF.best_range_u_wind(0.4)) * 100, 4, tol=0.3)


def crossover():
    """Guided derivation 5: where the jet overtakes the propeller."""
    from flight.constants import LBF, HP, LB
    cp = 0.5 * LBF / (HP * 3600)
    check("P5c c_p (1/m)", cp, 8.28e-7)
    check("P5a engine equivalent TSFC agrees", PF.equivalent_tsfc_prop(100.0, 0.85, 0.5 * LB / (HP * 3600)), cp * 100 / 0.85, rel=1e-9)
    c = 0.55 / 3600
    check("P5c c (1/s)", c, 1.528e-4)
    Vx = c * 0.85 / cp
    check("P5c V_x (m/s)", Vx, 157)
    check("P5c V_x (km/h)", Vx * 3.6, 564)
    a7 = A.speed_of_sound(A.isa(7e3)[0])
    check("P5c a at 7 km", a7, 312.3)
    check("P5c Mach", Vx / a7, 0.50)
    import tomllib
    with open(os.path.join(HERE, "..", "data", "vehicles", "atr72-600.toml"), "rb") as fh:
        atr = tomllib.load(fh)
    kt = [v for k, v in atr.items() if isinstance(v, dict) and "cruise_ktas" in v]
    kt = kt[0]["cruise_ktas"] if kt else atr["cruise_ktas"]
    check("P5d ATR 72-600 dataset cruise (kt)", kt, 275)
    check("P5d in km/h", kt * KT * 3.6, 510, tol=1)
    check("P5d ATR 72 (m/s)", 510 / 3.6, 142)


def best_mach():
    """Guided derivation 6: the best cruise Mach number."""
    M, mc, c0 = sp.symbols("M M_cr C_D0", positive=True)
    cdw = 20 * (M - mc)**4
    d = sp.diff(sp.log(M) - sp.log(c0 + cdw) / 2, M)
    sym_zero("P6a condition", sp.simplify(sp.numer(sp.together(d)) / 2 - (c0 + cdw - 40 * M * (M - mc)**3)) * 0 +
             sp.simplify(d * 2 * M * (c0 + cdw) - 2 * (c0 + cdw - 40 * M * (M - mc)**3)))
    cd0, k, mdd = 0.017, 0.04, 0.82
    mcr = AE.critical_from_divergence(mdd)
    check("P6c M_cr", mcr, 0.712)
    f = lambda m: m / (2 * np.sqrt(k * (cd0 + AE.transonic_wave_drag(m, mdd))))
    root = brentq(lambda m: cd0 + 20 * (m - mcr)**4 - 40 * m * (m - mcr)**3, mcr + 1e-6, 0.95)
    check("P6c best Mach", root, 0.795)
    Ms = np.linspace(0.5, 0.95, 45001)
    check("P6c agrees with a search", Ms[np.argmax([f(m) for m in Ms])], root, tol=2e-5)
    check("P6c M E at the best", f(root), 14.84)
    check("P6c M E at M_cr", f(mcr), 13.66)
    check("P6c M E at M_dd", f(mdd), 14.61)


def dodge_wind():
    """Guided derivation 7: descend to dodge a headwind?"""
    s_ = sp.symbols("s", positive=True)
    e = sp.symbols("epsilon", positive=True)
    sym_zero("P7b loss to second order", sp.series(2 * (1 - e) / (1 + (1 - e)**2), e, 0, 3).removeO() - (1 - e**2 / 2))
    H = A.scale_height(216.65)
    check("P7c H", H, 6342, tol=0.5)
    sv = np.exp(-610 / H)
    check("P7c s", sv, 0.908)
    r = 2 * sv / (1 + sv**2)
    check("P7c E/Emax", r, 0.9954)
    check("P7c loss (%)", (1 - r) * 100, 0.46)
    check("P7c V - V_w", 236.1 - 30, 206.1)
    check("P7c break-even reduction (m/s)", 206.1 / r - 206.1, 0.95)
    check("P7c in kt", (206.1 / r - 206.1) / KT, 2, tol=0.2)
    check("P7c 2000 ft (m)", 2000 * FT, 610, tol=0.5)



def earlier_papers():
    """Problems moved from the 2016-2019 papers."""
    import numpy as np
    import sympy as sp
    from flight import atmosphere as At, performance as Pf, aero as Ae
    from flight.constants import FT, KT
    g = 9.80665
    W, A, B = sp.symbols("W A B", positive=True)
    sym_zero("E17 antiderivative", sp.diff(sp.atan(W * sp.sqrt(B / A)) / sp.sqrt(A * B), W) - 1 / (A + B * W**2))
    q, S_, c0, K = sp.symbols("q S C_D0 K", positive=True)
    sym_zero("E17 sqrt(AB)", sp.simplify(sp.sqrt(q * S_ * c0 * K / (q * S_)) - sp.sqrt(K * c0)))

if __name__ == "__main__":
    run([objective, ferry, steps, wind_speed, wind_rule, crossover, best_mach, dodge_wind, earlier_papers])
