"""Checks every number in the answers and solutions of 05-general-equations-questions.qmd.

The terms of the general equations are computed independently of the scalar formulas: the vector
gravity (J2), Coriolis and centrifugal accelerations and the turning of the local horizon are
projected on e_V, n_gamma and n_chi. Run from anywhere:
    python3 codes/05-general-equations-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 _verify import check, truth, Objective, run
from flight import frames, gravity
from flight.constants import OMEGA_EARTH as W, A_EARTH as R, MU, G0, DEG

PAGE = os.path.join(HERE, "..", "05-general-equations-questions.qmd")
OM = np.array([0.0, 0.0, W])


def terms(h, V, gam, chi, lat, lon=0.0):
    """Gravity, curvature, Coriolis and centrifugal parts of (V_dot, V gamma_dot, V cos(gamma) chi_dot), from the
    engine's vector projection (flight.eom.term_breakdown), with short keys."""
    from flight.eom import term_breakdown
    t = term_breakdown(R + h, lat, lon, V, gam, chi)
    return dict(grav=t["gravity"], curv=t["curvature"], cor=t["coriolis"], cen=t["centrifugal"])


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    t = terms(0.0, 7000.0, 0.0, 90 * DEG, 0.0)
    q.num(5, t["cor"][1], "1.02")
    check("Q5 share of g (%)", t["cor"][1] / G0 * 100, 10, tol=0.5)
    t = terms(0.0, 250.0, 0.0, 0.0, 30 * DEG)
    q.num(6, t["cor"][2], "0.0182")
    check("Q6 distractor with cos(phi)", 2 * W * 250 * np.cos(30 * DEG), 0.0316)
    t = terms(1.0, 300.0, 90 * DEG - 1e-9, 0.0, 0.0)
    truth("Q9 Coriolis has no component along the velocity (random states)",
          all(abs(terms(h, V, g_ * DEG, c * DEG, p * DEG)["cor"][0]) < 1e-12
              for h, V, g_, c, p in ((1e4, 250, 3, 40, 20), (1e5, 3000, 30, 200, -35), (4e5, 7700, -5, 310, 60))))
    t = terms(0.0, 300.0, 90 * DEG, 0.0, 0.0)
    q.num(10, t["cen"][0], "0.0339")
    te, tw = terms(0.0, 250.0, 0.0, 90 * DEG, 0.0), terms(0.0, 250.0, 0.0, 270 * DEG, 0.0)
    check("Q11 eastbound Coriolis", te["cor"][1], 0.0365)
    check("Q11 westbound Coriolis", tw["cor"][1], -0.0365)
    check("Q11 difference", te["cor"][1] - tw["cor"][1], 0.0729)
    q.num(11, (te["cor"][1] - tw["cor"][1]) / G0 * 100, "0.74")
    r = R + 400e3
    q.num(12, np.sqrt(MU / r) - W * r, "7174")
    check("Q12 omega r (m/s)", W * r, 494, tol=0.5)
    check("Q12 westward (m/s)", np.sqrt(MU / r) + W * r, 8163)


