"""Lambert: the p window collapses as the transfer angle approaches 180 degrees."""
import numpy as np
import matplotlib.pyplot as plt
from _manstyle import CREAM, INK, MAROON, BLUE, GREEN, AMBER, PURPLE, despine
from _lambertp import p_window, tof_of_p

r1, r2 = 6678.137, 42164.0
pH = 2*r1*r2/(r1 + r2)
fig, (axL, axR) = plt.subplots(1, 2, figsize=(12.6, 5.4))

for deg, col in ((150, GREEN), (170, BLUE), (178, PURPLE), (179.8, MAROON)):
    dth = np.radians(deg)
    pi_, pii = p_window(r1, r2, dth)
    ps = np.linspace(pi_*(1 + 1e-7), pii*1.2 - 0.2*pi_, 4000)
    ts = np.array([tof_of_p(p, r1, r2, dth) for p in ps])/3600
    axL.semilogy(ps/pH, ts, color=col, lw=2.4, label=f"$\\Delta\\theta={deg}^\\circ$:  "
                 f"window $[{pi_/pH:.4f},\\ {pii/pH:.4f}]\\,p_H$")
axL.axvline(1.0, color=INK, lw=1.2, ls=(0, (5, 3)))
axL.text(1.003, 0.25, r"$p_H=\dfrac{2r_1r_2}{r_1+r_2}$", fontsize=11)
axL.set_xlim(0.92, 1.10); axL.set_ylim(0.1, 1000)
axL.set_xlabel(r"$p/p_H$"); axL.set_ylabel(r"time of flight  [h]")
axL.set_title("The admissible window pinches to a single $p$", fontsize=11.5)
axL.legend(frameon=False, fontsize=9, loc="upper right")
despine(axL)

# at exactly 180 deg: every connecting conic has p = pH; e sin f1 is free
a1, a2 = 1.0, 2.6
p = 2*a1*a2/(a1 + a2)
A = p/a1 - 1
for es, col in ((0.0, INK), (0.35, BLUE), (0.8, GREEN), (-0.35, PURPLE), (-1.3, MAROON)):
    e, f1 = np.hypot(A, es), np.arctan2(es, A)
    lim = np.arccos(-1/e) - 1e-3 if e >= 1 else np.pi
    ff = np.linspace(-lim, lim, 1500)
    rr = p/(1 + e*np.cos(ff))
    ok = rr < 7
    ang = ff - f1
    axR.plot(rr[ok]*np.cos(ang[ok]), rr[ok]*np.sin(ang[ok]), color=col, lw=0.9, alpha=0.35)
    fa = np.linspace(f1, f1 + np.pi, 300)
    ra = p/(1 + e*np.cos(fa))
    axR.plot(ra*np.cos(fa - f1), ra*np.sin(fa - f1), color=col, lw=2.4,
             label=f"$e\\sin f_1={es:+.2f}$,  $e={e:.2f}$")
axR.plot([a1, -a2], [0, 0], "o", color=INK, ms=8, zorder=6)
axR.plot([a1, -a2], [0, 0], color=INK, lw=1)
axR.plot(0, 0, "o", color=INK, ms=6)
axR.text(a1 + 0.1, -0.35, r"$\mathbf{r}_1$", fontsize=13)
axR.text(-a2 - 0.2, -0.45, r"$\mathbf{r}_2$", fontsize=13)
axR.set_xlim(-4.5, 2.6); axR.set_ylim(-3.2, 3.6)
axR.set_aspect("equal"); axR.axis("off")
axR.set_title(r"$\Delta\theta=180^\circ$: all share $p=p_H$; $p$ no longer labels them", fontsize=11.5)
axR.legend(frameon=False, fontsize=9, loc="lower left")

fig.tight_layout()
fig.savefig("img/fig-lam-180.png", dpi=160, bbox_inches="tight")
print("wrote img/fig-lam-180.png")
