"""Checks the numbers in orbital-maneuvers-questions.qmd, including the finite-burn integrations.

Model of every "integration" on the page: two-body motion with a constant thrust F along the velocity and the
mass flow of the rocket equation (codes/_mqburn.py), the burn centred in time on periapsis; for Q2 and the
efficiency of Q6, the exact time average of the coasting speed over the burn (codes/_mqcommon.eta_exact).

Run from the sfm-slides directory:   python3 codes/maneuvers-questions-verify.py
"""
import sys
import numpy as np
sys.path.insert(0, "codes")
from _mqburn import burn, MU, RE                                   # noqa: E402
from _mqcommon import eta_exact, half_arc                          # noqa: E402

RESULTS = []
G0 = 9.80665
MUS, AU = 1.32712440018e11, 1.495978707e8


def check(name, value, stated, tol):
    ok = abs(value - stated) <= tol
    RESULTS.append(ok)
    print(f"{'PASS' if ok else 'FAIL'}  {name:<62} {value:15.7g}   page: {stated}")


vis = lambda r, a: np.sqrt(MU * (2 / r - 1 / a))

# ======================================================================= Q1
print("Q1. first-order burn errors")
r1, r2 = 6678.137, 42164.0
at = (r1 + r2) / 2; vt1 = vis(r1, at); vc = np.sqrt(MU / r1); dv = vt1 - vc; et = (r2 - r1) / (r2 + r1)
check("Hohmann burn 1 [km/s]", dv, 2.42573, 5e-6)
check("delta r_a per m/s [km]", 4 * at ** 2 * vt1 / MU * 1e-3, 60.8, 0.05)
check("  for 1% [km]", 4 * at ** 2 * vt1 / MU * 0.01 * dv, 1474, 1)
check("pointing 1 deg: delta a [km]", -at ** 2 / MU * vc * dv * np.radians(1) ** 2, -8.5, 0.05)
gain = dv / vt1 * (1 + et) / et
check("delta omega / alpha", -gain, -0.568, 5e-4)
check("arrival shift for 1 deg [km]", gain * np.radians(1) * r2, 418, 1)
n1 = np.sqrt(MU / r1 ** 3)
check("timing: arrival shift per second [km]", n1 * r2, 48.8, 0.05)
check("  inertial hold [km per s]", n1 * r2 * (1 - gain), 21, 0.5)
check("Q1(d) radial [km]", 0.002 * dv * 1e3 * 4 * at ** 2 * vt1 / MU * 1e-3, 295, 1)
check("Q1(d) along-track RSS [km]", np.hypot(0.3 * gain * np.radians(1) * r2, n1 * r2), 134, 1)

# ======================================================================= Q2
print("Q2. finite burns (exact average of the coasting speed)")
rp, e = 7000.0, 0.5; ra = rp * (1 + e) / (1 - e)
check("eta formula, e = 0.5, theta = 30 deg", 1 - e * np.radians(30) ** 2 / (6 * (1 + e) ** 2), 0.9898, 5e-5)
check("eta exact for t_b = 818 s", eta_exact(rp, ra, 818), 0.9896, 5e-5)
check("half-arc for 818 s [deg]", np.degrees(half_arc(rp, ra, 818)), 30.0, 0.05)
check("half-arc for 1803 s [deg]", np.degrees(half_arc(rp, ra, 1803)), 60.0, 0.1)
for tb, k, stated in ((1803, 1, 4.39), (902, 2, 1.25), (601, 3, 0.57)):
    check(f"loss for {k} burn(s) of {tb} s [%]", 100 * (1 - eta_exact(rp, ra, tb)), stated, 0.006)

