"""Chase, terminal phase in CW: intercept and rendezvous share the first burn."""
import numpy as np
import _figfont                                # all figure text at one scale
import matplotlib.pyplot as plt
from _manstyle import CREAM, INK, MAROON, BLUE, GREEN, AMBER, PURPLE, despine
from _lambertp import mu, RE, cw_stm

a = RE + 420.0; n = np.sqrt(mu/a**3); T = 2*np.pi/n
X0 = np.array([-1.0, -10.0, 0.0, 1.5*n])          # 1 km below, 10 km behind, drifting

def targeting(tf):
    P = cw_stm(n, tf)
    vp = -np.linalg.solve(P[:2, 2:], P[:2, :2] @ X0[:2])
    vf = P[2:, :2] @ X0[:2] + P[2:, 2:] @ vp
    return vp, np.linalg.norm(vp - X0[2:]), np.linalg.norm(vf)

fig, (axL, axR) = plt.subplots(1, 2, figsize=(13.0, 5.2))
t = np.linspace(0, 2*T, 900)
drift = np.array([cw_stm(n, tt) @ X0 for tt in t])
axL.plot(drift[:, 1], drift[:, 0], color=INK, lw=1.2, ls=(0, (5, 3)), label="no burn: natural drift")
for frac, col in ((0.5, MAROON), (0.75, BLUE), (1.25, GREEN)):
    vp, d1, d2 = targeting(frac*T)
    tt = np.linspace(0, frac*T, 400)
    X = np.array([cw_stm(n, s) @ np.r_[X0[:2], vp] for s in tt])
    axL.plot(X[:, 1], X[:, 0], color=col, lw=2.4,
             label=f"$t_f={frac}T$:  $\\Delta v_1={1e3*d1:.2f}$, $\\Delta v_2={1e3*d2:.2f}$ m/s")
axL.plot(0, 0, "*", color=AMBER, ms=16, zorder=6); axL.text(0.3, 0.12, "target", fontsize=10)
axL.plot(X0[1], X0[0], "s", color=INK, ms=8); axL.text(X0[1] - 0.4, X0[0] - 0.05, "chaser", fontsize=10, ha="right", va="center")
axL.set_xlim(-13, 9); axL.set_ylim(-3.4, 1.6)
axL.set_xlabel("along-track $y$ [km]"); axL.set_ylabel("radial $x$ [km]")
axL.legend(frameon=False, fontsize=9, loc="upper left")
axL.set_title("Same arc for both: intercept skips the second burn", fontsize=11.5)
fr = np.linspace(0.08, 2.0, 3000)
d = np.array([targeting(f*T)[1:] for f in fr])*1e3
axR.semilogy(fr, d[:, 0] + d[:, 1], color=MAROON, lw=2.4, label="rendezvous  $\\Delta v_1+\\Delta v_2$")
axR.semilogy(fr, d[:, 0], color=BLUE, lw=2.0, label="intercept  $\\Delta v_1$")
axR.semilogy(fr, d[:, 1], color=GREEN, lw=1.4, ls=(0, (5, 3)), label="impact speed if not braked")
for s in (1.0, 8.8387/(2*np.pi), 2.0):
    axR.axvline(s, color=AMBER, lw=1.4, ls=(0, (4, 3)))
axR.text(1.01, 200, "$nt_f=2\\pi$", color=AMBER, fontsize=10)
axR.text(1.42, 200, "$nt_f=8.84$", color=AMBER, fontsize=10)
axR.text(1.98, 200, "$nt_f=4\\pi$", color=AMBER, fontsize=10, ha="right")
axR.set_ylim(0.3, 1000); axR.set_xlabel("transfer time $t_f/T$"); axR.set_ylabel(r"$\Delta v$ [m/s]")
axR.legend(frameon=False, fontsize=9.5, loc="upper left")
axR.set_title("Cost against the time allowed; singular times dashed", fontsize=11.5)
despine(axL); despine(axR)
fig.tight_layout()
fig.savefig("img/fig-chase-cw.png", dpi=160, bbox_inches="tight")
print("wrote img/fig-chase-cw.png")
