"""Step 4. Fresh optimizer output: order-P extremal derivative functionals of [B] section 2.2, in multiprecision.

Problem ([B] eq. 2-deriv, 2-sumrule, section 5.1, App. G.2).  Basis phi_k(t) = L_{2k-1}(4 pi t) e^{-2 pi t}, k = 1..P.
Vacuum action  v_k = phi_k(-a) - 2 phi_k(-a+1) + phi_k(-a+2),  a = (c-1)/12.
Dual (extremal spectrum) unknowns: m = P/2 levels t_1 < ... < t_m and weights d_n > 0 with
        F_k(t,d) = v_k + sum_n d_n phi_k(t_n) = 0,      k = 1..P          (P equations, P unknowns).
The order-P gap bound is Delta_1^(P)(c) = a + t_1.  The extremal functional g = sum_k alpha_k phi_k is fixed (up to
scale) by g(t_1) = 0, g(t_n) = g'(t_n) = 0 (n >= 2); then g_vac = 0 follows from the sum rule.

Method: Newton with step damping, continued upward in P (P -> P+2 adds one level at the top), starting from the
analytic P = 2 problem (Hellerman).  Everything is original code written for this reproduction; nothing is taken
from the paper's solver, whose published values (Table 2) are used only for comparison.

A-posteriori verification for every (c, P):
  * weights d_n > 0, levels ordered, Newton residual;
  * g_vac / sum|alpha_k v_k|  ~ 0;
  * positivity of g on [t_1, t_m + 12] on a dense grid;
  * exact polynomial division p(t) = (t - t_1) prod (t - t_n)^2 r(t): remainder ~ 0, and r has no real root above t_1
    (roots of r by mpmath.polyroots) -> g >= 0 on the whole half-line [t_1, inf);
  * (selected cases) the half-mass identity [B] eq. (2-halfmass) with the Bessel weight V, i.e. eq. (2-gvac-cardy).

Usage:  python code/s04_functional_newton.py C PMAX [--mass]
Output: results/functional_c{C}.json
"""
import sys, time, json, os
import mpmath as mp
from common import Tee, event, save_json, RES

PI = None


def lag(x, N):
    """[L_0(x), ..., L_N(x)] by the three-term recurrence."""
    L = [mp.mpf(1), 1 - x]
    for n in range(1, N):
        L.append(((2 * n + 1 - x) * L[n] - n * L[n - 1]) / (n + 1))
    return L[: N + 1]


def phi(t, P, deriv=False):
    """phi_k(t), k=1..P (and d/dt if deriv)."""
    x = 4 * PI * t
    L = lag(x, 2 * P - 1)
    e = mp.exp(-2 * PI * t)
    f = [L[2 * k - 1] * e for k in range(1, P + 1)]
    if not deriv:
        return f
    df = []
    for k in range(1, P + 1):
        n = 2 * k - 1
        dL = n * (L[n] - L[n - 1]) / x          # dL_n/dx
        df.append((4 * PI * dL - 2 * PI * L[n]) * e)
    return f, df


def vacuum(a, P):
    f0, f1, f2 = phi(-a, P), phi(-a + 1, P), phi(-a + 2, P)
    v = [f0[k] - 2 * f1[k] + f2[k] for k in range(P)]
    return v, f0


def residual(t, d, v, scale, P):
    F = [v[k] / scale[k] for k in range(P)]
    cols = []
    for n in range(len(t)):
        f, df = phi(t[n], P, deriv=True)
        cols.append((f, df))
        for k in range(P):
            F[k] += d[n] * f[k] / scale[k]
    return F, cols


def norm(F):
    return mp.sqrt(sum(x * x for x in F))