# ======================================================================= Q3, Q7
print("Q3, Q7. phasing")
r = 6778.137; v = np.sqrt(MU / r); T = 2 * np.pi * np.sqrt(r ** 3 / MU); dth = np.radians(20)
check("ISS speed [km/s]", v, 7.6686, 5e-5)
check("ISS period [s]", T, 5553.6, 0.05)
for k, Tph_s, aph_s, hp_s, dv_s in ((2, 5399.4, 6652.0, 148, 146.1), (3, 5450.8, 6694.2, 232, 96.5), (34, 5544.5, 6770.8, 385, 8.4)):
    Tph = T * (1 - dth / (2 * np.pi * k)); aph = (MU * (Tph / (2 * np.pi)) ** 2) ** (1 / 3)
    dvt = 2 * (v - vis(r, aph)) * 1e3
    check(f"k = {k}: T_ph [s]", Tph, Tph_s, 0.05)
    check(f"  a_ph [km]", aph, aph_s, 0.05)
    check(f"  perigee altitude [km]", 2 * aph - r - RE, hp_s, 0.5)
    check(f"  dv total [m/s]", dvt, dv_s, 0.05)
check("Q3(b) small-angle estimate [m/s]", v * dth / (3 * np.pi * 2) * 1e3, 142.0, 0.05)
check("k* (Q3c)", 7669 * 0.005 * dth / (6 * np.pi * 0.1), 7.1, 0.05)
check("k_min bound (Q3d)", 2 * 6778 * dth / (3 * np.pi * 200), 2.51, 0.005)
for k, prop in ((3, 226), (34, 20)):
    Tph = T * (1 - dth / (2 * np.pi * k)); aph = (MU * (Tph / (2 * np.pi)) ** 2) ** (1 / 3)
    check(f"Q7(b) propellant k = {k} [kg]", 7000 * (1 - np.exp(-2 * (v - vis(r, aph)) * 1e3 / (300 * G0))), prop, 0.5)
for k, stated in ((3, 12.8), (34, 57.9)):
    rel = 0.005 * dth; ab = 6 * np.pi * k * 0.1 / (v * 1e3)
    check(f"Q7(c) along-track RSS, k = {k} [km]", np.hypot(rel, ab) * r, stated, 0.05)

# ======================================================================= Q4
print("Q4. apse rotation")
a4, e4 = 12000.0, 0.4; p4 = a4 * (1 - e4 ** 2); s = np.sqrt(MU / p4)
dv4 = 2 * s * e4 * np.sin(np.radians(15)); vth = s * (1 + e4 * np.cos(np.radians(15)))
check("dv [km/s]", dv4, 1.30204, 5e-6)
check("v_theta at the crossing [km/s]", vth, 8.71802, 5e-6)
de = vth * dv4 * np.radians(1); da = 2 * a4 ** 2 * de / MU; T4 = 2 * np.pi * np.sqrt(a4 ** 3 / MU)
check("delta a for 1 deg [km]", da, 143, 0.5)
check("delta T per revolution [s]", 1.5 * T4 * da / a4, 234, 0.5)
check("pointing for |dT| < 10 s [deg]", np.degrees(MU * (2 / 3 * a4 * 10 / T4) / (2 * a4 ** 2) / (vth * dv4)), 0.043, 5e-4)
vp4 = vis(a4 * (1 - e4), a4)
check("trim at periapsis for 0.3 deg [m/s]", MU * (2 * a4 ** 2 * vth * dv4 * np.radians(0.3) / MU) / (2 * vp4 * a4 ** 2) * 1e3, 6.8, 0.05)

# ======================================================================= Q5
print("Q5. Chandrayaan-3")
rpc = RE + 200
orb = lambda ra_alt: ((rpc + RE + ra_alt) / 2, (RE + ra_alt - rpc) / (RE + ra_alt + rpc))
(aA, eA), (aB, eB), (aC, eC) = orb(36500), orb(127603), orb(369328)
vA, vB, vC = vis(rpc, aA), vis(rpc, aB), vis(rpc, aC)
check("dv A->B [m/s]", (vB - vA) * 1e3, 497.5, 0.05)
check("dv B->C [m/s]", (vC - vB) * 1e3, 165.6, 0.05)
check("from a 200 km circle [m/s]", (vC - np.sqrt(MU / rpc)) * 1e3, 3129, 0.5)
ve = 310 * G0 * 1e-3
m, a, e, vp, tot = 3900.0, aA, eA, vA, 0.0
for k in range(5):
    vpt = vp + (vB - vA) / 5; at_ = 1 / (2 / rpc - vpt ** 2 / MU)
    tb = m * ve * 1e3 / 440 * (1 - np.exp(-(vB - vA) / 5 / ve))
    R = burn(a, e, m, 440, 310, tb, eps_target=-MU / (2 * at_))
    tot += R["dv"]; m, a, e, vp = R["m"], R["a"], R["e"], vpt
