"""Animations of the chase manoeuvres of chase-lambert.qmd: phasing, the lead angle, the apsis-to-apsis routes.

The same engine as the manoeuvre animations (codes/_manim.py): each scenario is a list of legs (arcs of conics); the
burns are computed from the states at the ends of the legs and checked against the numbers quoted in the note.  Here the
target is a body that keeps to its own orbit all the time (the ring), and every scenario asserts that it is at the
meeting point when the chaser arrives there: that is the lead-angle and timing logic of the note, tested.

Run from the sfm-slides directory:
    python3 codes/anim-chase.py               all of them, into img/anim-chase-<name>.gif
    python3 codes/anim-chase.py --check       build every scenario and check the note's numbers, no drawing
    python3 codes/anim-chase.py --debug NAME  key frames as PNGs in $ANIM_DEBUG
Afterwards, from the project root:  python3 _filters/gif-frames.py   (the still frames that the PDF output uses).
"""
import os
import sys
import numpy as np
from _manstyle import CREAM, INK, MAROON, BLUE, GREEN, AMBER, PURPLE
from _manim import MU, RE, Orbit, Leg, Companion, Panel, animate, f_after

pi = np.pi
SCENARIOS = {}


def scenario(fn):
    SCENARIOS[fn.__name__] = fn
    return fn


def meets(P, comp, j, what):
    """The target must be where the chaser's leg j ends, at the moment it ends."""
    t = P.info["tstart"][j] + P.info["dur"][j]
    r_c = P.legs[j].end[0]
    d = float(np.linalg.norm(comp.pos(t) - r_c))
    assert d < 1.0, f"{what}: the target is {d:.2f} km from the chaser at the end of the transfer"


# ------------------------------------------------------------------ Example 1: closing a 20 degree gap at 420 km (section "same orbit")
@scenario
def phasing_k3():
    r, k, dth = 6798.137, 3, np.radians(20.0)
    circ = Orbit.circ(r, color=BLUE)
    T = 2*pi*np.sqrt(r**3/MU); n = 2*pi/T
    Tph = T*(1 - dth/(2*pi*k)); aph = r*(Tph/T)**(2/3)
    ph = Orbit.rprq(2*aph - r, r, w=pi, color=MAROON)                  # its apoapsis (angle 0) is the burn point
    pre, post = 0.2*3600, 0.3*3600
    legs = [Leg(circ, 2*pi - n*pre, 2*pi), Leg(ph, pi, pi + 2*pi*k), Leg(circ, 0, n*post)]
    tgt = Companion(circ, dth - n*pre, color=PURPLE, ghost=True, ms=19, label="target", label_off=(250, 250))
    P = Panel("the target $20^\\circ$ ahead: close the gap in $k=3$ revolutions", legs, ((-8200, 8200), (-8200, 8200)), companions=[tgt], arrow=0.9,
              labels=[dict(text="circle, $r=6798$ km", pos=(0, 7550), color=BLUE)],
              expect=dict(dv=[0.04816, 0.04816], total=0.09632, tol=1.2e-5, leg_h=[None, 4.562, None], kinds=["retrograde", "prograde"]))
    assert abs((2*aph - r) - 6629.76) < 0.01                           # the perigee radius of the note
    meets(P, tgt, 1, "phasing_k3")
    return [P], dict(K=40, suptitle="the chaser (black dot) flies the circle, three revolutions of a smaller ellipse, and the circle again; the ring is its target")


