"""Step 9. Analysis of the fresh extremal functionals (s04, s04b) and comparison with the published Table 2 inputs.

  * merge the two routes (continuation in P; homotopy in c) and cross-check them where both exist;
  * anchors: Delta_1 = 1 at c = 4 and Delta_1 = 2 at c = 12 ([B] section 2.2), convergence in P;
  * stretched-exponential convergence [B] eq. (5-conv), extrapolation to P = infinity, comparison with Table 2;
  * a-posteriori certificates: positivity on [t_1, inf), g_vac = 0, half-mass identity = 1/2;
  * anatomy: interior zero t_int, u_g(0) vs U_0, Cardy height from the complex zeros, x_1 vs x*.
Outputs: results/functional_bounds.csv, results/functional_extrapolation.csv, results/functional_analysis.json
"""
import os, glob, json
import numpy as np
import mpmath as mp
from scipy.optimize import least_squares
from common import Tee, event, save_json, save_csv, read_csv, RES, check

XS = float(mp.asinh(1) / mp.pi)
U0 = -0.388747872


def main():
    recs = {}
    cross = []
    for fn in sorted(glob.glob(os.path.join(RES, "functional_c*.json"))) + sorted(glob.glob(os.path.join(RES, "functional_homotopy_P*.json"))):
        for r in json.load(open(fn))["results"]:
            key = (r["c"], r["P"])
            r["route"] = r.get("route", "continuation in P at fixed c")
            if key in recs:
                d = abs(mp.mpf(recs[key]["Delta1"]) - mp.mpf(r["Delta1"]))
                cross.append([key[0], key[1], recs[key]["Delta1"][:22], r["Delta1"][:22], float(d)])
                if "neg_mass_below_t1_over_M" in r and "neg_mass_below_t1_over_M" not in recs[key]:
                    r["both_routes"] = True
                    recs[key] = r
                else:
                    recs[key]["both_routes"] = True
            else:
                recs[key] = r
    keys = sorted(recs)
    R = {"checks": []}; C = R["checks"]
    print(f"fresh optimizer output: {len(keys)} (c,P) points; c in {sorted(set(k[0] for k in keys))}; max P per c: " + ", ".join(f"c={c}:{max(k[1] for k in keys if k[0]==c)}" for c in sorted(set(k[0] for k in keys))))
    mx = max(x[4] for x in cross) if cross else 0.0
    print(f"two routes (P-continuation vs c-homotopy) overlap on {len(cross)} points; max |Delta1 difference| = {mx:.1e}")
    R["route_cross_check"] = dict(n=len(cross), max_abs_diff=mx)
    C.append({"label": "P-continuation and c-homotopy give the same extremal gap", "computed": mx, "paper": 0.0, "absdiff": mx, "tol": 1e-20, "pass": bool(mx < 1e-20), "source": "this work (two routes)", "unit": ""})
    T2 = {int(r["c"]): r for r in read_csv("table2_extracted.csv")}
    rows = []
    for k in keys:
        r = recs[k]; c, P = k
        cp = c - 1
        t1 = float(r["t1"])
        tint = [x for x in r.get("real_roots_between_vac_and_t1", []) if x > 0]
        rows.append([c, P, P / c, r["Delta1"][:20], r["ratio_c_over_Delta1"], (3 * t1 / cp) ** 0.5, r["route"], r.get("both_routes", False), r["weights_positive"], r["gvac_rel"],
                     r.get("positive_on_halfline"), r.get("division_remainder_rel"), r.get("n_real_roots_above_t1"), tint[-1] if tint else "", len(tint),
                     r.get("neg_mass_below_t1_over_M", ""), r.get("u_g_at_0", ""), r.get("cardy_height_2ImB_median", ""), r.get("n_complex_roots", ""),
                     T2[c]["Delta_inf"] if c in T2 else ("1" if c == 4 else "2" if c == 12 else ""), "fresh_optimizer_output"])
    hdr = ["c", "P", "P_over_c", "Delta1_P", "c_over_Delta1", "x1", "route", "confirmed_by_both_routes", "weights_positive", "gvac_rel", "positive_on_halfline", "division_remainder_rel",
           "n_real_cofactor_roots_above_t1", "t_int", "n_zeros_between_0_and_t1", "neg_mass_fraction", "u_g_at_0", "cardy_height_median", "n_complex_roots", "reference_Delta_inf", "provenance"]
    save_csv("functional_bounds.csv", hdr, rows)
    allpos = all(recs[k].get("positive_on_halfline") for k in keys); allw = all(recs[k]["weights_positive"] for k in keys)
    maxg = max(recs[k]["gvac_rel"] for k in keys); maxrem = max(recs[k].get("division_remainder_rel", 0) for k in keys)
    print(f"certificates over all {len(keys)} points: positive on [t1,inf): {allpos}; dual weights positive: {allw}; max |g_vac|/scale = {maxg:.1e}; max division remainder = {maxrem:.1e}")
    C.append({"label": f"all {len(keys)} fresh functionals nonnegative on [t_1, inf) (grid + exact factorisation + cofactor roots)", "computed": int(allpos), "paper": 1, "absdiff": 0, "tol": 0, "pass": bool(allpos), "source": "[B] section 2.2 (extremal functional)", "unit": ""})
    C.append({"label": "all dual weights d_n > 0", "computed": int(allw), "paper": 1, "absdiff": 0, "tol": 0, "pass": bool(allw), "source": "[B] section 2.2", "unit": ""})
    fm = [(k, recs[k]["neg_mass_below_t1_over_M"], recs[k]["gvac_plus_2pi_int_gV_rel"]) for k in keys if "neg_mass_below_t1_over_M" in recs[k]]
    dev = max(abs(x[1] - 0.5) for x in fm); dev2 = max(x[2] for x in fm)
    print(f"half-mass identity [B] eq. (2-halfmass) on {len(fm)} functionals: max |f_neg - 1/2| = {dev:.1e}; max |g_vac + Int g rho_C|/(2 pi M) = {dev2:.1e}")
    C.append(check("negative Cardy-weighted mass below t_1 over M (extremal: exactly 1/2), worst case", 0.5 + dev, 0.5, 1e-9, "[B] eq. (2-halfmass), (2-gvac-cardy)"))
    R["half_mass"] = dict(n=len(fm), max_dev=dev, max_identity_violation=dev2, valid_weight_note="V >= 0 requires a >= 2, i.e. c >= 25; for smaller c the identity still holds but V is not sign-definite")
    nz = [recs[k] for k in keys]
    one_zero = all(len([x for x in r.get("real_roots_between_vac_and_t1", [])]) == 1 for r in nz)
    R["exactly_one_zero_between_vacuum_and_t1"] = bool(one_zero)
    print(f"exactly one zero between the vacuum and t_1 at every (c,P): {one_zero}  ([B] Conj. 1(e), numerical evidence only)")
    C.append({"label": "exactly one zero between the vacuum and t_1 at every (c,P)", "computed": int(one_zero), "paper": 1, "absdiff": 0, "tol": 0, "pass": bool(one_zero), "source": "[B] Conj. 1(e), section 5.3", "unit": ""})

    print("== anchors and convergence in the order P  ([B] section 2.2; eq. 5-conv)")
    ext = []
    def series(c):
        Ps = np.array([k[1] for k in keys if k[0] == c]); D = np.array([float(recs[(c, p)]["Delta1"]) for p in Ps])
        return Ps, D
    for c, exact in ((4, 1.0), (12, 2.0)):
        Ps, D = series(c)
        m = Ps >= 16
        slope, icpt = np.polyfit(np.sqrt(Ps[m] / c), np.log(D[m] - exact), 1)
        print(f"  c={c}: Delta1^(P) - {exact:.0f} falls from {D[0]-exact:.3e} (P=2) to {D[-1]-exact:.3e} (P={Ps[-1]}); log-linear in sqrt(P/c) with k = {-slope:.2f} (P>=16)")
        C.append(check(f"c={c}: Delta1^(P={Ps[-1]}) approaches the exact optimum {exact:.0f} from above", D[-1], exact, 2e-4 if c == 12 else 1e-6, "[B] section 2.2 (exact optima, ref. HMR)"))
        C.append({"label": f"c={c}: Delta1^(P) monotonically decreasing in P and > exact optimum", "computed": int(np.all(np.diff(D) < 0) and D[-1] > exact), "paper": 1, "absdiff": 0, "tol": 0,
                  "pass": bool(np.all(np.diff(D) < 0) and D[-1] > exact), "source": "[B] section 2.2", "unit": ""})
        ext.append([c, int(Ps[-1]), Ps[-1] / c, D[-1], exact, D[-1] - exact, "", -slope, "exact optimum", "", ""])
        R[f"anchor_c{c}"] = dict(Pmax=int(Ps[-1]), Delta_at_Pmax=float(D[-1]), excess=float(D[-1] - exact), k_fit=float(-slope))
    for c in (8, 16, 24, 32, 48, 64):
        Ps, D = series(c)
        m = Ps / c >= (0.8 if c <= 32 else 0.5)
        if m.sum() < 4:
            m = Ps >= Ps[-5]
        x = Ps[m] / c; y = D[m]
        # (i) s = 1/2 fixed:  D = Dinf + A exp(-k sqrt(x));  (ii) s free
        def res1(p):
            return p[0] + np.exp(p[1]) * np.exp(-p[2] * np.sqrt(x)) - y
        s1 = least_squares(res1, [y[-1] - 1e-3, np.log(max(y[0] - y[-1], 1e-6)) + 3, 5.0], xtol=1e-15, ftol=1e-15, gtol=1e-15, max_nfev=20000)
        def res2(p):
            return p[0] + np.exp(p[1]) * np.exp(-p[2] * x ** p[3]) - y
        try:
            s2 = least_squares(res2, list(s1.x) + [0.5], bounds=([0, -50, 0, 0.2], [np.inf, 50, 100, 1.5]), xtol=1e-15, ftol=1e-15, gtol=1e-15, max_nfev=40000)
            Dinf2, sfree = s2.x[0], s2.x[3]
        except Exception:
            Dinf2, sfree = np.nan, np.nan
        ref = float(T2[c]["Delta_inf"]) if c in T2 else None
        sig = float(T2[c]["sigma"]) if c in T2 else None
        above = bool(ref is None or D[-1] > ref)
        print(f"  c={c:2d}: P up to {Ps[-1]} (P/c = {Ps[-1]/c:.2f}); Delta1^(Pmax) = {D[-1]:.6f}; extrapolated Delta_inf = {s1.x[0]:.5f} (s=1/2, k = {s1.x[2]:.2f}) / {Dinf2:.5f} (s free = {sfree:.2f})"
              + (f"; Table 2: {ref:.6f} +- {sig:.1e}; fresh bound above published limit: {above}; extrapolation - Table 2 = {s1.x[0]-ref:+.4f} / {Dinf2-ref:+.4f}" if ref else "  (no Table 2 entry)"))
        ext.append([c, int(Ps[-1]), Ps[-1] / c, D[-1], ref if ref else "", (D[-1] - ref) if ref else "", s1.x[0], s1.x[2], "Table 2 (published input)" if ref else "none", Dinf2, sfree])
        R[f"extrap_c{c}"] = dict(Pmax=int(Ps[-1]), Delta_at_Pmax=float(D[-1]), Dinf_s_half=float(s1.x[0]), k_s_half=float(s1.x[2]), Dinf_s_free=float(Dinf2), s_free=float(sfree), table2=ref, table2_sigma=sig,
                                 n_fit_points=int(m.sum()))
        if ref:
            C.append({"label": f"c={c}: fresh finite-P bound lies above the published P=inf value (bound property)", "computed": float(D[-1]), "paper": ref, "absdiff": float(D[-1] - ref), "tol": 0, "pass": above,
                      "source": "[B] Table 2, section 2.2", "unit": ""})
    c24 = R["extrap_c24"]
    C.append(check("c=24: stretched-exponential extrapolation (s=1/2) of fresh data vs Table 2", c24["Dinf_s_half"], c24["table2"], 2e-3, "[B] Table 2 (c=24), eq. (5-conv)"))
    ks = [R[f"extrap_c{c}"]["k_s_half"] for c in (8, 16, 24, 32, 48, 64)] + [R["anchor_c4"]["k_fit"], R["anchor_c12"]["k_fit"]]
    R["k_range"] = [float(min(ks)), float(max(ks))]
    print(f"  fitted k in Delta^(P)-Delta^(inf) ~ C exp(-k sqrt(P/c)): {min(ks):.2f} .. {max(ks):.2f}   ([B] eq. 5-conv: k ~ 4.7-5.7, s = 0.57-0.58 in App. G.2)")
    save_csv("functional_extrapolation.csv", ["c", "Pmax", "Pmax_over_c", "Delta1_at_Pmax", "reference_value", "Delta1_minus_reference", "Dinf_fit_s_half", "k_fit", "reference_kind", "Dinf_fit_s_free", "s_free"], ext)

    print("== anatomy of the fresh functionals at the largest order per c")
    anat = []
    for c in sorted(set(k[0] for k in keys)):
        P = max(k[1] for k in keys if k[0] == c); r = recs[(c, P)]
        tint = [x for x in r.get("real_roots_between_vac_and_t1", []) if x > 0]
        x1 = (3 * float(r["t1"]) / (c - 1)) ** 0.5
        anat.append([c, P, x1, x1 - XS, tint[-1] if tint else "", 1 / (4 * np.pi) + 0.058 / c, r.get("u_g_at_0", ""), (U0 - r["u_g_at_0"]) if "u_g_at_0" in r else "",
                     r.get("cardy_height_2ImB_median", ""), r.get("cardy_height_2ImB_min", ""), r.get("cardy_height_2ImB_max", ""), r.get("n_complex_roots", "")])
        print(f"  c={c:2d} P={P:2d}: x_1 = {x1:.4f} (x* = {XS:.4f}); t_int = {tint[-1] if tint else float('nan'):.6f} (1/4pi + 0.058/c = {1/(4*np.pi)+0.058/c:.6f}); "
              + (f"u_g(0) = {r['u_g_at_0']:+.4f} (U_0 = {U0:+.4f}, U_0 - u_g(0) = {U0 - r['u_g_at_0']:+.4f}); " if "u_g_at_0" in r else "")
              + f"complex zeros: {r.get('n_complex_roots')} with 2|Im b| median {r.get('cardy_height_2ImB_median')}")
    save_csv("functional_anatomy.csv", ["c", "P", "x1", "x1_minus_xstar", "t_int", "t_int_paper_formula", "u_g_at_0", "U0_minus_u_g0", "cardy_height_median", "cardy_height_min", "cardy_height_max", "n_complex_roots"], anat)
    R["anatomy"] = anat
    r64 = recs[(64, max(k[1] for k in keys if k[0] == 64))]
    if "u_g_at_0" in r64:
        ok = r64["u_g_at_0"] <= U0 + 0.02
        C.append({"label": "u_g(0) of the fresh c=64 functional does not exceed the majorant U_0 by more than O(1/c')", "computed": r64["u_g_at_0"], "paper": U0, "absdiff": abs(r64["u_g_at_0"] - U0), "tol": 0.02, "pass": bool(ok),
                  "source": "[B] Prop. 6.4, section 6.7", "unit": ""})
        R["u_g0_c64"] = dict(P=r64["P"], u_g0=r64["u_g_at_0"], U0=U0, paper_note="[B] section 6.7 quotes U - u_g = 0.053 at (c,P) = (64,256); our order is lower")
    R["n_points"] = len(keys); R["n_checks"] = len(C); R["n_pass"] = sum(bool(c["pass"]) for c in C)
    print(f"SUMMARY: {R['n_pass']}/{R['n_checks']} checks pass")
    for c in C:
        if not c["pass"]:
            print("  NOT PASSED:", c["label"], c["computed"], c["paper"])
    save_json("functional_analysis.json", R)
    event("analyze", "Fresh extremal functionals analysed", f"{len(keys)} (c,P) points, all positive on [t1,inf): {allpos}; c=4 excess {R['anchor_c4']['excess']:.1e}, c=12 excess {R['anchor_c12']['excess']:.1e}; c=24 extrapolation {c24['Dinf_s_half']:.5f} vs Table 2 {c24['table2']}",
          outputs=["results/functional_bounds.csv", "results/functional_analysis.json"])


if __name__ == "__main__":
    with Tee("s09_functional_analysis"):
        main()
