"""Lecture 3, ECI and ECEF: the Earth seen from above the North Pole. The ECI axes (grey) point at fixed stars;
the ECEF axes (blue) turn with the Earth at omega_E, carrying the launch pad at Sriharikota (13.7 deg N) and its
local east direction. The pad's speed relative to the stars, omega_E r cos(phi), is the engine's
frames.inertial_velocity of a point at rest. Six hours of turning. Writes img/anim-03-turning-earth.gif."""
import numpy as np
from _visual import plt, save_anim, earth_disc, INK, MAROON, BLUE, GREEN, GREY
from flight.frames import rot_z, ecef_from_geodetic, inertial_velocity
from flight.constants import OMEGA_EARTH as W, A_EARTH as R

LAT, LON = np.radians(13.72), np.radians(80.23)
PAD = ecef_from_geodetic(LAT, LON, 0.0)
V_PAD = np.linalg.norm(inertial_velocity(PAD, np.zeros(3)))
HOURS = 6.0

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(8, 8))
    N, fps = 120, 18
    ts = np.linspace(0, HOURS * 3600, N)
    kw = dict(arrowstyle="-|>", mutation_scale=16, lw=2.2)

    def frame(k):
        ax.clear()
        t = ts[k]
        C = rot_z(-W * t)                                     # ECEF -> ECI components (ECEF turned by +W t)
        earth_disc(ax, 1.0)
        for v, lab in (((1.55, 0), "$x_I$"), ((0, 1.55), "$y_I$")):
            ax.annotate("", xy=v, xytext=(0, 0), arrowprops=dict(color=GREY, **kw))
            ax.text(v[0] + 0.04, v[1] + 0.04, lab, fontsize=13, color=GREY)
        for v, lab in ((np.array([1.3, 0, 0]), "$x_E$"), (np.array([0, 1.3, 0]), "$y_E$")):
            p = C @ v
            ax.annotate("", xy=p[:2], xytext=(0, 0), arrowprops=dict(color=BLUE, **kw))
            ax.text(p[0] * 1.08, p[1] * 1.08, lab, fontsize=13, color=BLUE)
        pad = C @ PAD / R
        east = C @ np.array([-np.sin(LON), np.cos(LON), 0.0])
        pp = pad[:2] / np.linalg.norm(pad[:2]) * 1.0
        ax.plot(*pp, "o", color=MAROON, ms=10)
        ax.annotate("", xy=pp + 0.45 * east[:2], xytext=pp, arrowprops=dict(color=MAROON, **kw))
        lab = pp * 1.22 + 0.25 * east[:2]
        ax.text(*lab, f"{V_PAD:.0f} m/s", fontsize=12, color=MAROON, ha="center", va="center")
        ax.text(-1.75, -1.65, f"t = {t / 3600:3.1f} h,  the Earth has turned {np.degrees(W * t):5.1f}°", fontsize=12)
        ax.text(-1.75, 1.75, "seen from above the North Pole", fontsize=12)
        ax.text(0.0, -0.12, "N", fontsize=12, ha="center", color=INK)
        ax.set_xlim(-1.8, 1.8)
        ax.set_ylim(-1.8, 1.95)
        ax.set_aspect("equal")
        ax.axis("off")
        return []

    save_anim(fig, frame, N, fps, "anim-03-turning-earth")