# ------------------------------------------------------------------ phasing on an ellipse: from an angle to a time
@scenario
def phasing_ellipse():
    a, e = 10000.0, 0.3
    o = Orbit(a*(1 - e*e), e, w=0.0, color=BLUE)
    T = 2*pi*np.sqrt(a**3/MU)
    lims = ((-18500, 10500), (-13500, 12500))
    pre, post = 0.5, 1.0
    out = []
    # chaser at periapsis, target 30 deg behind (f = -30 deg);  chaser at apoapsis, target 30 deg behind (f = 150 deg)
    for nm, fb, ft, f2, dv_each, tph_h in (("at periapsis", 2*pi, -pi/6, 0.0, 0.064904, 10387.13), ("at apoapsis", pi, 5*pi/6, pi, 0.351585, 11367.30)):
        dt = float(o.time(fb if fb == pi else 0.0) - o.time(ft)) if fb == pi else float(o.time(pi/6) - o.time(0.0))
        aph = a*((T + dt)/T)**(2/3)
        rb = a*(1 - e) if fb != pi else a*(1 + e)
        ph = Orbit.rprq(rb, 2*aph - rb, w=0.0, color=MAROON) if fb != pi else Orbit.rprq(2*aph - rb, rb, w=0.0, color=PURPLE)
        legs = [Leg(o, f_after(o, fb, -pre), fb), Leg(ph, f2, f2 + 2*pi), Leg(o, f2, f_after(o, f2, post))]
        tgt = Companion(o, f_after(o, ft, -pre), color=INK, ghost=True, ms=17, label="target", label_off=(300, 500))
        P = Panel(f"the chaser burns {nm}; the target is $30^\\circ$ behind it", legs, lims, companions=[tgt], arrow=0.7,
                  labels=[dict(text="phasing ellipse", pos=(-3000, -12200), color=MAROON if fb != pi else PURPLE)],
                  expect=dict(dv=[dv_each, dv_each], tol=6e-6, leg_h=[None, tph_h/3600, None], kinds=["prograde", "retrograde"]))
        meets(P, tgt, 1, "phasing_ellipse " + nm)
        out.append(P)
    return out, dict(K=26, suptitle="the chaser (black dot) flies its orbit, one longer ellipse, and the orbit again; the ring is its target, on the same orbit")


# ------------------------------------------------------------------ Example 2: 300 km to 420 km, the lead angle and the wait
@scenario
def hohmann_rdv():
    r1, r2 = 6678.137, 6798.137
    n1, n2 = np.sqrt(MU/r1**3), np.sqrt(MU/r2**3)
    at = (r1 + r2)/2; tH = pi*np.sqrt(at**3/MU); thstar = pi - n2*tH
    assert abs(np.degrees(thstar) - 2.378) < 5e-4 and abs(tH - 2752.27) < 0.01       # the note's lead angle and transfer time
    th0 = np.radians(40.0); tw = (th0 - thstar)/(n1 - n2)
    c1, c2, tr = Orbit.circ(r1, color=BLUE), Orbit.circ(r2, color=GREEN), Orbit.rprq(r1, r2, w=0.0, color=MAROON)
    post = 0.1*3600
    legs = [Leg(c1, 2*pi - n1*tw, 2*pi), Leg(tr, 0, pi), Leg(c2, pi, pi + n2*post)]
    tgt = Companion(c2, thstar - n2*tw, color=PURPLE, ghost=True, ms=19, label="target", label_off=(250, 250))
    exp = dict(dv=[0.034321, 0.034168], total=0.068489, tol=6e-6, leg_h=[5.98, tH/3600, None], tol_h=6e-3, kinds=["prograde", "prograde"])
    P = Panel("the whole manoeuvre, to scale: $300$ km to $420$ km", legs, ((-8000, 8000), (-8000, 8000)), companions=[tgt], arrow=1.0, expect=exp,
              labels=[dict(text="chaser: $300$ km", pos=(0, -6150), color=BLUE), dict(text="target: $420$ km", pos=(0, 7550), color=GREEN)])
    meets(P, tgt, 1, "hohmann_rdv")
    # the same legs, enlarged around the arrival: the chaser and the target meet at the apoapsis of the transfer
    Z = Panel("the arrival, enlarged about $9\\times$", legs, ((-7700, -5900), (-900, 900)), companions=[tgt], arrow=1.0, readout=False,
              labels=[dict(text="$420$ km circle", pos=(-6650, 780), color=GREEN, ha="right"), dict(text="transfer ellipse", pos=(-6120, -760), color=MAROON, ha="left")])
    return [P, Z], dict(K=22, dpi=62, colors=128, suptitle="the chaser (black dot) waits on its circle for the target (ring) to be $2.378^\\circ$ ahead, then burns")