check("five finite burns: extra dv [m/s]", (tot - (vB - vA)) * 1e3, 8.9, 0.05)
check("  perigee after them [km]", R["rp"] - RE, 224, 0.5)
check("burn 1 duration (formula) [s]", 3900 * ve * 1e3 / 440 * (1 - np.exp(-(vB - vA) / 5 / ve)), 868, 0.5)
tb = 4068.0
for _ in range(6):                                           # centre the single burn on its own duration
    R = burn(aA, eA, 3900, 440, 310, tb, eps_target=-MU / (2 * aB)); tb = R["t"]
check("one burn A->B: duration [min]", R["t"] / 60, 86, 0.5)
check("  dv [m/s]", R["dv"] * 1e3, 645, 0.5)
check("  perigee [km]", R["rp"] - RE, 694, 0.5)
tb = 1213.0
for _ in range(6):
    R = burn(aB, eB, 3311, 440, 310, tb, eps_target=-MU / (2 * aC)); tb = R["t"]
check("TLI finite burn: extra dv [m/s]", R["dv"] * 1e3 - (vC - vB) * 1e3, 6.5, 0.05)
check("  as a fraction [%]", (R["dv"] / (vC - vB) - 1) * 100, 3.9, 0.05)
check("TLI apogee gain [km per m/s]", 4 * aC ** 2 * vC / MU * 1e-3, 4000, 10)

# ======================================================================= Q6
print("Q6. Mangalyaan")
rpm, ram = RE + 252, RE + 192874; am = (rpm + ram) / 2; em = (ram - rpm) / (ram + rpm); vpm = vis(rpm, am)
check("e", em, 0.93559, 5e-6)
check("v_p [km/s]", vpm, 10.7873, 5e-5)
check("half arc of the 1328.89 s burn [deg]", np.degrees(half_arc(rpm, ram, 1328.89)), 53.3, 0.05)
check("eta, exact average", eta_exact(rpm, ram, 1328.89), 0.960, 5e-4)
mdot = 440 / (310 * G0)
check("propellant [kg]", mdot * 1328.89, 192, 0.5)
m0 = mdot * 1328.89 / (1 - np.exp(-0.648 / ve))
check("initial mass [kg]", m0, 1002, 0.5)
R = burn(am, em, m0, 440, 310, 1328.89, tb=1328.89)
vinf = np.sqrt(2 * R["eps"])
check("integrated burn: dv [m/s]", R["dv"] * 1e3, 648, 0.5)
check("  v_inf [km/s]", vinf, 3.14, 0.005)
check("  C3 [km2/s2]", vinf ** 2, 9.9, 0.05)
vimp = np.sqrt(2 * MU / rpm + vinf ** 2) - vpm
check("  waste against an impulsive burn [m/s]", (R["dv"] - vimp) * 1e3, 28, 0.5)
# speed and thrust acceleration at cutoff, for (d)
m1 = m0 - mdot * 1328.89
check("speed at cutoff [km/s]", R["vend"], 10.1, 0.05)
check("one second late: delta v_inf [m/s]", R["vend"] / vinf * 440 / m1, 1.8, 0.05)
check("thrust acceleration at cutoff [m/s2]", 440 / m1, 0.54, 0.005)

