"""Checks every number and formula in the answers and solutions of 27-landing-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/27-landing-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
import sympy as sp
from _verify import check, truth, sym_zero, Objective, run
from _scripts import load
import _takeoff as T
from flight import performance as PF, atmosphere as A
from flight.constants import KT, FT, G0

PAGE = os.path.join(HERE, "..", "27-landing-questions.qmd")
R0 = A.isa(0.0)[2]
C = T.LAND
L = T.landing(R0)
VTD = L["vtd"]


def runv(thrust, V_from, V_to):
    return PF.ground_run(T.W, thrust, C["mu"], R0, T.S, C["cd"], C["cl"], V_to, V_from)


def data():
    check("data W (kN)", T.W / 1e3, 57.83)
    check("data S (m^2)", T.S, 21.55)
    check("data V_TD", VTD, 63.8)
    check("data 1 lb (N)", T.LB, 4.448)


def objective():
    q = Objective(PAGE, 12)
    check("Q3 share of the field length used (%)", 100 / 1.667, 60, tol=0.5)
    hs = PF.landing_transition(VTD, 1.2, C["glide"], C["h"])[1]
    check("Q6 numerator", (VTD * C["glide"])**2, 11.17)
    check("Q6 denominator", 2 * G0 * 0.2, 3.92)
    q.num(6, hs, "2.8")
    check("Q6 C: n = 1.1", PF.landing_transition(VTD, 1.1, C["glide"], C["h"])[1], 5.7)
    V = 180 * KT
    check("Q7 V", V, 92.6)
    check("Q7 a", V**2 / 600, 14.3)
    q.num(7, V**2 / 600 / G0, "1.46")
    G = load("fig-27-ground-run")
    check("Q8 mu .2", G.RUNS[3]["total"], 1336)
    check("Q8 mu .4", G.RUNS[0]["total"], 684)
    q.num(9, 1 / 0.64, "1.56")
    check("Q9 B", 1 / np.sqrt(0.64), 1.25)
    q.num(10, 1.1**2, "1.21")
    check("Q11 dry", G.RUNS[1]["total"], 779)
    check("Q11 reverse", G.RUNS[4]["total"], 467)
    U, V_, m, c1, c2 = sp.symbols("U V m c1 c2", positive=True)
    x = m / (2 * c1) * sp.log((c1 * U**2 + c2) / c2)
    sym_zero("Q12 dx/dU = m U/(c1 U^2 + c2)", sp.simplify(sp.diff(x, U) - m * U / (c1 * U**2 + c2)))
    sym_zero("Q12 x(0) = 0", x.subs(U, 0))
    sym_zero("Q12 limit c1 -> 0", sp.limit(x, c1, 0) - m * U**2 / (2 * c2))


def times():
    ga, h0 = C["glide"], C["h"]
    glide, flare = h0 / (VTD * ga), VTD * ga / (2 * G0 * (C["n"] - 1))
    check("D1 glide time", glide, 4.56)
    check("D1 flare time", flare, 0.85)
    check("D1 air time", glide + flare, 5.41)
    check("D1 = x_tr/V", glide + flare, L["transition"] / VTD, rel=1e-12)
    a0 = C["idle"] - C["mu"] * T.W
    b = 0.5 * R0 * T.S * (C["cd"] - C["mu"] * C["cl"])
    truth("D1 a0 and b negative", a0 < 0 and b < 0)
    c0, c2 = -a0, -b
    check("D1 c0 (kN)", c0 / 1e3, 18.50)
    check("D1 c2", c2, 1.423)
    check("D1 W/g", T.M, 5897, tol=0.5)
    check("D1 sqrt(c0 c2)", np.sqrt(c0 * c2), 162.3)
    check("D1 argument", VTD * np.sqrt(c2 / c0), 0.560)
    tg = PF.ground_run_time(T.W, C["idle"], C["mu"], R0, T.S, C["cd"], C["cl"], 0.0, VTD)
    check("D1 t_g", tg, 23.0)
    check("D1 closed form = integration", tg, L["t_ground"], rel=1e-4)
    check("D1 formula as printed", T.M / np.sqrt(c0 * c2) * np.arctanh(VTD * np.sqrt(c2 / c0)), tg, rel=1e-12)
    check("D1 total time", glide + flare + tg, 28.4)


def reversers():
    rev = 0.4 * T.T_AVG
    check("D2 reverse (lb)", rev / T.LB, 2300, tol=0.5)
    Tr = C["idle"] - rev
    check("D2 net thrust (lb)", Tr / T.LB, -1910, tol=0.5)
    check("D2 from touch-down", runv(Tr, VTD, 0.0), 467)
    vr = 0.8 * VTD
    x1, x2 = runv(C["idle"], VTD, vr), runv(Tr, vr, 0.0)
    check("D2 V_r", vr, 51.1)
    check("D2 x1", x1, 315)
    check("D2 x2", x2, 287)
    check("D2 total", x1 + x2, 602)
    check("D2 cost", x1 + x2 - runv(Tr, VTD, 0.0), 135)


def flare():
    R, g_, h = sp.symbols("R gamma h", positive=True)
    total = R * sp.sin(g_) + (h - 2 * R * sp.sin(g_ / 2)**2) / sp.tan(g_)
    form = h / sp.tan(g_) + R * sp.tan(g_ / 2)
    for gv in (0.05, 0.4, 1.2):
        check(f"E3a identity at gamma = {gv}", float(total.subs({g_: gv, R: 5.0, h: 7.0})), float(form.subs({g_: gv, R: 5.0, h: 7.0})),
              rel=1e-12)
    V, ga, hob, g = 161.95, np.radians(3), 50.0, 32.2
    n = PF.min_flare_load_factor(V, ga, hob, g=g)
    check("E3d n_min", n, 1.022)
    Rm, x2, hr, x3, _, _ = PF.arc_transition(V, n, ga, hob, g=g)
    check("E3b x3 = 0", x3, 0.0, tol=1e-6)
    check("E3b x2 = h/tan(gamma/2)", x2, hob / np.tan(ga / 2), rel=1e-12)
    check("E3d longest", x2, 1909, tol=0.5)
    check("E3d shortest", hob / np.tan(ga), 954, tol=0.5)
    check("E3d ratio", hob / np.tan(ga) / x2, 0.4997, tol=5e-5)
    check("E3c ratio formula", 0.5 * (1 - np.tan(ga / 2)**2), hob / np.tan(ga) / x2, rel=1e-12)
    a = PF.arc_transition(V, 1.15, ga, hob, g=g)
    check("E3d n 1.15", a[1] + a[3], 1096, tol=0.5)


def energy_split():
    """Guided derivation 4: where the energy of a landing goes."""
    from scipy.integrate import quad
    from flight.constants import LBF, LB
    W = 13000 * LBF
    S = 232 * FT**2
    CL, CD, T, mu, rho = 0.5173, 0.07323, 390 * LBF, 0.35, 1.225
    m = W / G0
    V = 209 * FT
    check("P4b m (kg)", m, 5897)
    check("P4b V_td (m/s)", V, 63.7)
    A_ = G0 * (mu - T / W)
    B_ = rho * S * (CD - mu * CL) / (2 * m)
    KE = 0.5 * m * V**2
    check("P4b kinetic energy (MJ)", KE / 1e6, 12.0)
    Ed = quad(lambda v: 0.5 * rho * v * v * S * CD * v / (A_ + B_ * v * v), 0, V)[0]
    Eb = quad(lambda v: mu * (W - 0.5 * rho * v * v * S * CL) * v / (A_ + B_ * v * v), 0, V)[0]
    Et = quad(lambda v: -T * v / (A_ + B_ * v * v), 0, V)[0]
    check("P4b drag share (%)", Ed / KE * 100, 13.5)
    check("P4b brake share (%)", Eb / KE * 100, 97.7)
    check("P4b thrust share (%)", Et / KE * 100, -11.2)
    check("P4a the shares add to one", (Ed + Eb + Et) / KE, 1.0, tol=1e-9)
    vv = sp.symbols("V", positive=True)
    a, b = sp.symbols("A B", positive=True)
    sym_zero("P4a sum of the integrands = m V", sp.simplify(m * (a + b * vv**2) * vv / (a + b * vv**2) - m * vv))


def landing_scaling():
    """Guided derivation 5: landing against take-off at Leh."""
    check("P5c landing ratio", 0.938 / 0.640, 1.47)
    check("P5c take-off ratio", (0.938 / 0.640)**2.2, 2.32)
    check("P5c the note's landing distances", 1594 / 1180, 1.35)


def exponential_flare():
    """Guided derivation 6: the exponential flare."""
    from scipy.integrate import solve_ivp
    t, tau, hs, hb, Vg, gg, ns = sp.symbols("t tau h_s h_b Vg g n_s", positive=True)
    h = (hs + hb) * sp.exp(-t / tau) - hb
    sym_zero("P6a law", sp.diff(h, t) + (h + hb) / tau)
    tTD = tau * sp.log((hs + hb) / hb)
    sym_zero("P6a touch-down", sp.simplify(h.subs(t, tTD)))
    sym_zero("P6a sink at touch-down", sp.simplify(-sp.diff(h, t).subs(t, tTD) - hb / tau))
    sol = sp.solve(sp.Eq(1 + sp.diff(h, t, 2).subs(t, 0).subs(tau, (hs + hb) / Vg) / gg, ns), hs + hb)
    sym_zero("P6c start height", sp.simplify(sol[0] - Vg**2 / (gg * (ns - 1))))
    G, V, gam, n, hd, h0 = 9.80665, 63.8, np.radians(3), 1.2, 0.5, 50 * 0.3048
    sv = V * gam
    check("P6d V gamma", sv, 3.34, tol=0.005)
    S = sv**2 / (G * (n - 1))
    check("P6d h_s + h_b", S, 5.69, tol=0.005)
    ta = S / sv
    check("P6d tau", ta, 1.70, tol=0.005)
    hbn = hd * ta
    check("P6d h_b", hbn, 0.85, tol=0.005)
    hsn = S - hbn
    check("P6d h_s", hsn, 4.84, tol=0.005)
    check("P6d Hull start", sv**2 / (2 * G * (n - 1)), 2.84, tol=0.005)
    truth("P6c h_s exceeds Hull's start since h_b < it", hsn > sv**2 / (2 * G * (n - 1)) > hbn)
    check("P6c h_s + h_b is twice Hull", S / (sv**2 / (2 * G * (n - 1))), 2.0, tol=1e-12)
    tf = ta * np.log(S / hbn)
    check("P6d flare time", tf, 3.23, tol=0.005)
    ev = lambda t_, y: y[0]; ev.terminal = True
    num = solve_ivp(lambda t_, y: [-(y[0] + hbn) / ta], (0, 50), [hsn], events=ev, rtol=1e-12)
    check("P6d flare time by integration", num.t[-1], tf, tol=1e-6)
    check("P6d flare distance", V * tf, 206, tol=0.5)
    check("P6d gamma (rad)", gam, 0.0524, tol=5e-5)
    xg = (h0 - hsn) / gam
    check("P6d glide part", xg, 199, tol=0.5)
    check("P6d total", xg + V * tf, 405, tol=0.5)
    xc = h0 / gam + V**2 * gam / (2 * G * (n - 1))
    check("P6d Hull", xc, 345, tol=0.5)
    check("P6d difference", xg + V * tf - xc, 60, tol=0.5)


def lift_vs_brakes():
    """Guided derivation 7: the wing that fights the brakes."""
    import _takeoff as TK
    from flight import atmosphere as AT
    V, m, c1, c2, Vt = sp.symbols("V m c_1 c_2 V_t", positive=True)
    anti = m / (2 * c1) * sp.log(c2 + c1 * V**2)
    sym_zero("P7c antiderivative", sp.diff(anti, V) - m * V / (c2 + c1 * V**2))
    sym_zero("P7c limit", sp.limit(m / (2 * c1) * sp.log((c2 + c1 * Vt**2) / c2), c1, 0) - m * Vt**2 / (2 * c2))
    R0_ = AT.isa(0.0)[2]
    Lr = TK.landing(R0_)
    cl, cd, mu = TK.LAND["cl"], TK.LAND["cd"], TK.LAND["mu"]
    check("P7 V_TD", Lr["vtd"], 63.83, tol=0.005)
    check("P7 W (kN)", TK.W / 1e3, 57.83, tol=0.005)
    check("P7 idle (kN)", TK.LAND["idle"] / 1e3, 1.735, tol=5e-4)
    check("P7 S", TK.S, 21.55, tol=0.005)
    check("P7 m", TK.M, 5897, tol=0.5)
    check("P7a C_D/C_L", cd / cl, 0.142, tol=5e-4)
    check("P7a mu C_L", mu * cl, 0.1811, tol=5e-5)
    check("P7a C_D - mu C_L", cd - mu * cl, -0.108, tol=5e-4)
    q = 0.5 * R0_ * Lr["vtd"]**2
    check("P7b q", q, 2496, tol=0.5)
    aero = q * TK.S * (cd - mu * cl)
    check("P7b aero (kN)", aero / 1e3, -5.80, tol=0.005)
    brk = mu * TK.W - TK.LAND["idle"]
    check("P7b brakes (kN)", brk / 1e3, 18.5, tol=0.05)
    check("P7b share (%)", -100 * aero / brk, 31, tol=0.5)
    def xg(CL, CD, MU):
        a1 = 0.5 * R0_ * TK.S * (CD - MU * CL); a2 = MU * TK.W - TK.LAND["idle"]
        return TK.M / (2 * a1) * np.log((a2 + a1 * Lr["vtd"]**2) / a2)
    check("P7c clean", xg(cl, cd, mu), 779, tol=0.5)
    check("P7c = note's simulator", xg(cl, cd, mu), Lr["ground"], tol=0.01)
    check("P7c no lift", xg(1e-12, cd, mu), 589, tol=0.5)
    check("P7c spoilers", xg(0.10, 0.10, mu), 595, tol=0.5)
    check("P7c quarter", 1 - xg(1e-12, cd, mu) / xg(cl, cd, mu), 0.25, tol=0.01)
    check("P7d clean", xg(cl, cd, 0.10), 2611, tol=0.5)
    check("P7d spoilers", xg(0.10, 0.10, 0.10), 1952, tol=0.5)
    check("P7d saving (%)", 100 * (1 - xg(0.10, 0.10, 0.10) / xg(cl, cd, 0.10)), 25, tol=0.5)
    check("P7d dry saving (%)", 100 * (1 - xg(0.10, 0.10, mu) / xg(cl, cd, mu)), 24, tol=0.5)


if __name__ == "__main__":
    run([data, objective, times, reversers, flare, energy_split, landing_scaling, exponential_flare, lift_vs_brakes])
