"""Lecture 30, Weiland's test (2010, sec. 9.2.1): a vehicle in a circular equatorial orbit at 400 km, written in the
frame turning with the Earth, where its speed is 7177.49 m/s (R = 6378 km, omega_E = 7.292e-5 rad/s, g = g0 R^2/r^2).
Integrated with the Coriolis and centrifugal terms, the height stays at 400 km. Without them the same start is integrated as plain
two-body motion in the turning axes, and the vehicle reaches the ground. Top: height against time. Bottom: longitude
relative to the ground. Writes img/fig-30-dropped-terms.png."""
import numpy as np
from scipy.integrate import solve_ivp
from _visual import plt, save, despine, MAROON, BLUE, GREY
from flight.constants import G0

RW, WW = 6378000.0, 7.292e-5
MW, R0 = G0 * RW**2, RW + 400e3
VC = np.sqrt(MW / R0)
V_REL = VC - WW * R0


def two_body(t, y):
    r = np.hypot(y[0], y[1])
    return [y[2], y[3], -MW * y[0] / r**3, -MW * y[1] / r**3]


def hit(t, y):
    return np.hypot(y[0], y[1]) - RW


hit.terminal, hit.direction = True, -1
SOL = solve_ivp(two_body, (0.0, 3000.0), [R0, 0.0, 0.0, V_REL], events=hit, rtol=1e-11, atol=1e-6, max_step=2.0)
T_HIT = float(SOL.t[-1])
H_OFF = (np.hypot(SOL.y[0], SOL.y[1]) - RW) / 1e3
LON_OFF = np.degrees(np.arctan2(SOL.y[1], SOL.y[0]))
def turning_frame(t, y):
    """The same motion with the two rotation terms: a = g - 2 w x v - w x (w x r), w along the polar axis."""
    dv = two_body(t, y)
    return [dv[0], dv[1], dv[2] + 2 * WW * y[3] + WW**2 * y[0], dv[3] - 2 * WW * y[2] + WW**2 * y[1]]


T_ON = np.linspace(0, 2000.0, 200)
ON = solve_ivp(turning_frame, (0.0, 2000.0), [R0, 0.0, 0.0, V_REL], t_eval=T_ON, rtol=1e-11, atol=1e-6)
H_ON = (np.hypot(ON.y[0], ON.y[1]) - RW) / 1e3
LON_ON = np.degrees(np.unwrap(np.arctan2(ON.y[1], ON.y[0])))

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(2, 1, figsize=(10, 6.4), sharex=True)
    fig.subplots_adjust(hspace=0.12)
    a.plot(T_ON, H_ON, color=BLUE, lw=2.8, label="with the rotation terms: a circular orbit")
    a.plot(SOL.t, H_OFF, color=MAROON, lw=2.8, label="terms left out: the ground")
    a.plot(T_HIT, 0, "X", color=MAROON, ms=13, zorder=5)
    a.text(T_HIT + 30, 25, f"impact after {T_HIT:.0f} s,\n{LON_OFF[-1]:.1f}° of longitude on", fontsize=11, color=MAROON)
    a.set_ylabel("height (km)"); a.set_ylim(-10, 470)
    a.legend(frameon=False, fontsize=11.5, loc="center right")
    b.plot(T_ON, LON_ON, color=BLUE, lw=2.8)
    b.plot(SOL.t, LON_OFF, color=MAROON, lw=2.8)
    b.plot(T_HIT, LON_OFF[-1], "X", color=MAROON, ms=13)
    b.set_ylabel("longitude from the start (deg)"); b.set_xlabel("time (s)")
    b.set_xlim(0, 2000); b.set_ylim(0, 130)
    despine(a); despine(b)
    save(fig, "fig-30-dropped-terms")
