"""Checks every number in the answers and solutions of 03-position-velocity-questions.qmd.
Run from anywhere:  python3 codes/03-position-velocity-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, Objective, run
from flight import frames, atmosphere
from flight.constants import OMEGA_EARTH as W, A_EARTH as R, B_EARTH, F_EARTH, MU, DEG

PAGE = os.path.join(HERE, "..", "03-position-velocity-questions.qmd")


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    vn = frames.ned_from_angles(200, 10 * DEG, 135 * DEG)
    q.num(5, vn[0], "-139.3")
    check("Q5 rate of climb (m/s)", -vn[2], 34.7)
    check("Q5 distractor without cos(gamma)", 200 * np.cos(135 * DEG), -141.4)
    lam, phi, r, V = sp.symbols("lambda phi r V", positive=True)
    g, chi = 0, sp.pi / 2
    truth("Q6 level and east: r_dot = phi_dot = 0", V * sp.sin(g) == 0 and sp.simplify(V * sp.cos(g) * sp.cos(chi) / r) == 0)
    q.num(7, W * R * np.cos(5.24 * DEG), "463")
    check("Q7 Sriharikota (m/s)", W * R * np.cos(13.7 * DEG), 452)
    check("Q7 equator (m/s)", W * R, 465)
    q.num(8, 2 * W * R * np.cos(13.7 * DEG), "904", tol=1)
    q.num(10, (B_EARTH + 10e3 - R) / 1e3, "-11.4")
    rr = R + 11e3
    check("Q11 rate (rad/s)", 250 / rr, 3.91e-5, tol=5e-8)
    q.num(11, np.degrees(250 / rr) * 3600, "8.1")
    check("Q11 Earth's rate (deg/h)", np.degrees(W) * 3600, 15.0)
    r4 = R + 400e3
    vi = np.sqrt(MU / r4)
    check("Q12 inertial speed (m/s)", vi, 7668.6)
    check("Q12 ground speed of the frame (m/s)", W * r4, 494.3)
    check("Q12 speed relative to the Earth (m/s)", vi - W * r4, 7174.3)
    q.num(12, 2 * np.pi * r4 / (vi - W * r4) / 60, "98.9")
    check("Q12 inertial period (min)", 2 * np.pi * r4 / vi / 60, 92.6)
    check("Q12 westward orbit (min)", 2 * np.pi * r4 / (vi + W * r4) / 60, 87.0)


def chennai():
    """Drill 1: leaving Chennai."""
    phi, r = 13.08 * DEG, R + 11e3
    check("P1 rate of climb (m/s)", 120 * np.sin(8 * DEG), 16.7)
    v = frames.ned_from_angles(230, 0.0, 350 * DEG)
    check("P1 V_N (m/s)", v[0], 226.5)
    check("P1 V_E (m/s)", v[1], -39.9)
    check("P1 phi_dot (rad/s)", v[0] / r, 3.55e-5, tol=5e-8)
    check("P1 phi_dot (deg/h)", np.degrees(v[0] / r) * 3600, 7.31)
    check("P1 lambda_dot (deg/h)", np.degrees(v[1] / (r * np.cos(phi))) * 3600, -1.32)
    check("P1 two hours (deg)", 2 * np.degrees(v[0] / r) * 3600, 14.6)
    check("P1 Delhi - Chennai latitude (deg)", 28.61 - 13.08, 15.5)


def launch_sites():
    """Drill 2: the launch sites of the world."""
    for name, lat, v in (("Sriharikota", 13.72, 452), ("Kourou", 5.24, 463), ("Cape Canaveral", 28.5, 409), ("Baikonur", 45.96, 323)):
        check(f"P2 {name} (m/s)", W * R * np.cos(lat * DEG), v)
    u = W * (R + 200e3) * np.cos(13.72 * DEG)
    check("P2 frame speed at 200 km (m/s)", u, 466)
    # the inertial velocity from frames.inertial_velocity, for the three headings
    lat, lon = 13.72 * DEG, 80.23 * DEG
    rv = frames.ecef_from_spherical(R + 200e3, lat, lon)
    C = frames.ned_matrix(lat, lon).T
    for chi, want in ((90, 7866), (180, 7415), (270, 6934)):
        vI = frames.inertial_velocity(rv, C @ frames.ned_from_angles(7400, 0, chi * DEG))
        check(f"P2 inertial speed heading {chi} (m/s)", np.linalg.norm(vI), want)
    check("P2 gain heading south (m/s)", np.hypot(7400, u) - 7400, 15)


def two_latitudes():
    """Extension 3: the two latitudes, and the altitude error of a sphere."""
    pd, k = sp.symbols("phi_d k", positive=True)
    d = pd - sp.atan(k * sp.tan(pd))
    dd = sp.diff(d, pd)
    t = 1 / sp.sqrt(k)
    truth("P3 d delta/d phi_d = 0 at tan(phi_d) = 1/sqrt(k)", sp.simplify(dd.subs(pd, sp.atan(t))) == 0)
    truth("P3 the derivative given in the solution", sp.simplify(dd - (1 - k / sp.cos(pd) ** 2 / (1 + k**2 * sp.tan(pd) ** 2))) == 0)
    f = F_EARTH
    dmax = np.arctan(1 / (1 - f)) - np.arctan(1 - f)
    check("P3 largest difference (deg)", np.degrees(dmax), 0.1924)
    check("P3 at geodetic latitude (deg)", np.degrees(np.arctan(1 / (1 - f))), 45.10)
    check("P3 f in degrees", np.degrees(f), 0.1921)
    lat_d = np.radians(np.linspace(30, 60, 30001))
    diff = lat_d - frames.geocentric_from_geodetic_surface(lat_d)
    check("P3 numerical maximum agrees (deg)", np.degrees(diff.max()), 0.1924)
    r45 = np.linalg.norm(frames.ecef_from_geodetic(45 * DEG, 0.0, 0.0))
    check("P3 ellipsoid radius at 45 deg (km)", r45 / 1e3, 6367.49)
    check("P3 error at 45 deg (km)", (R - r45) / 1e3, 10.6)
    check("P3 error at the pole (km)", (R - B_EARTH) / 1e3, 21.4)
    check("P3 density ratio over 10.6 km", atmosphere.ISA.state(0)[2] / atmosphere.ISA.state(10.6e3)[2], 3.2)


if __name__ == "__main__":
    run([objective, chennai, launch_sites, two_latitudes])
