"""Checks every number and direction in the answers and solutions of 02-rotating-frames-questions.qmd.
Run from anywhere:  python3 codes/02-rotating-frames-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.constants import OMEGA_EARTH as W, G0, A_EARTH as R, MU, DEG

PAGE = os.path.join(HERE, "..", "02-rotating-frames-questions.qmd")
DELHI, TVM = 28.61 * DEG, 8.52 * DEG
E, N, U = np.eye(3)                                   # local east, north, up (right-handed)


def omega_local(phi):
    return W * (np.cos(phi) * N + np.sin(phi) * U)


def coriolis(phi, V):
    return -2 * np.cross(omega_local(phi), V)


def objective():
    """The 12 objective questions."""
    q = Objective(PAGE, 12)
    check("Q2 sidereal day (s)", 365.25 / 366.25 * 86400, 86164, tol=1)
    check("Q2 distractor 86400 x 366.25/365.25 (s)", 86400 * 366.25 / 365.25, 86636, tol=1)
    w = 2 * np.pi / 6
    q.num(5, 2 * w * 2, "4.19")
    check("Q5 omega", w, 1.047)
    check("Q5 distractor without 2", w * 2, 2.09)
    q.num(6, W**2 * R * np.cos(45 * DEG), "0.0240")
    check("Q6 equator value", W**2 * R, 0.0339)
    truth("Q7 flying north at the equator: Coriolis is zero", np.allclose(coriolis(0.0, 230 * N), 0))
    v = 160 / 3.6
    c = coriolis(DELHI, v * E)
    check("Q8 train speed (m/s)", v, 44.4)
    q.num(8, -c @ N * 1e3, "3.1")
    truth("Q8 horizontal part points south (to the right of east)", c @ N < 0 and abs(c @ E) < 1e-15)
    check("Q8 distractor 2 w V (mm/s^2)", 2 * W * v * 1e3, 6.5)
    t = np.sqrt(2 * 72.5 / G0)
    check("Q10 fall time (s)", t, 3.845)
    q.num(10, W * G0 * t**3 * np.cos(DELHI) / 3 * 100, "1.2")
    check("Q10 in metres", W * G0 * t**3 * np.cos(DELHI) / 3, 0.012)
    mu_sun, d = 1.327e20, 1.496e11
    check("Q11 Earth's acceleration towards the Sun (mm/s^2)", mu_sun / d**2 * 1e3, 5.9)
    check("Q11 ... a sixth of the Coriolis term on an airliner at 250 m/s", mu_sun / d**2 / (2 * W * 250), 1 / 6, tol=0.01)
    check("Q11 solar tidal acceleration (m/s^2)", 2 * mu_sun * R / d**3, 5e-7, tol=5e-8)
    truth("Q11 ... below 1e-7 of g", 2 * mu_sun * R / d**3 / G0 < 1e-7)
    check("Q12 geostationary radius (km)", (MU / W**2) ** (1 / 3) / 1e3, 42164)


def merry_go_round():
    """Drill 1: walking outwards on a merry-go-round (vectors in the platform frame, z up)."""
    w = 2 * np.pi / 8
    om = np.array([0, 0, w])
    r = np.array([2.0, 0, 0])
    vB = np.array([1.2, 0, 0])
    m = 50.0
    check("P1 omega (rad/s)", w, 0.785)
    cf = -np.cross(om, np.cross(om, r))
    check("P1 centrifugal (m/s^2)", np.linalg.norm(cf), 1.23)
    truth("P1 centrifugal points outwards", cf @ r > 0)
    co = -2 * np.cross(om, vB)
    check("P1 Coriolis (m/s^2)", np.linalg.norm(co), 1.88)
    truth("P1 Coriolis points against the turning (anticlockwise turning is +y at this point)", co[1] < 0)
    F = m * (2 * np.cross(om, vB) + np.cross(om, np.cross(om, r)))
    check("P1 friction, inward part (N)", -F[0], 61.7)
    check("P1 friction, along the turning (N)", F[1], 94.2)
    check("P1 friction total (N)", np.linalg.norm(F), 113)
    check("P1 weight (N)", m * G0, 490, tol=1)
    check("P1 friction / weight (%)", np.linalg.norm(F) / (m * G0) * 100, 23)


def airliner():
    """Drill 2: an A320 over Delhi."""
    V = 230.0
    check("P2 2 w V", 2 * W * V, 0.0335)
    for a, b, want in ((E, N, U), (N, U, E), (U, E, N)):
        truth(f"P2 cross product rule {want}", np.allclose(np.cross(a, b), want))
    c = coriolis(DELHI, V * E)
    check("P2 east: upward part", c @ U, 0.0294)
    check("P2 east: southward part", -(c @ N), 0.0161)
    check("P2 lift change (%)", c @ U / G0 * 100, 0.30)
    truth("P2 flying west the upward part changes sign", np.isclose(coriolis(DELHI, -V * E) @ U, -(c @ U)))
    cn = coriolis(DELHI, V * N)
    check("P2 north: eastward part", cn @ E, 0.0161)
    truth("P2 north: no vertical part", abs(cn @ U) < 1e-15)


def always_right():
    """Extension 3: the horizontal Coriolis part, the inertial circle, the Foucault pendulum."""
    V = 230.0
    ok = True
    for phi in (DELHI, -DELHI, TVM):
        for chi in np.radians(np.arange(0, 360, 15)):
            Vh = V * (np.cos(chi) * N + np.sin(chi) * E)
            c = coriolis(phi, Vh)
            ch = c - (c @ U) * U
            ok &= np.allclose(ch, -2 * W * np.sin(phi) * np.cross(U, Vh))
            ok &= np.isclose(np.linalg.norm(ch), 2 * W * V * abs(np.sin(phi)))
            right = np.cross(Vh, U)                    # V turned 90 deg to the right, seen from above
            ok &= (ch @ right > 0) == (phi > 0)
    truth("P3 horizontal part = -2 w sin(phi) e_up x V, same size for every heading, right in the north, left in the south", ok)
    check("P3 radius (km)", V / (2 * W * np.sin(DELHI)) / 1e3, 3293)
    check("P3 sideways acceleration", 2 * W * V * np.sin(DELHI), 0.0161)
    check("P3 bank (deg)", np.degrees(np.arctan(2 * W * V * np.sin(DELHI) / G0)), 0.094)
    check("P3 Foucault Delhi (h)", 86164 / np.sin(DELHI) / 3600, 50.0)
    check("P3 Foucault Thiruvananthapuram (h)", 86164 / np.sin(TVM) / 3600, 162, tol=0.5)
    check("P3 Foucault pole (h)", 86164 / 3600, 23.93)


if __name__ == "__main__":
    run([objective, merry_go_round, airliner, always_right])
