"""Chase, circular 300 -> 420 km: cost over (departure phase angle, time of flight)."""
import numpy as np
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

r1, r2 = RE + 300.0, RE + 420.0
n1, n2 = np.sqrt(mu/r1**3), np.sqrt(mu/r2**3)
at = 0.5*(r1 + r2); tH = np.pi*np.sqrt(at**3/mu)
dvH = (np.sqrt(mu*(2/r1 - 1/at)) - np.sqrt(mu/r1)) + (np.sqrt(mu/r2) - np.sqrt(mu*(2/r2 - 1/at)))
lead = np.degrees(np.pi - n2*tH)
# For circular orbits only the phase at departure matters: chaser at M=0, target at M=theta.
phis = np.linspace(-40, 30, 281)
dts = np.linspace(10, 85, 151)*60
# grid() takes epochs; emulate phase by a zero-rate chaser epoch trick: build columns by phase.
dv1 = np.full((len(dts), len(phis)), np.nan); dv2 = dv1.copy()
import os
from _chase_grids import CACHE, solve
fn = os.path.join(CACHE, "circ-phase.npz")
if os.path.exists(fn):
    d = np.load(fn); dv1, dv2 = d["dv1"], d["dv2"]
else:
    R1, V1 = np.array([r1, 0.0]), np.array([0.0, np.sqrt(mu/r1)])
    for j, ph in enumerate(np.radians(phis)):
        for i, dt in enumerate(dts):
            th = ph + n2*dt
            R2 = r2*np.array([np.cos(th), np.sin(th)])
            V2 = np.sqrt(mu/r2)*np.array([-np.sin(th), np.cos(th)])
            dv1[i, j], dv2[i, j] = solve(R1, V1, R2, V2, dt)
    np.savez(fn, dv1=dv1, dv2=dv2)


def fill_specks(Z):
    """Fill isolated NaN cells (the Lambert solver divides by sin(dtheta) and fails exactly on the
    180-degree line) from their finite neighbours; genuine infeasible regions are left alone."""
    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) * 1e3, fill_specks(dv2) * 1e3
tot = dv1 + dv2
# the transfer angle: dtheta = theta + n2 dt; the 180-degree line separates short-way from long-way arcs
dt180 = np.linspace(dts[0], dts[-1], 400)
th180 = 180 - np.degrees(n2 * dt180)

fig = plt.figure(figsize=(13.0, 8.4))
gs = fig.add_gridspec(2, 2, height_ratios=[1.25, 1])
axA, axB, axC = fig.add_subplot(gs[0, 0]), fig.add_subplot(gs[0, 1]), fig.add_subplot(gs[1, :])
levels = [70, 100, 150, 250, 400, 700, 1000, 2000, 4000]
for ax, Z, title in ((axA, tot, r"rendezvous  $\Delta v_1+\Delta v_2$  [m/s]"),
                     (axB, dv1, r"intercept  $\Delta v_1$  [m/s]")):
    cs = ax.contourf(phis, dts/60, np.clip(Z, 30, 5000), levels=[30] + levels + [5000],
                     norm=LogNorm(30, 5000), cmap="magma_r")
    ax.contour(phis, dts/60, Z, levels=levels, colors=INK, linewidths=0.5)
    ax.plot(lead, tH/60, "*", color=CREAM, mec=INK, ms=16)
    ok_ = (th180 >= phis[0]) & (th180 <= phis[-1])
    ax.plot(th180[ok_], dt180[ok_]/60, color=CREAM, lw=1.6, ls=(0, (5, 3)))
    ax.text(th180[ok_][-1] + 1, dt180[ok_][-1]/60 - 1, r"$\Delta\theta=180^\circ$: short way below, long way above",
            fontsize=9, color=INK, ha="left", va="top", bbox=dict(fc=CREAM, ec="none", alpha=0.8, pad=1))
    ax.set_facecolor("#e9e4da")
    ax.set_xlabel(r"phase angle at departure $\theta$ [deg]  (target ahead $>0$)")
    ax.set_ylabel("time of flight [min]")
    ax.set_title(title, fontsize=11.5)
    cb = fig.colorbar(cs, ax=ax, ticks=levels)
    cb.ax.set_yticklabels([str(l) for l in levels])
for ax in (axA, axB):
    ax.text(27, 12, "grey: every arc\ndips below 100 km", fontsize=9.5, ha="right",
            bbox=dict(fc=CREAM, ec=INK, lw=0.5))
import warnings; warnings.simplefilter("ignore")
best_r = np.nanmin(tot, axis=0); best_i = np.nanmin(dv1, axis=0)
axC.semilogy(phis, best_r, color=MAROON, lw=2.6, label="best rendezvous over time of flight")
axC.semilogy(phis, best_i, color=BLUE, lw=2.2, label="best intercept over time of flight")
axC.axhline(1e3*dvH, color=INK, lw=1.4, ls=(0, (6, 4)))
axC.text(8, 1e3*dvH*0.62, f"Hohmann {1e3*dvH:.1f} m/s at $\\theta^*={lead:.2f}^\\circ$", fontsize=10)
axC.axvline(lead, color=INK, lw=0.8)
sec = axC.secondary_xaxis("top", functions=(lambda th: (40 - th)/np.degrees(n1 - n2)/3600,
                                            lambda h: 40 - h*3600*np.degrees(n1 - n2)))
sec.set_xlabel(r"waiting time to reach this phase, starting from $\theta_0=40^\circ$  [h]")
axC.set_xlabel(r"phase angle at departure $\theta$ [deg]")
axC.set_ylabel(r"$\Delta v$ [m/s]"); axC.set_xlim(phis[0], phis[-1])
axC.legend(frameon=False, fontsize=10, loc="upper left")
despine(axC)
fig.tight_layout()
fig.savefig("img/fig-chase-porkchop-circ.png", dpi=160, bbox_inches="tight")
print("wrote img/fig-chase-porkchop-circ.png")
for th in (-20, -10, -5, 0, 2.38, 5, 10, 12):
    j = np.argmin(abs(phis - th))
    print(f"theta={phis[j]:6.1f}  best rdv={best_r[j]:8.2f}  at dt={dts[np.nanargmin(tot[:, j])]/60 if np.isfinite(best_r[j]) else np.nan:6.2f} min  best int={best_i[j]:8.2f}")
