"""Problem 6: refine the transfers found by aditya-hoi-scan.py.

For a target time of flight, start from the nearest scan transfers and let Nelder-Mead move the
direction of the insertion dv; for each direction the magnitude is found (bisection) so that the
first perigee is at 256 km.  The objective is |dv| + (TOF - target)^2 * 0.5 m/s per day^2.
Every evaluated direction is itself a valid transfer, and all of them are kept.
Reads codes/data/aditya-hoi-scan-{A,B}.npy, writes codes/data/aditya-hoi-refined-<crossing>.npy.
Usage (from the sfm-slides directory):   python3 codes/aditya-hoi-refine.py A
"""
import sys
import numpy as np
from multiprocessing import Pool
from scipy.integrate import solve_ivp
from scipy.optimize import minimize

sys.path.insert(0, "codes")
from _imcommon import Re, AU, VU, TU, DAY, MU3, cr3bp, halo     # noqa: E402

WHICH = sys.argv[1] if len(sys.argv) > 1 else "A"
K = "AB".index(WHICH)
s0, T = halo(120000.0)
H = s0.copy() if K == 0 else solve_ivp(cr3bp, [0, T / 2], s0, rtol=1e-12, atol=1e-13).y[:, -1]
xE = 1 - MU3
DAYTU = DAY / TU
target_r = (Re + 256) / AU


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


def perigee(m, d):
    y = H.copy()
    y[3:] += m * d
    r = solve_ivp(cr3bp, [0, -260 * 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:
            return rr - target_r, -t / DAYTU
    return None


def solve_mag(d, m0):
    lo, hi = 0.8 * m0, 1.25 * m0
    a, b = perigee(lo, d), perigee(hi, d)
    if a is None or b is None or np.sign(a[0]) == np.sign(b[0]):
        return None
    fa = a[0]
    for _ in range(26):
        mid = 0.5 * (lo + hi)
        c = perigee(mid, d)
        if c is None:
            return None
        if np.sign(c[0]) == np.sign(fa):
            lo, fa = mid, c[0]
        else:
            hi = mid
    c = perigee(hi, d)
    return (hi, c[1]) if c is not None and abs(c[0]) * AU < 10 else None


def task(args):
    th, ph, m_ms, tgt = args
    seen = []
    state = {"m": m_ms / 1000 / VU}

    def f(x):
        d = np.array([np.sin(x[0]) * np.cos(x[1]), np.sin(x[0]) * np.sin(x[1]), np.cos(x[0])])
        s = solve_mag(d, state["m"])
        if s is None:
            return 1e4
        m, tof = s
        state["m"] = m
        seen.append((K, tof, m * VU * 1000, x[0], x[1]))
        return m * VU * 1000 + 0.5 * (tof - tgt) ** 2
    minimize(f, [th, ph], method="Nelder-Mead", options=dict(xatol=1e-4, fatol=0.05, maxfev=70,
                                                              initial_simplex=[[th, ph], [th + 0.05, ph], [th, ph + 0.05]]))
    return seen


if __name__ == "__main__":
    scan = np.load(f"codes/data/aditya-hoi-scan-{WHICH}.npy")
    jobs = []
    for tgt in (40, 60, 80, 95, 105, 110, 115, 125, 140, 160, 180, 200):
        near = scan[np.argsort(abs(scan[:, 1] - tgt) + scan[:, 2] / 20)][:3]
        jobs += [(r[3], r[4], r[2], tgt) for r in near]
    with Pool(11) as p:
        res = p.map(task, jobs)
    out = np.array([x for r in res for x in r])
    np.save(f"codes/data/aditya-hoi-refined-{WHICH}.npy", out)
    for lo in range(30, 260, 10):
        s = out[(out[:, 1] >= lo) & (out[:, 1] < lo + 10)]
        if len(s):
            print(f"{lo:3d}-{lo + 10:3d} d: {len(s):4d} transfers, cheapest {s[:, 2].min():6.1f} m/s", flush=True)