def newton(t, d, v, scale, P, tol, maxit=60):
    m = len(t)
    F, cols = residual(t, d, v, scale, P)
    nF = norm(F)
    for it in range(maxit):
        if nF < tol:
            return t, d, nF, it, True
        J = mp.matrix(P, 2 * m)
        for n in range(m):
            f, df = cols[n]
            for k in range(P):
                J[k, n] = d[n] * df[k] / scale[k]
                J[k, m + n] = f[k] / scale[k]
        try:
            step = mp.lu_solve(J, mp.matrix([-x for x in F]))
        except ZeroDivisionError:
            return t, d, nF, it, False
        lam = mp.mpf(1)
        ok = False
        for _ in range(40):
            tn = [t[n] + lam * step[n] for n in range(m)]
            dn = [d[n] + lam * step[m + n] for n in range(m)]
            if all(tn[i] < tn[i + 1] for i in range(m - 1)) and tn[0] > 0:
                Fn, colsn = residual(tn, dn, v, scale, P)
                nn = norm(Fn)
                if nn < nF * (1 - lam / 4):
                    ok = True
                    break
            lam /= 2
        if not ok:
            return t, d, nF, it, False
        t, d, F, cols, nF = tn, dn, Fn, colsn, nn
    return t, d, nF, maxit, nF < tol


def lsq_weights(t, v, scale, P):
    """Least-squares weights for fixed levels (the problem is linear in d)."""
    m = len(t)
    A = mp.matrix(P, m)
    for n in range(m):
        f = phi(t[n], P)
        for k in range(P):
            A[k, n] = f[k] / scale[k]
    b = mp.matrix([-v[k] / scale[k] for k in range(P)])
    AtA = A.T * A
    d = mp.lu_solve(AtA, A.T * b)
    return [d[n] for n in range(m)]


def functional(t, P):
    """alpha_k with g(t_1)=0, g(t_n)=g'(t_n)=0 (n>=2), alpha_P = -1 (so that g > 0 at large t)."""
    rows = []
    f = phi(t[0], P); rows.append(f)
    for n in range(1, len(t)):
        f, df = phi(t[n], P, deriv=True)
        s = max(abs(x) for x in f + df)
        rows.append([x / s for x in f]); rows.append([x / s for x in df])
    A = mp.matrix(P - 1, P - 1); b = mp.matrix(P - 1, 1)
    for i, r in enumerate(rows):
        s = max(abs(x) for x in r)
        for k in range(P - 1):
            A[i, k] = r[k] / s
        b[i] = r[P - 1] / s          # move alpha_P = -1 to the right-hand side
    al = mp.lu_solve(A, b) if P > 1 else mp.matrix(0, 1)
    return [al[k] for k in range(P - 1)] + [mp.mpf(-1)]


def g_eval(alpha, t, P):
    f = phi(t, P)
    return sum(alpha[k] * f[k] for k in range(P))


def poly_coeffs(alpha, P):
    """Monomial coefficients (ascending, in t) of p(t) = sum_k alpha_k L_{2k-1}(4 pi t)."""
    N = 2 * P - 1
    co = [mp.mpf(0)] * (N + 1)
    for k in range(1, P + 1):
        n = 2 * k - 1
        for j in range(n + 1):
            co[j] += alpha[k - 1] * (-1) ** j * mp.binomial(n, j) / mp.factorial(j) * (4 * PI) ** j
    return co


def divide_linear(co_desc, root):
    """Synthetic division of a polynomial (descending coefficients) by (t - root): quotient, remainder."""
    q = [co_desc[0]]
    for c in co_desc[1:]:
        q.append(c + q[-1] * root)
    return q[:-1], q[-1]