# ------------------------------------------------------------------ the outer chaser: Example 2 reversed
@scenario
def hohmann_outer():
    r1, r2 = 6798.137, 6678.137                                        # chaser 420 km, target 300 km
    n2 = np.sqrt(MU/r2**3)
    at = (r1 + r2)/2; tH = pi*np.sqrt(at**3/MU); thstar = pi - n2*tH
    assert abs(np.degrees(thstar) + 2.431) < 5e-4                      # the target must trail by 2.431 deg
    n1 = np.sqrt(MU/r1**3)
    c1, c2, tr = Orbit.circ(r1, color=BLUE), Orbit.circ(r2, color=GREEN), Orbit.rprq(r2, r1, w=pi, color=MAROON)
    pre, post = 0.3*3600, 0.1*3600
    legs = [Leg(c1, 2*pi - n1*pre, 2*pi), Leg(tr, pi, 2*pi), Leg(c2, pi, pi + n2*post)]
    tgt = Companion(c2, thstar - n2*pre, color=PURPLE, ghost=True, ms=19, label="target", label_off=(250, 250))
    P = Panel("the chaser at $420$ km, the target at $300$ km, trailing by $2.431^\\circ$", legs, ((-8000, 8000), (-8000, 8000)), companions=[tgt], arrow=1.0,
              labels=[dict(text="target: $300$ km", pos=(0, -6150), color=GREEN), dict(text="chaser: $420$ km", pos=(0, 7550), color=BLUE)],
              expect=dict(dv=[0.034168, 0.034321], total=0.068489, tol=6e-6, leg_h=[None, tH/3600, None], kinds=["retrograde", "retrograde"]))
    meets(P, tgt, 1, "hohmann_outer")
    return [P], dict(K=40, suptitle="the outer chaser (black dot) burns retrograde; the target (ring), the faster, catches up with the arrival point")


# ------------------------------------------------------------------ the two apsis-to-apsis routes between aligned ellipses
@scenario
def routes():
    mk = lambda a, e, col: Orbit(a*(1 - e*e), e, w=0.0, color=col)
    o1, o2 = mk(6800.0, 0.02, BLUE), mk(10000.0, 0.3, GREEN)
    lims = ((-15500, 9500), (-10500, 10500))
    t1 = Orbit.rprq(6664, 13000, w=0.0, color=MAROON)
    t2 = Orbit.rprq(6936, 7000, w=pi, color=PURPLE)
    pre = 0.7
    legs1 = [Leg(o1, f_after(o1, 2*pi, -pre), 2*pi), Leg(t1, 0, pi), Leg(o2, pi, f_after(o2, pi, 1.5))]
    legs2 = [Leg(o1, f_after(o1, pi, -pre), pi), Leg(t2, 0, pi), Leg(o2, 0.0, f_after(o2, 0.0, 1.5))]
    P1 = Panel("route (i): periapsis of the chaser to apoapsis of the target", legs1, lims, arrow=0.07,
               labels=[dict(text="chaser's orbit", pos=(0, 7400), color=BLUE, ha="left"), dict(text="target's orbit", pos=(-9000, -9400), color=GREEN)],
               expect=dict(dv=[1.08217, 0.07410], tol=6e-6, leg_h=[None, 1.3475, None], kinds=["prograde", "prograde"]))
    P2 = Panel("route (ii): apoapsis of the chaser to periapsis of the target", legs2, lims, arrow=0.07,
               labels=[dict(text="chaser's orbit", pos=(0, 7400), color=BLUE, ha="left"), dict(text="target's orbit", pos=(-9000, -9400), color=GREEN)],
               expect=dict(dv=[0.09358, 1.07512], tol=6e-6, leg_h=[None, 0.8040, None], kinds=["prograde", "prograde"]))
    return [P1, P2], dict(K=40)


# ------------------------------------------------------------------ driver
def build(name):
    return SCENARIOS[name]()


if __name__ == "__main__":
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    for nm in args or list(SCENARIOS):
        panels, kw = build(nm)
        for P in panels:
            print(P.table())
        if "--check" in sys.argv:
            continue
        out = f"img/anim-chase-{nm.replace('_', '-')}.gif"
        if "--debug" in sys.argv:
            animate(panels, out, debug=os.path.join(os.environ["ANIM_DEBUG"], "chase_" + nm), **kw)
        else:
            animate(panels, out, **kw)
