"""Chase, elliptic: chaser (6800 km, 0.02) -> target (10000 km, 0.3), coaxial, porkchop in epoch."""
import numpy as np
import warnings
import _figfont                                # all figure text at one scale
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from _manstyle import CREAM, INK, MAROON, BLUE, GREEN, AMBER, PURPLE, despine
from _lambertp import mu, RE
from _chase_grids import grid
from _lambertp import state_planar

warnings.simplefilter("ignore")
orb1 = (6800.0, 0.02, 0.0, 0.0)                      # chaser at periapsis at t = 0
orb2 = (10000.0, 0.30, 0.0, np.radians(90.0))        # target at M = 90 deg at t = 0
t0s = np.linspace(0, 24, 481)*3600
dts = np.linspace(0.25, 2.5, 181)*3600
dv1, dv2 = grid("ell-B", orb1, orb2, t0s, dts)


def fill_specks(Z):
    """Fill isolated NaN cells (the solver divides by sin(dtheta) on the 180-degree line)."""
    Z = Z.copy()
    for i, j in zip(*np.where(np.isnan(Z))):
        nb = [Z[a, b] for a, b in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1))
              if 0 <= a < Z.shape[0] and 0 <= b < Z.shape[1] and np.isfinite(Z[a, b])]
        if len(nb) >= 3:
            Z[i, j] = np.mean(nb)
    return Z


dv1, dv2 = fill_specks(dv1), fill_specks(dv2)
tot, dv1k = (dv1 + dv2)*1e3, dv1*1e3
# transfer angle on the grid, for the 180-degree line
n1, n2 = np.sqrt(mu/orb1[0]**3), np.sqrt(mu/orb2[0]**3)
DTH = np.empty((len(dts), len(t0s)))
for j, t0 in enumerate(t0s):
    R1 = state_planar(orb1[0], orb1[1], orb1[2], orb1[3] + n1*t0)[0]
    for i, dt in enumerate(dts):
        R2 = state_planar(orb2[0], orb2[1], orb2[2], orb2[3] + n2*(t0 + dt))[0]
        DTH[i, j] = np.arctan2(R1[0]*R2[1] - R1[1]*R2[0], R1 @ R2)
SIN180 = np.ma.masked_where(np.cos(DTH) > 0, np.sin(DTH))
fig, axs = plt.subplots(2, 1, figsize=(12.6, 8.6), sharex=True)
levels = [1170, 1500, 2000, 3000, 5000]
for ax, Z, lab in ((axs[0], tot, r"rendezvous $\Delta v_1+\Delta v_2$ [m/s]"),
                   (axs[1], dv1k, r"intercept $\Delta v_1$ [m/s]")):
    lv = levels if Z is tot else [100, 200, 400, 700, 1000, 1500, 2500, 4000]
    cs = ax.contourf(t0s/3600, dts/3600, np.clip(Z, lv[0]*0.9, 8000), levels=[lv[0]*0.9] + lv + [8000],
                     norm=LogNorm(lv[0]*0.9, 8000), cmap="magma_r")
    ax.contour(t0s/3600, dts/3600, Z, levels=lv, colors=INK, linewidths=0.4)
    cb = fig.colorbar(cs, ax=ax, ticks=lv); cb.ax.set_yticklabels([str(l) for l in lv])
    ax.set_facecolor("#e9e4da")
    ax.set_ylabel("time of flight [h]")
    ax.set_title(lab, fontsize=11.5)
    ax.contour(t0s/3600, dts/3600, SIN180, levels=[0], colors=[CREAM], linewidths=1.4, linestyles="dashed")
    i, j = np.unravel_index(np.nanargmin(Z), Z.shape)
    ax.plot(t0s[j]/3600, dts[i]/3600, "*", color=CREAM, mec=INK, ms=16)
    ax.annotate(f"best on the grid: depart {t0s[j]/3600:.2f} h, fly {dts[i]/3600:.3f} h, {Z[i, j]:.0f} m/s",
                (t0s[j]/3600, dts[i]/3600), xytext=(-330, 14), textcoords="offset points", fontsize=10,
                arrowprops=dict(arrowstyle="->", color=INK, lw=0.9),
                bbox=dict(fc=CREAM, ec=INK, lw=0.5))
    print(lab, "best", t0s[j]/3600, dts[i]/3600, Z[i, j])
axs[1].set_xlabel("departure epoch $t_0$ [h]")
fig.tight_layout()
fig.savefig("img/fig-chase-porkchop-ell.png", dpi=160, bbox_inches="tight")
print("wrote img/fig-chase-porkchop-ell.png")