# ======================================================================= Q8
print("Q8. GTO to GEO")
rpg, rag = RE + 185, RE + 35786; ag = (rpg + rag) / 2; va = vis(rag, ag); vg = np.sqrt(MU / rag)
vex = 315 * G0 * 1e-3
for site, i_d, dvs, tbs, arcs, losss in (("Kourou", 7, 1503, 8116, 25.1, 12.0), ("Sriharikota", 19.2, 1653, 8728, 26.7, 14.9),
                                         ("Cape", 28.5, 1837, 9443, 28.5, 18.9)):
    ir = np.radians(i_d); V0 = np.array([va, 0]); V1 = vg * np.array([np.cos(ir), np.sin(ir)])
    d = np.linalg.norm(V1 - V0); u = (V1 - V0) / d
    tb = 3000 * vex * 1e3 / 440 * (1 - np.exp(-d / vex))
    t = np.linspace(0, tb, 20001); mm = 3000 - 440 / (vex * 1e3) * t; sv = vex * np.log(3000 / mm)
    sp = np.linalg.norm(V0[None, :] + sv[:, None] * u[None, :], axis=1)
    arc = np.trapz(sp, t) / rag
    check(f"{site}: dv [m/s]", d * 1e3, dvs, 0.5)
    check(f"  burn time [s]", tb, tbs, 0.5)
    check(f"  arc [deg]", np.degrees(arc), arcs, 0.05)
    check(f"  loss theta^2/6 [m/s]", (arc / 2) ** 2 / 6 * d * 1e3, losss, 0.05)
ir = np.radians(28.5); d = np.sqrt(va ** 2 + vg ** 2 - 2 * va * vg * np.cos(ir))
beta = np.arctan2(vg * np.sin(ir), vg * np.cos(ir) - va)
dvf = -va * d * np.sin(beta) / vg                             # d|v_f|/d beta
check("Q8(c) speed change per degree of yaw (Cape) [m/s]", abs(dvf) * np.radians(1) * 1e3, 13.3, 0.05)
gain = 2 * rag ** 2 * vg / MU * 1e-3
check("  semi-major axis error [km]", gain * abs(dvf) * np.radians(1) * 1e3, 364, 1)
check("  drift [deg/day]", 360 * 1.5 * gain * abs(dvf) * np.radians(1) * 1e3 / rag, 4.7, 0.05)
check("GEO gain [km per m/s]", gain, 27.4, 0.05)
check("angle between dv and v_GEO (cos) (Q8d)", np.cos(np.arcsin(va * np.sin(ir) / d)), 0.91, 0.005)

# ======================================================================= Q9
print("Q9. bi-elliptic to lunar distance")
r1, r2, rb = 6678.137, 384400.0, 1e6
aH = (r1 + r2) / 2
dvH = (vis(r1, aH) - np.sqrt(MU / r1)) + (np.sqrt(MU / r2) - vis(r2, aH))
check("Hohmann [km/s]", dvH, 3.9365, 5e-5)
a1, a2 = (r1 + rb) / 2, (rb + r2) / 2
dvB = (vis(r1, a1) - np.sqrt(MU / r1)) + (vis(rb, a2) - vis(rb, a1)) + (vis(r2, a2) - np.sqrt(MU / r2))
check("bi-elliptic [km/s]", dvB, 3.7672, 5e-5)
check("saving [m/s]", (dvH - dvB) * 1e3, 169, 0.5)
check("flight time [d]", (np.pi * np.sqrt(a1 ** 3 / MU) + np.pi * np.sqrt(a2 ** 3 / MU)) / 86400, 53.7, 0.05)
check("Hill radius of the Earth [km]", AU * (MU / (3 * MUS)) ** (1 / 3), 1.50e6, 0.01e6)

# ======================================================================= Q10
print("Q10. GEO budget")
vech = 320 * G0
check("chemical propellant [kg]", 3000 * (1 - np.exp(-806 / vech)), 680, 0.5)
check("electric propellant [kg]", 3000 * (1 - np.exp(-806 / (1800 * G0))), 134, 0.5)
check("gauge uncertainty [m/s]", vech * 0.03 * 680 / 2320, 27.6, 0.05)
check("life at 55 m/s/yr [yr]", (806 - 11) / 58, 13.7, 0.05)
check("3-sigma propellant [kg]", 3000 * (1 - np.exp(-941 / vech)), 777, 0.5)
check("life with 2% low Isp [yr]", (0.98 * vech * np.log(3000 / 2320) - 11) / 53, 14.7, 0.05)

print(f"\n{sum(RESULTS)} PASS, {len(RESULTS) - sum(RESULTS)} FAIL")
