"""Checks every number and formula in the answers and solutions of 35-synthesis-questions.qmd,
including the guided derivations 4-7.
Run from anywhere:  python3 codes/35-synthesis-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 flight import entry as E, performance as PF
from flight.constants import MU, R_EARTH, G0

PAGE = os.path.join(HERE, "..", "35-synthesis-questions.qmd")
g, r = 9.798, 6378e3


def objective():
    q = Objective(PAGE, 12)
    check("Q1 u", 250**2 / (9.77 * 6389e3), 0.001, tol=5e-5)
    check("Q4 energy height", PF.energy_height(800.0, 50.0), 927.5, tol=0.05)
    q.num(4, 30 * PF.energy_height(800.0, 50.0) / 1e3, "28", x=28, tol=0.5)
    check("Q7 aircraft", np.log(1 / 0.8), 0.223, tol=5e-4)
    check("Q7 stage", np.log(1 / 0.4), 0.916, tol=5e-4)
    check("Q9 sqrt(gr) (km/s)", np.sqrt(g * r) / 1e3, 7.9, tol=0.006)
    q.num(9, np.sqrt(0.5 * g * r) / 1e3, "5.6")
    check("Q10 ratio", -np.log(0.5) / 0.5, 1.386, tol=5e-4)


def drill1():
    for V, u, L in ((100.0, 0.00016, 9.80), (3000.0, 0.144, 8.39), (7000.0, 0.784, 2.12)):
        uu = V**2 / (g * r)
        check(f"D1 u {V}", uu, u, tol=5e-4 if u > 0.01 else 5e-6)
        check(f"D1 lift (kN) {V}", 1000 * E.glide_deceleration(uu, 1.0, g) / 1e3, L, tol=0.006)


def drill2():
    check("D2 from height (km)", 4 * 25.0, 100, tol=1e-9)
    s = 4 * PF.energy_height(0.0, 900.0, g=G0) / 1e3
    check("D2 from speed", s, 165, tol=0.5)
    check("D2 total", 100 + s, 265, tol=0.5)


def extension():
    u = sp.symbols("u")
    sym_zero("E3a series", sp.series(-sp.log(1 - u), u, 0, 3).removeO() - (u + u**2 / 2))
    V = np.sqrt(0.02 * g * r)
    check("E3c speed", V, 1118, tol=0.5)
    truth("E3c above the 590 m/s fighter", V > 590)
    check("E3c exact correction about 1 %", (E.glide_range_angle(0.0, 0.02, 1.0) / (0.02 / 2) - 1) * 100, 1.0, tol=0.02)


def free_cruise():
    """Guided derivation 4: a cruise that needs no fuel."""
    gr = 9.8 * 6.39e6
    check("P4b g r", gr, 6.26e7, rel=0.001)
    for V, u, b in ((236.0, 8.9e-4, 1.0009), (600.0, 0.0057, 1.006), (1500.0, 0.036, 1.037)):
        check(f"P4b u at {V} m/s", V**2 / gr, u)
        check(f"P4b bonus at {V} m/s", 1 / (1 - V**2 / gr), b)
    check("P4c circular speed near the ground (km/s)", np.sqrt(MU / R_EARTH) / 1e3, 7.9)
    W, u, E_, V, c = sp.symbols("W u E V c", positive=True)
    sym_zero("P4a specific range", V / (c * W * (1 - u) / E_) - V * E_ / (c * W * (1 - u)))


def breathing_rocket():
    """Guided derivation 5: an airliner is a rocket that breathes."""
    gg, c, m0, m1, ve, V, Ee, u, t, h, T = sp.symbols("g c m_0 m_1 v_eq V E u t h T", positive=True)
    sym_zero("P5a v_eq = g/c", T / (c * T / gg) - gg / c)
    m = sp.symbols("m", positive=True)
    sym_zero("P5b rocket equation", sp.integrate(ve / m, (m, m1, m0)) - ve * sp.log(m0 / m1))
    tt = Ee * ve * sp.log(m0 / m1) / (gg * (1 - u))                       # time from g(1-u)t/E = v_eq ln
    sym_zero("P5c Breguet", (V * tt).subs(ve, gg / c) - V * Ee / (c * (1 - u)) * sp.log(m0 / m1))
    sym_zero("P5e v_eq = eta h / V", (T * V / ((T / ve) * h)) * h / V - ve)
    G, Vn, En, cn, R = 9.80665, 230.0, 17.0, 0.6 / 3600, 12e6
    vq = G / cn
    check("P5a v_eq (km/s)", vq / 1e3, 58.8, tol=0.05)
    tf = R / Vn
    check("P5d time (s)", tf, 52170, tol=5)
    check("P5d time (h)", tf / 3600, 14.5, tol=0.05)
    check("P5d u", Vn**2 / (9.8 * 6.39e6), "8.4e-4")
    check("P5d rate g/E", G / En, 0.577, tol=5e-4)
    dv = G / En * tf
    check("P5d drag velocity (km/s)", dv / 1e3, 30.1, tol=0.05)
    check("P5d mass ratio", np.exp(dv / vq), 1.67, tol=0.005)
    check("P5d against the PSLV ideal", dv / 9708, 3.1, tol=0.05)
    check("P5d rocket mass ratio", np.exp(dv / 3020), 21000, tol=500)
    check("P5d same as exp(R c/(V E))", np.exp(R * cn / (Vn * En)), np.exp(dv / vq), tol=1e-12)
    check("P5e eta_o", vq * Vn / 42e6, 0.32, tol=0.005)
    check("P5e jet/rocket", vq / 3020, 19, tol=0.5)
    truth("P5e nearly twenty", 18 < vq / 3020 < 20)


def glide_handover():
    """Guided derivation 6: where the entry glide becomes a sailplane's glide."""
    u, H, E_, g, r, w = sp.symbols("u H E g r w", positive=True)
    lnrho = sp.log(1 - u) - sp.log(u)
    sym_zero("P6a dh/du", sp.simplify((-H * sp.diff(lnrho, u)).subs(u, 1 / (1 + w)) - (H / (u * (1 - u))).subs(u, 1 / (1 + w))))
    udot = -(2 / E_) * sp.sqrt(g / r) * (1 - u) * sp.sqrt(u)
    hdot = H / (u * (1 - u)) * udot
    sym_zero("P6a sin gamma", sp.simplify(hdot / sp.sqrt(u * g * r) + 2 * H / (E_ * r * u)))
    vin = lambda uu, E, rH=900.0: 2 * (1 - uu) / (E * (rH * uu * (1 - uu) + (2 - uu)))
    check("P6b limit u->0", vin(1e-12, 4.0), 0.25, tol=1e-9)
    check("P6b u*", 2 / 900, 0.00222, tol=5e-6)
    gr = 9.8 * 6.39e6
    check("P6b gr", gr, "6.262e7")
    check("P6b sqrt(2gH)", np.sqrt(gr / 450), 373, tol=0.5)
    share = lambda uu, rH=900.0: 2 / (rH * uu * (1 - uu) + (2 - uu))
    for uu, V, sh, ga in ((0.5, 5596, 0.009, 0.063), (0.01, 791, 0.18, 2.60), (2 / 900, 373, 0.50, 7.18), (0.0005, 177, 0.82, 11.77)):
        check(f"P6c speed {uu}", np.sqrt(uu * gr), V, tol=0.5)
        check(f"P6c share {uu}", share(uu), sh, tol=0.005 if sh > 0.1 else 5e-4)
        check(f"P6c share = -E sin/(1-u) {uu}", 4.0 * vin(uu, 4.0) / (1 - uu), share(uu), tol=1e-12)
        check(f"P6c angle E=4 {uu}", np.degrees(np.arcsin(vin(uu, 4.0))), ga, tol=0.005)
    check("P6c sailplane angle", np.degrees(np.arcsin(0.25)), 14.48, tol=0.005)


def one_rule():
    """Guided derivation 7: one rule for distance."""
    u = sp.symbols("u", positive=True)
    sym_zero("P7b series", sp.series(sp.log(1 / (1 - u)) / u, u, 0, 2).removeO() - (1 + u / 2))
    check("P7d entry glider", np.log(20) / 0.95, 3.15, tol=0.005)
    eh = 0.322 * 42e6 / 9.80665
    check("P7d fuel energy height (km)", eh / 1e3, 1379, tol=0.5)
    check("P7d airliner range (km)", 17 * eh * np.log(1.668) / 1e3, 12000, tol=10)
    check("P7d mass ratio of problem 5", np.exp(30097.1 / 58839.9), 1.668, tol=5e-4)
    check("P7d eta_o of problem 5", 9.80665 / (0.6 / 3600) * 230 / 42e6, 0.322, tol=5e-4)


if __name__ == "__main__":
    run([objective, drill1, drill2, extension, free_cruise, breathing_rocket, glide_handover, one_rule])