def pslv_max_q():
    """Drill 1: PSLV at maximum dynamic pressure (state taken from the simulator's reference mission)."""
    from flight import missions
    tr = missions.fly(missions.pslv_c18_like())
    i = int(np.argmax(tr.q))
    check("P1 time of max-q (s)", tr.t[i], 63, tol=0.5)
    check("P1 h (km)", tr.h[i] / 1e3, 11, tol=0.5)
    check("P1 V (m/s)", tr.V[i], 470, tol=5)
    check("P1 gamma (deg)", np.degrees(tr.gamma[i]), 64, tol=0.5)
    check("P1 chi (deg)", np.degrees(tr.chi[i]), 75, tol=0.5)
    check("P1 latitude (deg)", np.degrees(tr.lat[i]), 13.7, tol=0.05)
    t = terms(11e3, 470.0, 64 * DEG, 75 * DEG, 13.7 * DEG)
    gr, gN = gravity.spherical_components(R + 11e3, 13.7 * DEG)
    check("P1 g_r", gr, 9.778)
    check("P1 g_N", gN, -0.0073)
    want = {("grav", 0): -8.789, ("cen", 0): 0.0279, ("grav", 1): -4.285, ("curv", 1): 0.0152, ("cor", 1): 0.0643,
            ("cen", 1): 0.0159, ("grav", 2): 0.0070, ("curv", 2): 0.0016, ("cor", 2): -0.0084, ("cen", 2): 0.0076}
    for (k, j), v in want.items():
        check(f"P1 {['V', 'gamma', 'chi'][j]} equation, {k}", t[k][j], v)
    small = [abs(t[k][j]) / G0 < 0.01 for (k, j) in want if k != "grav"]
    truth("P1 every non-gravity term below 1 % of g0", all(small))
    check("P1 largest: Coriolis in the gamma equation (%)", t["cor"][1] / G0 * 100, 0.66)
    truth("P1 the curvature term in the V equation is zero", abs(t["curv"][0]) < 1e-12)


def east_west_north():
    """Drill 2: east, west and north at the latitude of Sriharikota."""
    p = 13.7 * DEG
    te, tw, tn = (terms(11e3, 250.0, 0.0, c * DEG, p) for c in (90, 270, 0))
    check("P2 east", te["cor"][1], 0.0354)
    check("P2 west", tw["cor"][1], -0.0354)
    check("P2 lift change (%)", te["cor"][1] / G0 * 100, 0.36)
    for k in ("grav", "curv", "cen"):
        truth(f"P2 north: the {k} term of the chi equation vanishes", abs(tn[k][2]) < 1e-12)
    check("P2 north: Coriolis in the chi equation", tn["cor"][2], 0.0086)
    check("P2 bank (deg)", np.degrees(np.arcsin(-tn["cor"][2] / G0)), -0.050)


def orbits():
    """Extension 3: orbits from the gamma equation."""
    import sympy as sp
    V, r, w, gr = sp.symbols("V r omega g_r", positive=True)
    truth("P3 east: -g_r + V^2/r + 2wV + w^2 r = (V + w r)^2/r - g_r",
          sp.simplify((-gr + V**2 / r + 2 * w * V + w**2 * r) - ((V + w * r) ** 2 / r - gr)) == 0)
    truth("P3 west: -g_r + V^2/r - 2wV + w^2 r = (V - w r)^2/r - g_r",
          sp.simplify((-gr + V**2 / r - 2 * w * V + w**2 * r) - ((V - w * r) ** 2 / r - gr)) == 0)
    rr = R + 400e3
    check("P3 circular speed (m/s)", np.sqrt(MU / rr), 7668.6)
    check("P3 omega r (m/s)", W * rr, 494.3)
    check("P3 eastward V (m/s)", np.sqrt(MU / rr) - W * rr, 7174.3)
    check("P3 westward V (m/s)", np.sqrt(MU / rr) + W * rr, 8162.8)
    # numerical: with point-mass gravity and V = 7174.3 east, the vector terms balance in the gamma equation
    from flight.gravity import point_mass
    rv = frames.ecef_from_spherical(rr, 0.0, 0.0)
    C = frames.ned_matrix(0.0, 0.0).T
    eV, ng, nc = (C @ e for e in frames.wind_directions(0.0, 90 * DEG))
    Vv = (np.sqrt(MU / rr) - W * rr) * eV
    tot = point_mass(rv) - 2 * np.cross(OM, Vv) - np.cross(OM, np.cross(OM, rv))
    Om = (np.linalg.norm(Vv) / rr) * np.array([0, 0, 1.0])
    tot = tot - np.linalg.norm(Vv) * np.cross(Om, eV)
    truth(f"P3 the gamma-equation terms cancel for the eastward orbit (residual {tot @ ng:.1e})", abs(tot @ ng) < 1e-9)
    check("P3 geostationary radius (km)", (MU / W**2) ** (1 / 3) / 1e3, 42164)


if __name__ == "__main__":
    run([objective, pslv_max_q, east_west_north, orbits])
