"""Chase, same orbit: cost and perigee of k-revolution phasing, 420 km, 20 degree gap."""
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

a = RE + 420.0; n = np.sqrt(mu/a**3); T = 2*np.pi/n; vc = np.sqrt(mu/a)
th = np.radians(20.0)
ks = np.arange(1, 13)
fig, (axL, axR) = plt.subplots(1, 2, figsize=(12.4, 4.9))
for sgn, col, lab in ((-1, MAROON, "target 20° ahead: drop, arrive early"),
                      (+1, BLUE, "target 20° behind: raise, arrive late")):
    Tph = T*(1 + sgn*th/(2*np.pi*ks))
    aph = (mu*(Tph/(2*np.pi))**2)**(1/3)
    dv = np.abs(np.sqrt(mu*(2/a - 1/aph)) - vc)*1e3
    alt = 2*aph - a - RE
    axL.plot(ks, 2*dv, "o-", color=col, lw=2.2, ms=6, label=f"{lab}: rendezvous")
    axL.plot(ks, dv, "s--", color=col, lw=1.4, ms=5, alpha=0.8, label="   intercept (first burn only)")
    axR.plot(ks, alt, "o-", color=col, lw=2.2, ms=6, label=lab)
axR.axhline(200, color=AMBER, lw=1.6, ls=(0, (5, 3)))
axR.text(8.2, 215, "200 km: practical floor (drag)", color=AMBER, fontsize=10)
axR.axhline(0, color=INK, lw=1.0)
axR.text(8.2, 12, "surface", fontsize=10)
axR.fill_between([0.5, 12.5], -150, 200, color=AMBER, alpha=0.08)
axL.set_xlabel("phasing revolutions $k$"); axL.set_ylabel(r"$\Delta v$  [m/s]")
axL.set_yscale("log"); axL.legend(frameon=False, fontsize=9)
axL.set_yticks([20, 30, 50, 100, 200, 300]); axL.set_yticklabels(["20", "30", "50", "100", "200", "300"])
axL.minorticks_off()
axL.set_title(r"Cost falls like $1/k$; intercept is exactly half", fontsize=11.5)
axR.set_xlabel("phasing revolutions $k$"); axR.set_ylabel("altitude of the far apsis  [km]")
axR.set_xlim(0.5, 12.5); axR.set_ylim(-150, 1000)
axR.legend(frameon=False, fontsize=9, loc="upper right")
axR.set_title("Dropping is limited by the atmosphere: $k\\geq3$", fontsize=11.5)
for ax in (axL, axR):
    despine(ax)
fig.tight_layout()
fig.savefig("img/fig-chase-coorbital.png", dpi=160, bbox_inches="tight")
print("wrote img/fig-chase-coorbital.png")
