"""Lecture 3, a constant heading spirals into the pole: a vehicle at 250 m/s holds a heading of 45 deg (north-east)
from Sriharikota, on a sphere. The velocity in ECEF comes from the engine (frames.ned_matrix, ned_from_angles); the
latitude and longitude it produces are read back with frames.spherical_from_ecef. Seen from above the North Pole,
the track spirals round the pole: near it, a small sideways speed sweeps through many degrees of longitude, which is
why lambda-dot = V cos(gamma) sin(chi)/(r cos(phi)) grows without limit. Writes img/anim-03-spiral.gif."""
import numpy as np
from scipy.integrate import solve_ivp
from _visual import plt, save_anim, INK, MAROON, BLUE, GREY
from flight.frames import ned_matrix, ned_from_angles, spherical_from_ecef, ecef_from_spherical
from flight.constants import A_EARTH as R

V, CHI = 250.0, np.radians(45.0)
LAT0, LON0 = np.radians(13.72), np.radians(80.23)


def rhs(t, y):
    r, lat, lon = spherical_from_ecef(y)
    v = ned_matrix(lat, lon).T @ ned_from_angles(V, 0.0, CHI)
    return v - (v @ y) / (y @ y) * y                       # stay on the sphere


stop = lambda t, y: spherical_from_ecef(y)[1] - np.radians(89.9)
stop.terminal = True
SOL = solve_ivp(rhs, (0, 4e5), ecef_from_spherical(R, LAT0, LON0), events=stop, rtol=1e-10, atol=1e-3, max_step=200)
LAT = np.array([spherical_from_ecef(SOL.y[:, i])[1] for i in range(SOL.t.size)])
LON = np.array([spherical_from_ecef(SOL.y[:, i])[2] for i in range(SOL.t.size)])
LON_UNW = np.unwrap(LON)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(8, 8))
    N, fps = 130, 16
    idx = np.linspace(0, SOL.t.size - 1, N).astype(int)
    rho = np.degrees(np.pi / 2 - LAT)                       # azimuthal map: distance from the pole in degrees
    X, Y = rho * np.sin(LON - LON0), -rho * np.cos(LON - LON0)

    def frame(k):
        ax.clear()
        for c in (10, 30, 50, 70):
            th = np.linspace(0, 2 * np.pi, 200)
            ax.plot(c * np.cos(th), c * np.sin(th), color="#d9d2c3", lw=0.8)
            ax.text(c * 0.71, c * 0.71, f"{90 - c}°", fontsize=10, color=GREY)
        i = idx[k]
        ax.plot(X[:i + 1], Y[:i + 1], color=MAROON, lw=2.2)
        ax.plot(X[i], Y[i], "o", color=MAROON, ms=9)
        ax.plot(0, 0, "+", color=INK, ms=14)
        ax.text(-3, -3, "North Pole", fontsize=11, ha="right", va="top")
        ax.text(-84, 80, f"heading 45°, {V:.0f} m/s, from Sriharikota", fontsize=12)
        ax.text(-84, -86, f"after {SOL.t[i] / 3600:5.1f} h:  latitude {np.degrees(LAT[i]):5.1f}°,  "
                           f"longitude turned {np.degrees(LON_UNW[i] - LON0):6.0f}°", fontsize=12)
        ax.set_xlim(-88, 88)
        ax.set_ylim(-92, 88)
        ax.set_aspect("equal")
        ax.axis("off")
        return []

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