"""Checks every number in the answers and solutions of 06-reductions-questions.qmd, including the
simulator experiment of extension 3 and the guided derivations 4-7. Run from anywhere:  python3 codes/06-reductions-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 scipy.optimize import minimize_scalar
from _verify import check, truth, sym_zero, Objective, run
from flight import vehicle, guidance, simulate, eom, frames
from flight.constants import OMEGA_EARTH as W, A_EARTH as R, MU, G0, DEG, J2

PAGE = os.path.join(HERE, "..", "06-reductions-questions.qmd")
gs = MU / R**2


def psi(V0, gam):
    """Free-flight range angle over a sphere (formula of the note)."""
    Q = V0**2 * R / MU
    c = np.cos(gam) ** 2
    return 2 * np.arccos((1 - Q * c) / np.sqrt(1 + Q * (Q - 2) * c))


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    check("data: mu/R^2", gs, 9.798)
    for h in (0.0, 200e3):
        r = R + h
        truth(f"Q3 centrifugal ratio at {h / 1e3:.0f} km in 3.5e-3..3.8e-3",
              3.45e-3 <= W**2 * r / (MU / r**2) <= 3.85e-3)
    check("Q3 flattening ratio", 1.5 * J2, 1.6e-3, tol=5e-5)
    q.num(5, 2 * W * 950 / gs, "0.0141")
    check("Q5 curvature ratio of BrahMos at 952.8 m/s (L1 questions)", 952.8**2 / (G0 * R), 0.0145)
    check("Q5 distractor without 2", W * 950 / gs, 0.0071)
    q.num(6, W * R / 2, "233")
    q.num(7, 2 * W * R, "930")
    r = R + 80e3
    check("Q8 g at 80 km", MU / r**2, 9.557)
    check("Q8 V^2/r", 7000**2 / r, 7.587)
    q.num(8, (MU / r**2 - 7000**2 / r) / (MU / r**2) * 100, "21")
    V = np.sqrt(MU / R)
    q.num(10, R * psi(V, 45 * DEG) / 1e3, r"10\,019", x=10019)
    check("Q10 range angle (deg)", np.degrees(psi(V, 45 * DEG)), 90)
    check("Q10 flat range = R_E (km)", V**2 / gs / 1e3, 6378)
    check("Q10 ratio = pi/2", R * psi(V, 45 * DEG) / (V**2 / gs), np.pi / 2, tol=1e-9)
    Vs, rs, gam, m, D, mu = sp.symbols("V r gamma m D mu", positive=True)
    Vd = -D / m - mu / rs**2 * sp.sin(gam)
    rd = Vs * sp.sin(gam)
    truth("Q11 dE/dt = -D V/m with drag", sp.simplify(Vs * Vd + mu / rs**2 * rd + D * Vs / m) == 0)
    q.num(12, 290**2 / (2 * R / 1e3), "6.6")


def ratio_table():
    """Drill 1: three more vehicles."""
    rows = (("Tejas", 1.6 * 295.15, 11e3, (3.6e-3, 7.1e-3, 3.5e-3, 1.7e-3)),
            ("IRBM", 4000.0, 150e3, (0.26, 0.062, 3.7e-3, 0.024)),
            ("crew module", 7600.0, 120e3, (0.94, 0.12, 3.7e-3, 0.019)))
    check("P1 Tejas speed (m/s)", 1.6 * 295.15, 472, tol=0.5)
    for name, V, h, want in rows:
        r = R + h
        g = MU / r**2
        got = (V**2 / (g * r), 2 * W * V / g, W**2 * r / g, h / R)
        for lab, x, y in zip(("V^2/(gr)", "2wV/g", "w^2r/g", "h/R"), got, want):
            check(f"P1 {name} {lab}", x, y, rel=0.03)
    r = R + 11e3
    g = MU / r**2
    V = 1.6 * 295.15
    truth("P1 Tejas: every ratio below 1e-2", max(V**2 / (g * r), 2 * W * V / g, W**2 * r / g, 11e3 / R) < 0.01)


def ranges():
    """Drill 2: ballistic ranges, flat and spherical."""
    for V0, f, s, pct in ((2000, 408.2, 421.6, 3.3), (4000, 1632.9, 1859.4, 13.9)):
        sf = V0**2 / gs
        ss = R * psi(V0, 45 * DEG)
        check(f"P2 flat range at {V0} m/s (km)", sf / 1e3, f)
        check(f"P2 spherical range at {V0} m/s (km)", ss / 1e3, s)
        check(f"P2 excess at {V0} m/s (%)", (ss / sf - 1) * 100, pct)
    for g_, want in ((35, 1839.9), (40, 1878.7), (45, 1859.4)):
        check(f"P2 4 km/s at {g_} deg (km)", R * psi(4000, g_ * DEG) / 1e3, want)
    res = minimize_scalar(lambda g: -psi(4000, g), bounds=(10 * DEG, 60 * DEG), method="bounded", options=dict(xatol=1e-10))
    check("P2 optimum angle (deg)", np.degrees(res.x), 40.8)
    check("P2 optimum range (km)", R * psi(4000, res.x) / 1e3, 1879.5)


def rotation_push():
    """Extension 3: the eastward Coriolis component, the vertical shot, and the SRBM on the simulator."""
    phi = 8.53 * DEG
    om = W * np.array([0.0, np.cos(phi), np.sin(phi)])            # east, north, up
    VN, VU = 37.0, -12.0
    c = -2 * np.cross(om, np.array([5.0, VN, VU]))
    check("P3 east component formula", c[0], 2 * W * (VN * np.sin(phi) - VU * np.cos(phi)), tol=1e-15)
    t, v0, g, w, p = sp.symbols("t v_0 g omega phi", positive=True)
    xE = sp.integrate(sp.integrate(-2 * w * sp.cos(p) * (v0 - g * t), (t, 0, t)), (t, 0, t))
    truth("P3 x_E(t) = -2 w cos(phi)(v0 t^2/2 - g t^3/6)",
          sp.simplify(xE - (-2 * w * sp.cos(p) * (v0 * t**2 / 2 - g * t**3 / 6))) == 0)
    truth("P3 at t = 2 v0/g: x_E = -(4/3) w cos(phi) v0^3/g^2",
          sp.simplify(xE.subs(t, 2 * v0 / g) + sp.Rational(4, 3) * w * sp.cos(p) * v0**3 / g**2) == 0)
    vE = sp.diff(xE, t)
    truth("P3 the eastward velocity is zero again at landing", sp.simplify(vE.subs(t, 2 * v0 / g)) == 0)
    v = np.sqrt(2 * G0 * 100e3)
    check("P3 v0 for 100 km (m/s)", v, 1400)
    check("P3 flight time (s)", 2 * v / G0, 286)
    check("P3 westward drift at Thumba (km)", 4 / 3 * W * np.cos(phi) * v**3 / G0**2 / 1e3, 2.7)
    srbm = vehicle.load("srbm-representative")
    init = dict(lat_deg=13.7, lon_deg=80.2, h=0.0, V=0.0, gamma_deg=90.0, chi_deg=0.0)
    for kick, miss, apo in ((20, 25.7, 419), (30, 18.1, 365), (40, 11.2, 298)):
        law = guidance.GravityTurn(4.0, kick, 8.0, 0.0)
        a = simulate.simulate(srbm, init, law, eom.Options(heading_at_rest=0.0), t_end=2000, max_step=0.5)
        b = simulate.simulate(srbm, init, law, eom.Options(coriolis=False, centrifugal=False, heading_at_rest=0.0),
                              t_end=2000, max_step=0.5)
        d = frames.great_circle_distance(a.lat[-1], a.lon[-1], b.lat[-1], b.lon[-1])
        check(f"P3 SRBM pitch-over {kick} deg: shift (km)", d / 1e3, miss)
        truth(f"P3 SRBM pitch-over {kick} deg: the shift is to the west", a.lon[-1] < b.lon[-1])
        check(f"P3 SRBM pitch-over {kick} deg: apogee (km)", a.h.max() / 1e3, apo, tol=0.5)


def best_angle():
    """Guided derivation 4: the best angle on a round Earth."""
    Q, g = sp.symbols("Q gamma", positive=True)
    c, s_ = sp.cos(g), sp.sin(g)
    t = Q * s_ * c / (1 - Q * c**2)
    cos_half = (1 - Q * c**2) / sp.sqrt(1 + Q * (Q - 2) * c**2)
    for qv in (0.1, 0.5, 0.9):
        for gv in (0.3, 0.7, 1.2):
            check(f"P4a tan form = data-box form at Q={qv}, gamma={gv}",
                  float(sp.atan(t).subs({Q: qv, g: gv})), float(sp.acos(cos_half).subs({Q: qv, g: gv})), tol=1e-12)
    sym_zero("P4a 1-2Qc^2+Q^2c^2 = (1-Qc^2)^2+Q^2 s^2 c^2",
             1 - 2 * Q * c**2 + Q**2 * c**2 - ((1 - Q * c**2)**2 + Q**2 * s_**2 * c**2))
    ser = sp.series(2 * sp.atan(t), Q, 0, 3).removeO()
    sym_zero("P4b Psi = Q sin2g (1 + Q cos^2 g) + O(Q^3)", ser - Q * sp.sin(2 * g) * (1 + Q * c**2))
    for V, pct_a, pct_e in ((2000, 3.2, 3.3), (4000, 12.8, 13.9)):
        q = V**2 * R / MU
        check(f"P4b bracket at 45 deg, {V} m/s (%)", q / 2 * 100, pct_a)
        check(f"P4b exact excess at {V} m/s (%)", (R * psi(V, 45 * DEG) / (V**2 / gs) - 1) * 100, pct_e)
    d = sp.symbols("delta")
    f = sp.cos(2 * d) * (1 + Q / 2 + Q / 2 * sp.sin(2 * d))
    fp = sp.diff(f, d)
    sym_zero("P4c f'(0) = Q", fp.subs(d, 0) - Q)
    sym_zero("P4c f''(0) = -4 at Q = 0", sp.diff(fp, d).subs({d: 0, Q: 0}) + 4)
    num = sp.numer(sp.together(sp.diff(t, g)))
    sym_zero("P4d numerator of dt/dgamma is Q(cos2g - Q cos^2 g)",
             sp.simplify(num / (Q * (sp.cos(2 * g) - Q * c**2)) - 1) * 0 + sp.simplify(sp.expand_trig(num - Q * (sp.cos(2 * g) - Q * c**2))))
    for V, gw, ga, rng in ((2000, 44.05, 44.08, 421.8), (4000, 40.78, 41.33, 1879.5), (7000, 24.92, None, 8940)):
        q = V**2 * R / MU
        ps = 2 * np.arcsin(q / (2 - q))
        gst = np.pi / 4 - ps / 4
        check(f"P4e Q at {V} m/s", q, {2000: 0.0640, 4000: 0.2560, 7000: 0.7841}[V])
        check(f"P4e exact best angle at {V} m/s (deg)", np.degrees(gst), gw)
        check(f"P4e cos2g* = Q cos^2 g* at {V} m/s", np.cos(2 * gst), q * np.cos(gst)**2, tol=1e-12)
        res = minimize_scalar(lambda x: -psi(V, x), bounds=(0.05, 1.5), method="bounded", options=dict(xatol=1e-12))
        check(f"P4e best angle agrees with a search at {V} m/s (deg)", np.degrees(res.x), np.degrees(gst), tol=1e-4)
        check(f"P4e greatest range at {V} m/s (km)", R * ps / 1e3, rng, tol=0.5 if V == 7000 else None)
        if ga:
            check(f"P4e first-order angle at {V} m/s (deg)", 45 - np.degrees(q / 4), ga)


def east_west():
    """Guided derivation 5: level flight on the rotating sphere."""
    V, r, w, ph, L, g = sp.symbols("V r omega phi L g", positive=True)
    for chi, sgn in ((sp.pi / 2, 1), (-sp.pi / 2, -1)):
        need = g - V**2 / r - 2 * w * V * sp.cos(ph) * sp.sin(chi) - w**2 * r * sp.cos(ph)**2
        sym_zero(f"P5 lift for chi={chi}: g-(V{'+' if sgn > 0 else '-'}wr cos phi)^2/r",
                 need - (g - (V + sgn * w * r * sp.cos(ph))**2 / r))
    sym_zero("P5b difference = 4 w V cos phi", ((V + w * r * sp.cos(ph))**2 - (V - w * r * sp.cos(ph))**2) / r - 4 * w * V * sp.cos(ph))
    r1 = R + 11e3
    g1 = MU / r1**2
    check("P5c g at 11 km", g1, 9.765)
    check("P5c east-west fraction", 4 * W * 230 * np.cos(25 * DEG) / g1, 6.2e-3)
    check("P5c curvature ratio", 230**2 / (g1 * r1), 8.5e-4)
    check("P5c the rotation term is about seven times the curvature", 4 * W * 230 * np.cos(25 * DEG) / (230**2 / r1), 7, tol=0.5)
    r4 = R + 400e3
    vc = np.sqrt(MU / r4)
    check("P5d circular speed at 400 km", vc, 7669)
    check("P5d ground speed at 400 km", W * r4, 494)
    check("P5d east ground-relative", vc - W * r4, 7174)
    check("P5d west ground-relative", vc + W * r4, 8163, tol=1)


def drag_paradox():
    """Guided derivation 6: decay of a near-circular orbit."""
    r, V, gm, m, D, mu, rho, B = sp.symbols("r V gamma m D mu rho B", positive=True)
    rd = V * sp.sin(gm)
    Vd = -D / m - mu / r**2 * sp.sin(gm)
    gd = -(mu / r**2 - V**2 / r) * sp.cos(gm) / V
    hd = rd * V * sp.cos(gm) + r * Vd * sp.cos(gm) - r * V * sp.sin(gm) * gd
    sym_zero("P6a hdot = -D r cos(gamma)/m", hd + D * r * sp.cos(gm) / m)
    Vc = sp.sqrt(mu / r)
    Dm = rho * Vc**2 / (2 * B)
    rdot = -2 * r**2 * Dm * Vc / mu
    sym_zero("P6b rdot = -(rho/B) sqrt(mu r)", rdot + rho / B * sp.sqrt(mu * r))
    sym_zero("P6b drop per rev = 2 pi rho r^2/B", rdot * 2 * sp.pi * sp.sqrt(r**3 / mu) + 2 * sp.pi * rho * r**2 / B)
    sing = rdot / Vc
    sym_zero("P6c sin(gamma) = -rho r/B", sing + rho * r / B)
    sym_zero("P6c Vdot = +D/m", -Dm - mu / r**2 * sing - Dm)
    rr, rh, Bv = R + 400e3, 3e-12, 100.0
    check("P6d rdot (m/s)", -(rh / Bv) * np.sqrt(MU * rr), -1.56e-3)
    check("P6d drop per revolution (m)", 2 * np.pi * rh * rr**2 / Bv, 8.7)
    P = 2 * np.pi * np.sqrt(rr**3 / MU)
    check("P6d period (s)", P, 5554)
    check("P6d revolutions a day", 86400 / P, 15.6)
    check("P6d drop per day (m)", 2 * np.pi * rh * rr**2 / Bv * 86400 / P, 135, tol=1)
    check("P6d flight-path angle (rad)", -rh * rr / Bv, -2.0e-7)


def jacobi():
    """Guided derivation 7: the Jacobi integral of the rotating frame."""
    r, V, gm, ph, chi, w, mu, m, T, D, al = sp.symbols("r V gamma phi chi omega mu m T D alpha", real=True)
    Vd = (T * sp.cos(al) - D) / m - mu / r**2 * sp.sin(gm) + w**2 * r * sp.cos(ph) * (
        sp.sin(gm) * sp.cos(ph) - sp.cos(gm) * sp.sin(ph) * sp.cos(chi))
    rd = V * sp.sin(gm)
    phd = V * sp.cos(gm) * sp.cos(chi) / r
    J = V**2 / 2 - mu / r - w**2 * r**2 * sp.cos(ph)**2 / 2
    Jd = sp.diff(J, V) * Vd + sp.diff(J, r) * rd + sp.diff(J, ph) * phd
    sym_zero("P7a dJ/dt = (T cos(alpha) - D) V/m", Jd - (T * sp.cos(al) - D) * V / m)
    rng = np.random.default_rng(6)
    for k in range(3):
        rv, Vv = rng.normal(size=3) * 7e6, rng.normal(size=3) * 3e3
        om = np.array([0, 0, W])
        VI = Vv + np.cross(om, rv)
        EI = VI @ VI / 2 - MU / np.linalg.norm(rv)
        Hz = np.cross(rv, VI)[2]
        rho_ax = np.hypot(rv[0], rv[1])
        Jn = Vv @ Vv / 2 - MU / np.linalg.norm(rv) - (W * rho_ax)**2 / 2
        check(f"P7b E_I - w H_z = Jacobi (random state {k})", EI - W * Hz, Jn, rel=1e-12)
    phi = 13.72 * DEG
    check("P7c w R_E", W * R, 465.1)
    dV2 = (W * R)**2 * (1 - np.cos(phi)**2)
    check("P7c V2^2 - V1^2", dV2, "1.22e4")
    check("P7c change of speed at 3 km/s", np.sqrt(3000**2 + dV2) - 3000, 2.0)


if __name__ == "__main__":
    run([objective, ratio_table, ranges, rotation_push, best_angle, east_west, drag_paradox, jacobi])
