"""Step 4b. Extremal functionals at larger c by homotopy in the central charge at fixed order P.

Why: the upward continuation in P of s04 stalls early for c >= 16 (logged in logs/s04_functional_c*.log).  The extremal
spectrum varies smoothly with c at fixed P, so we (i) continue in P at c = 4, where s04 is robust, and (ii) march in c
with an adaptive step and a secant predictor, re-solving F(t,d) = 0 by damped Newton at every step.
Verification at the recorded central charges is identical to s04 (grid positivity, exact division, cofactor roots,
half-mass identity).

Usage:  python code/s04b_functional_homotopy.py P [c_max]
Output: results/functional_homotopy_P{P}.json
"""
import sys, time
import mpmath as mp
import s04_functional_newton as S
from common import Tee, event, save_json

TARGETS = [4, 8, 12, 16, 24, 32, 48, 64]


def seed_c4(P):
    a = mp.mpf(3) / 12
    t = d = None
    for p in range(2, P + 1, 2):
        v, f0 = S.vacuum(a, p)
        tol = mp.mpf(10) ** (-(mp.mp.dps - 18))
        if p == 2:
            tg = [a + 2 / S.PI]
            t, d, nF, it, ok = S.newton(tg, S.lsq_weights(tg, v, f0, p), v, f0, p, tol)
            assert ok and d[0] > 0
        else:
            gap = (t[-1] - t[-2]) if len(t) > 1 else mp.mpf("1.3")
            for mult in (1.25, 1.0, 1.5, 0.8, 1.8, 2.2, 0.6, 2.8, 3.5):
                tg = list(t) + [t[-1] + gap * mp.mpf(mult)]
                tt, dd, nF, it, ok = S.newton(tg, S.lsq_weights(tg, v, f0, p), v, f0, p, tol)
                if ok and all(x > 0 for x in dd):
                    t, d = tt, dd
                    break
            else:
                raise RuntimeError(f"c=4 seed failed at P={p}")
    return t, d


def solve_at(c, P, t_guess, logd_guess):
    a = (mp.mpf(c) - 1) / 12
    v, f0 = S.vacuum(a, P)
    tol = mp.mpf(10) ** (-(mp.mp.dps - 18))
    dg = [mp.exp(x) for x in logd_guess]
    t, d, nF, it, ok = S.newton(list(t_guess), dg, v, f0, P, tol, maxit=40)
    ok = ok and all(x > 0 for x in d)
    return t, d, nF, it, ok, v


def main(P, cmax):
    mp.mp.dps = int(50 + 2.2 * P + 0.6 * cmax)
    S.PI = mp.pi
    t0 = time.time()
    t, d = seed_c4(P)
    print(f"  P={P}: c=4 seed solved by continuation in P [{time.time()-t0:.1f}s], Delta1 = {mp.nstr(mp.mpf(3)/12 + t[0], 14)}", flush=True)
    results = []
    c = mp.mpf(4)
    prev = None                     # (c, t, logd) of the previous accepted point
    cur = (c, list(t), [mp.log(x) for x in d])
    h = mp.mpf(1) / 2
    targets = [x for x in TARGETS if x <= cmax]
    nsteps = nfail = 0

    def record(ci, t, d):
        a = mp.mpf(ci - 1) / 12
        v, f0 = S.vacuum(a, P)
        alpha = S.functional(t, P)
        ver = S.verify(ci, P, t, d, alpha, v, with_roots=True, with_mass=True)
        rec = dict(c=ci, P=P, P_over_c=P / ci, dps=mp.mp.dps, t1=mp.nstr(t[0], 25), Delta1=mp.nstr(a + t[0], 25), Delta1_float=float(a + t[0]),
                   ratio_c_over_Delta1=float(ci / (a + t[0])), levels=[float(x) for x in t], log10_weights=[float(mp.log10(x)) for x in d],
                   weights_positive=bool(all(x > 0 for x in d)), provenance="fresh_optimizer_output", route="homotopy in c at fixed P")
        rec.update(ver)
        results.append(rec)
        tint = [x for x in ver.get("real_roots_between_vac_and_t1", []) if x > 0]
        print(f"  c={ci:3d} P={P:3d}: Delta1^(P) = {mp.nstr(a + t[0], 14)}  c/Delta1 = {rec['ratio_c_over_Delta1']:.6f}  gvac_rel={ver['gvac_rel']:.1e} "
              f"pos={ver.get('positive_on_halfline')} rem={ver.get('division_remainder_rel'):.1e} t_int={tint[-1] if tint else None} "
              f"f_neg={ver['neg_mass_below_t1_over_M']:.10f} u_g(0)={ver['u_g_at_0']:.5f} [{time.time()-t0:.0f}s]", flush=True)
        save_json(f"functional_homotopy_P{P}.json", {"P": P, "c_max": cmax, "results": results, "homotopy_steps": nsteps, "rejected_steps": nfail})

    record(4, t, d)
    ti = 1
    while ti < len(targets):
        target = mp.mpf(targets[ti])
        cn = min(c + h, target)
        # predictor
        if prev is not None:
            s = (cn - cur[0]) / (cur[0] - prev[0])
            tg = [cur[1][i] + s * (cur[1][i] - prev[1][i]) for i in range(len(t))]
            lg = [cur[2][i] + s * (cur[2][i] - prev[2][i]) for i in range(len(t))]
            if not all(tg[i] < tg[i + 1] for i in range(len(tg) - 1)):
                tg, lg = cur[1], cur[2]
        else:
            tg, lg = cur[1], cur[2]
        tt, dd, nF, it, ok, v = solve_at(cn, P, tg, lg)
        nsteps += 1
        if not ok:
            nfail += 1
            h /= 2
            if h < mp.mpf(1) / 4096:
                print(f"  P={P}: homotopy stalled at c={mp.nstr(c, 8)}; stopping")
                break
            continue
        prev = cur
        cur = (cn, tt, [mp.log(x) for x in dd])
        c = cn
        if it <= 6:
            h = min(h * mp.mpf("1.6"), mp.mpf(4))
        if c == target:
            record(int(target), tt, dd)
            ti += 1
    print(f"  P={P}: {nsteps} homotopy steps, {nfail} rejected; total {time.time()-t0:.0f}s")
    return results


if __name__ == "__main__":
    P = int(sys.argv[1]); cmax = int(sys.argv[2]) if len(sys.argv) > 2 else 64
    with Tee(f"s04b_homotopy_P{P}"):
        res = main(P, cmax)
        event("compute", f"Homotopy in c at order P={P}",
              f"reached c={res[-1]['c']}: Delta1^(P={P}) = {res[-1]['Delta1'][:13]}; all recorded functionals positive on [t1,inf): {all(r.get('positive_on_halfline') for r in res)}",
              outputs=[f"results/functional_homotopy_P{P}.json"])