def verify(c, P, t, d, alpha, v, with_roots=True, with_mass=False):
    a = mp.mpf(c - 1) / 12
    out = {}
    gv = sum(alpha[k] * v[k] for k in range(P))
    gs = sum(abs(alpha[k] * v[k]) for k in range(P))
    out["gvac_rel"] = float(abs(gv) / gs)
    # dense grid positivity
    tmax = t[-1] + 12
    ng = 200 * len(t) + 2400
    scale = max(abs(g_eval(alpha, t[0] + (tmax - t[0]) * i / 60, P)) for i in range(1, 61))
    gmin = None
    for i in range(1, ng + 1):
        tt = t[0] + (tmax - t[0]) * i / ng
        val = g_eval(alpha, tt, P) * mp.exp(2 * PI * (tt - t[0]))     # remove the trivial exponential
        gmin = val if gmin is None or val < gmin else gmin
    pscale = max(abs(g_eval(alpha, t[0] + (tmax - t[0]) * i / 60, P) * mp.exp(2 * PI * ((tmax - t[0]) * i / 60))) for i in range(1, 61))
    out["grid_min_over_scale"] = float(gmin / pscale)
    out["grid_points"] = ng
    out["grid_nonneg"] = bool(gmin >= -pscale * mp.mpf(10) ** (-(mp.mp.dps // 3)))
    if with_roots:
        co = poly_coeffs(alpha, P)[::-1]
        lead = co[0]
        q, r = divide_linear(co, t[0]); rem = [abs(r)]
        for n in range(1, len(t)):
            q, r1 = divide_linear(q, t[n]); q, r2 = divide_linear(q, t[n]); rem += [abs(r1), abs(r2)]
        csc = max(abs(x) for x in co)
        out["division_remainder_rel"] = float(max(rem) / csc)
        qn = [x / q[0] for x in q]
        roots = mp.polyroots(qn, maxsteps=400, extraprec=mp.mp.prec, error=False)
        cp = c - 1
        real_above = [float(mp.re(z)) for z in roots if abs(mp.im(z)) < mp.mpf(10) ** (-20) * (1 + abs(z)) and mp.re(z) > t[0]]
        real_between = sorted(float(mp.re(z)) for z in roots if abs(mp.im(z)) < mp.mpf(10) ** (-20) * (1 + abs(z)) and -a < mp.re(z) <= t[0])
        real_below = [float(mp.re(z)) for z in roots if abs(mp.im(z)) < mp.mpf(10) ** (-20) * (1 + abs(z)) and mp.re(z) <= -a]
        cplx = [z for z in roots if abs(mp.im(z)) >= mp.mpf(10) ** (-20) * (1 + abs(z))]
        heights = sorted(float(2 * abs(mp.im(mp.sqrt(3 * z / cp)))) for z in cplx if mp.im(z) > 0)
        out.update(n_cofactor_roots=len(roots), n_real_roots_above_t1=len(real_above), real_roots_between_vac_and_t1=real_between,
                   n_real_roots_below_vacuum=len(real_below), n_complex_roots=len(cplx),
                   cardy_height_2ImB_min=heights[0] if heights else None, cardy_height_2ImB_median=heights[len(heights) // 2] if heights else None,
                   cardy_height_2ImB_max=heights[-1] if heights else None,
                   complex_roots_b=[[float(mp.re(mp.sqrt(3 * z / cp))), float(mp.im(mp.sqrt(3 * z / cp)))] for z in cplx if mp.im(z) > 0][:60])
        out["positive_on_halfline"] = bool(out["grid_nonneg"] and len(real_above) == 0 and out["division_remainder_rel"] < 1e-15)
    if with_mass:
        old = mp.mp.dps
        al = alpha; tt = t
        Kf = lambda al_, x: mp.re(mp.besseli(0, 4 * PI * mp.sqrt(mp.mpc(al_ * x))))
        V = lambda x: Kf(a, x) - 2 * Kf(a - 1, x) + Kf(a - 2, x)
        pts = [mp.mpf(0)] + real_between_pts(out) + [x for x in tt] + [tt[-1] + 3, tt[-1] + 8, tt[-1] + 16, tt[-1] + 40]
        pts = sorted(set(pts))
        mp.mp.dps = 30
        gV = lambda x: g_eval(al, x, P) * V(x)
        pieces = [mp.quad(gV, [pts[i], pts[i + 1]]) for i in range(len(pts) - 1)]
        mp.mp.dps = old
        M = sum(abs(x) for x in pieces)
        neg = -sum(x for i, x in enumerate(pieces) if pts[i + 1] <= tt[0] and x < 0)
        net = sum(pieces)
        out["mass_M"] = mp.nstr(M, 12)
        out["neg_mass_below_t1_over_M"] = float(neg / M)
        out["int_gV_over_M"] = float(net / M)                       # = -g_vac/(2 pi M) -> 0 for the extremal functional
        out["gvac_plus_2pi_int_gV_rel"] = float(abs(gv + 2 * PI * net) / (2 * PI * M))
        out["V_positive_weight"] = bool(a >= 2)
        g0 = g_eval(al, mp.mpf(0), P)
        out["u_g_at_0"] = float(mp.log(abs(g0) / M) / (c - 1))
        prof = []
        for i in range(0, 41):
            x = mp.mpf(i) / 40 * mp.sqrt(3 * tt[0] / (c - 1)) * mp.mpf("1.6")
            val = abs(g_eval(al, (c - 1) * x * x / 3, P))
            prof.append([float(x), float(mp.log(val / M) / (c - 1)) if val > 0 else None])
        out["u_g_profile"] = prof
    return out


def real_between_pts(out):
    return [mp.mpf(x) for x in out.get("real_roots_between_vac_and_t1", []) if x > 0]


def run(c, Pmax, with_mass=False):
    global PI
    a_f = (c - 1) / 12
    results = []
    t = d = None
    for P in range(2, Pmax + 1, 2):
        mp.mp.dps = int(50 + 2.2 * P + 0.6 * c)
        PI = mp.pi
        a = mp.mpf(c - 1) / 12
        t0 = time.time()
        v, f0 = vacuum(a, P)
        scale = f0
        m = P // 2
        tol = mp.mpf(10) ** (-(mp.mp.dps - 18))
        if P == 2:
            best = None
            for guess in (a + 2 / PI, a + mp.mpf("0.3"), a + 1, a + mp.mpf("0.1")):
                tg = [mp.mpf(guess)]
                dg = lsq_weights(tg, v, scale, P)
                tt, dd, nF, it, ok = newton(tg, dg, v, scale, P, tol)
                if ok and dd[0] > 0 and (best is None or tt[0] > best[0][0]):
                    best = (tt, dd, nF, it)
            if best is None:
                raise RuntimeError("P=2 failed")
            t, d, nF, it = best
        else:
            gap = (t[-1] - t[-2]) if len(t) > 1 else mp.mpf("1.3")
            found = None
            for mult in (1.25, 1.0, 1.5, 0.8, 1.8, 2.2, 0.6, 2.8, 3.5):
                tg = [mp.mpf(x) for x in t] + [t[-1] + gap * mp.mpf(mult)]
                dg = lsq_weights(tg, v, scale, P)
                tt, dd, nF, it, ok = newton(tg, dg, v, scale, P, tol)
                if ok and all(x > 0 for x in dd):
                    found = (tt, dd, nF, it, mult)
                    break
            if found is None:
                print(f"  c={c} P={P}: continuation failed for all trial top levels; stopping at P={P-2}")
                break
            t, d, nF, it, mult = found
        alpha = functional(t, P)
        do_mass = with_mass and (P == Pmax or P in (8, 16, 24, 32, 48))
        ver = verify(c, P, t, d, alpha, v, with_roots=True, with_mass=do_mass)
        rec = dict(c=c, P=P, P_over_c=P / c, dps=mp.mp.dps, newton_iterations=it, newton_residual=float(nF),
                   t1=mp.nstr(t[0], 25), Delta1=mp.nstr(a + t[0], 25), Delta1_float=float(a + t[0]), ratio_c_over_Delta1=float(c / (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)),
                   seconds=time.time() - t0, provenance="fresh_optimizer_output")
        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={c:3d} P={P:3d}: Delta1^(P) = {mp.nstr(a + t[0], 14)}  c/Delta1 = {rec['ratio_c_over_Delta1']:.6f}  it={it} res={float(nF):.1e} "
              f"gvac_rel={ver['gvac_rel']:.1e} pos={ver.get('positive_on_halfline')} rem={ver.get('division_remainder_rel', float('nan')):.1e} "
              f"t_int={tint[-1] if tint else None} [{rec['seconds']:.1f}s]" + (f" f_neg={ver['neg_mass_below_t1_over_M']:.12f}" if do_mass else ""), flush=True)
        save_json(f"functional_c{c}.json", {"c": c, "a": a_f, "Pmax_requested": Pmax, "results": results})
    return results


if __name__ == "__main__":
    c = int(sys.argv[1]); Pmax = int(sys.argv[2]); wm = "--mass" in sys.argv
    with Tee(f"s04_functional_c{c}"):
        res = run(c, Pmax, with_mass=wm)
        if res:
            last = res[-1]
            event("compute", f"Fresh extremal functionals at c={c}",
                  f"orders P=2..{last['P']}: Delta1^(P={last['P']}) = {last['Delta1'][:14]} (c/Delta1 = {last['ratio_c_over_Delta1']:.5f}); positivity verified: {all(r.get('positive_on_halfline') for r in res)}",
                  outputs=[f"results/functional_c{c}.json"])
