"""Problem 6: the cost of halo-orbit insertion against the transfer time, for Aditya-L1.

Start at either xz-plane crossing of the halo (A: z = +120 000 km, Sun side of L1; B: the
other crossing), add a trial insertion dv (direction on a grid, magnitude scanned), and
integrate *backwards* in the CR3BP to the first perigee.  Keep the trajectories whose perigee is
at 256 km altitude (EBN#4's perigee), found by bisection on the magnitude.  Each one is a
transfer from that perigee to the halo, with its time of flight and its insertion dv.
Writes codes/data/aditya-hoi-scan-<crossings>.npy; about an hour per crossing.
Usage: python3 codes/aditya-hoi-scan.py [A|B|AB]
Run from the sfm-slides directory:   python3 codes/aditya-hoi-scan.py
"""
import sys, time, numpy as np
sys.path.insert(0, "codes")
from _imcommon import *
from scipy.integrate import solve_ivp

s0, T = halo(120000.0)
HA = s0.copy()
HB = solve_ivp(cr3bp, [0, T / 2], s0, rtol=1e-12, atol=1e-13).y[:, -1]
xE = 1 - MU3; DAYTU = DAY / TU
target = (Re + 256) / AU


def ev(t, y):
    d = y[:3] - [xE, 0, 0]
    return d @ y[3:]


def first_perigee(H, dv, tmax=260):
    y = H.copy(); y[3:] += dv
    r = solve_ivp(cr3bp, [0, -tmax * DAYTU], y, rtol=1e-10, atol=1e-12, events=ev)
    for t, yy in zip(r.t_events[0], r.y_events[0]):
        rr = np.linalg.norm(yy[:3] - [xE, 0, 0])
        if rr * AU < 60000:                      # a genuine Earth approach
            return rr, -t, yy
    return None


out = []
mags = np.concatenate([np.linspace(0.5, 20, 14), np.linspace(25, 400, 30)]) / 1000 / VU
t0 = time.time()
WHICH = sys.argv[1] if len(sys.argv) > 1 else "AB"
for name, H in [(n, h) for n, h in (("A", HA), ("B", HB)) if n in WHICH]:
    for th in np.linspace(0, np.pi, 13)[1:-1]:          # polar angle from +z
        for ph in np.linspace(0, 2 * np.pi, 24, endpoint=False):
            d = np.array([np.sin(th) * np.cos(ph), np.sin(th) * np.sin(ph), np.cos(th)])
            prev = None
            for m in mags:
                fp = first_perigee(H, m * d)
                val = None if fp is None else fp[0] - target
                if prev is not None and val is not None and np.sign(val) != np.sign(prev[1]):
                    lo, hi, flo = prev[0], m, prev[1]
                    for _ in range(30):
                        mid = (lo + hi) / 2; fm = first_perigee(H, mid * d)
                        if fm is None:
                            break
                        if np.sign(fm[0] - target) == np.sign(flo):
                            lo, flo = mid, fm[0] - target
                        else:
                            hi = mid
                    fm = first_perigee(H, hi * d)
                    if fm is not None and abs(fm[0] - target) * AU < 5:
                        rr, tof, yy = fm
                        vin = yy[3:] + np.cross([0, 0, 1], yy[:3] - [xE, 0, 0])
                        out.append((0 if name == "A" else 1, tof / DAYTU, hi * VU * 1000, th, ph,
                                    np.linalg.norm(vin) * VU))   # crossing, TOF [d], HOI [m/s], angles, perigee speed
                        print("%s th %.2f ph %.2f  TOF %.1f d  HOI %.1f m/s  perigee speed %.4f" %
                              (name, th, ph, tof / DAYTU, hi * VU * 1000, out[-1][-1]), flush=True)
                prev = (m, val) if val is not None else None
        np.save(f"codes/data/aditya-hoi-scan-{WHICH}.npy", np.array(out))
    print(name, "done after %.0f s" % (time.time() - t0), flush=True)
np.save(f"codes/data/aditya-hoi-scan-{WHICH}.npy", np.array(out))
print("done", flush=True)
