"""Step 5. Reanalysis of [B] Table 2 (published finite-c gaps; INPUT points, not recomputed here).

(1) refit of t_1/c in the bases of [B] section 5.2 (eq. 5-meas), with window / form / weighting sensitivity;
(2) residuals against the parameter-free two-term law  Delta = c/Lambda_V + A_opt c^(1/3)  (Conj. 1(a));
(3) a competing gamma*log(c) term ([B] section 5.3);
(4) the "9.08" explanation of [B] section 5.2: AHT-type forms fitted to the exact two-term law on windows;
(5) leave-one-out, implementation I vs II, converged vs extrapolated rows;
(6) finite-c drift of the ratio c/Delta and of the local slope.
Outputs: results/table2_fits.csv, results/table2_residuals.csv, results/table2_window_drift.csv,
         results/table2_aht_forms.csv, results/table2_reanalysis.json
"""
import numpy as np
import mpmath as mp
from common import Tee, event, save_json, save_csv, read_csv, check

mp.mp.dps = 30
XS = mp.asinh(1) / mp.pi
XIS = float(XS**2 / 3)
LV = float(1 / (mp.mpf(1) / 12 + XS**2 / 3))
AOPT = float(-mp.airyaizero(1) * mp.asinh(1) / (3 * mp.sqrt(2) * mp.pi**4) ** (mp.mpf(1) / 3))

BASES = {
    "F3 {1,c^-2/3,c^-1}": [lambda c: c**0, lambda c: c ** (-2 / 3), lambda c: c ** (-1.0)],
    "F4 {1,c^-2/3,c^-1,c^-4/3} (paper)": [lambda c: c**0, lambda c: c ** (-2 / 3), lambda c: c ** (-1.0), lambda c: c ** (-4 / 3)],
    "F4log {1,c^-2/3,log(c)/c,c^-1}": [lambda c: c**0, lambda c: c ** (-2 / 3), lambda c: np.log(c) / c, lambda c: c ** (-1.0)],
    "F5 {1,c^-2/3,c^-1,c^-4/3,c^-5/3}": [lambda c: c**0, lambda c: c ** (-2 / 3), lambda c: c ** (-1.0), lambda c: c ** (-4 / 3), lambda c: c ** (-5 / 3)],
}


def lsq(c, y, basis, w=None):
    A = np.vstack([f(c) for f in basis]).T
    if w is None:
        w = np.ones_like(y)
    Aw = A * w[:, None]; yw = y * w
    coef, *_ = np.linalg.lstsq(Aw, yw, rcond=None)
    res = y - A @ coef
    cov = np.linalg.inv(Aw.T @ Aw)
    dof = len(y) - len(coef)
    return coef, res, cov, dof


def main():
    T = read_csv("table2_extracted.csv")
    c = np.array([float(r["c"]) for r in T]); D = np.array([float(r["Delta_inf"]) for r in T]); sig = np.array([float(r["sigma"]) for r in T])
    impl = np.array([r["impl"] for r in T]); conv = np.array([r["converged_Pmax_ge_4c"] == "True" for r in T])
    t1 = D - (c - 1) / 12
    y = t1 / c; sy = sig / c
    R = {"Lambda_V": LV, "xi_star": XIS, "A_opt": AOPT, "checks": []}
    C = R["checks"]

    print("== (1) refit of t_1/c  ([B] eq. 5-meas: xi_meas = 0.026240 +- 0.000025, Lambda_meas = 9.1263 +- 0.002)")
    fits = []
    for name, basis in BASES.items():
        for cmin in (24, 48, 64, 96, 128, 192, 256):
            m = c >= cmin
            if m.sum() < len(basis) + 3:
                continue
            for wname, w in (("unweighted", None), ("1/sigma", 1 / sy[m])):
                coef, res, cov, dof = lsq(c[m], y[m], basis, w)
                chi2 = float(np.sum((res / sy[m]) ** 2))
                xi = coef[0]; lam = 1 / (1 / 12 + xi)
                fits.append([name, cmin, int(m.sum()), wname, xi, lam, coef[1], float(np.sqrt(cov[0, 0])) if w is not None else "", chi2 / dof, float(np.max(np.abs(res)))])
    save_csv("table2_fits.csv", ["form", "c_min", "n_points", "weighting", "xi_fit", "Lambda_fit", "coef_c^-2/3", "xi_stat_err_weighted", "chi2_per_dof", "max_abs_residual_t1_over_c"], fits)
    central = [f for f in fits if f[0].startswith("F4 ") and f[1] == 24 and f[3] == "unweighted"][0]
    print(f"  central (paper's basis F4, all 24 rows, unweighted): xi = {central[4]:.6f}  Lambda = {central[5]:.4f}  coefficient of c^-2/3 = {central[6]:.4f}")
    C.append(check("xi_meas, basis {1,c^-2/3,c^-1,c^-4/3}, all rows, unweighted", central[4], 0.026240, 2.5e-5, "[B] eq. (5-meas)"))
    C.append(check("Lambda_meas", central[5], 9.1263, 2e-3, "[B] eq. (5-meas)"))
    uw = [f for f in fits if f[3] == "unweighted" and not f[0].startswith("F5")]
    xi_all = np.array([f[4] for f in uw]); lam_all = np.array([f[5] for f in uw]); A_all = np.array([f[6] for f in uw])
    print(f"  spread over forms F3/F4/F4log and windows c_min=24..256 (unweighted, {len(uw)} fits): xi in [{xi_all.min():.6f}, {xi_all.max():.6f}], "
          f"Lambda in [{lam_all.min():.4f}, {lam_all.max():.4f}], c^-2/3 coefficient in [{A_all.min():.4f}, {A_all.max():.4f}]")
    print(f"  theory: xi* = {XIS:.7f}, Lambda_V = {LV:.5f}, A_opt = {AOPT:.5f};   xi(Lambda=9.08) = {1/9.08-1/12:.5f}")
    R["fit_central"] = dict(xi=central[4], Lambda=central[5], A=central[6])
    R["fit_spread_unweighted_F3_F4_F4log"] = dict(xi_min=float(xi_all.min()), xi_max=float(xi_all.max()), Lambda_min=float(lam_all.min()), Lambda_max=float(lam_all.max()),
                                                 A_min=float(A_all.min()), A_max=float(A_all.max()), n_fits=len(uw), half_spread_xi=float((xi_all.max() - xi_all.min()) / 2),
                                                 half_spread_Lambda=float((lam_all.max() - lam_all.min()) / 2))
    f34 = [f for f in uw if f[0].startswith("F3") or f[0].startswith("F4 ")]
    R["fit_spread_F3_F4"] = dict(xi_min=min(f[4] for f in f34), xi_max=max(f[4] for f in f34), Lambda_min=min(f[5] for f in f34), Lambda_max=max(f[5] for f in f34),
                                 A_min=min(f[6] for f in f34), A_max=max(f[6] for f in f34))
    print(f"  restricted to power-law forms F3, F4: xi in [{R['fit_spread_F3_F4']['xi_min']:.6f}, {R['fit_spread_F3_F4']['xi_max']:.6f}], "
          f"Lambda in [{R['fit_spread_F3_F4']['Lambda_min']:.4f}, {R['fit_spread_F3_F4']['Lambda_max']:.4f}], A in [{R['fit_spread_F3_F4']['A_min']:.4f}, {R['fit_spread_F3_F4']['A_max']:.4f}]  (paper: A between 0.269 and 0.285)")
    f5 = [f for f in fits if f[0].startswith("F5") and f[3] == "unweighted"]
    R["fit_F5"] = dict(xi_min=min(f[4] for f in f5), xi_max=max(f[4] for f in f5), Lambda_min=min(f[5] for f in f5), Lambda_max=max(f[5] for f in f5))
    print(f"  over-parametrised F5 (5 terms; sensitivity only): Lambda in [{R['fit_F5']['Lambda_min']:.4f}, {R['fit_F5']['Lambda_max']:.4f}]")
    wf = [f for f in fits if f[3] == "1/sigma" and f[0].startswith("F4 ")]
    R["fit_weighted_F4"] = [dict(c_min=f[1], xi=f[4], Lambda=f[5], xi_err=f[7], chi2_dof=f[8]) for f in wf]
    for f in wf[:3]:
        print(f"  weighted by 1/sigma, F4, c>={f[1]}: xi = {f[4]:.6f} +- {f[7]:.1e} (stat), Lambda = {f[5]:.4f}, chi2/dof = {f[8]:.2f}")
    inside_xi = np.mean(np.abs(xi_all - 0.026240) <= 2.5e-5); inside_lam = np.mean(np.abs(lam_all - 9.1263) <= 2e-3)
    R["fraction_of_fits_inside_published_band"] = dict(xi=float(inside_xi), Lambda=float(inside_lam))
    print(f"  fraction of these fits inside the published band: xi {inside_xi:.2f}, Lambda {inside_lam:.2f}")

    print("== (2) residuals against the parameter-free two-term law (Conj. 1(a), conjectural)")
    two = c / LV + AOPT * c ** (1 / 3)
    r2 = D - two
    aht = c / 9.08 + 0.439 * np.log(c) - 0.896
    rows = [[int(c[i]), impl[i], bool(conv[i]), D[i], sig[i], c[i] / D[i], two[i], r2[i], r2[i] / sig[i], aht[i], D[i] - aht[i], c[i] / two[i]] for i in range(len(c))]
    save_csv("table2_residuals.csv", ["c", "impl", "converged", "Delta_inf", "sigma", "ratio", "two_term_law", "resid_two_term", "resid_two_term_over_sigma",
                                      "AHT_log_fit", "Delta_minus_AHT_log_fit", "ratio_two_term_law"], rows)
    print(f"  remainder Delta - c/Lambda_V - A_opt c^(1/3): min {r2.min():+.4f} (c={int(c[r2.argmin()])}), max {r2.max():+.4f} (c={int(c[r2.argmax()])}); at c=2048: {r2[-1]:+.4f} +- {sig[-1]:.3f}")
    print(f"  AHT log fit minus data at c=2048: {aht[-1]-D[-1]:+.3f}  (paper: 0.22, sigma = 0.010)")
    C.append(check("log-fit departure at c=2048", aht[-1] - D[-1], 0.22, 5e-3, "[B] Fig. 6 caption"))
    # O(1) remainder model r = r0 + r1 c^(-1/3)
    co, res, cov, dof = lsq(c, r2, [lambda c: c**0, lambda c: c ** (-1 / 3)])
    R["remainder"] = dict(min=float(r2.min()), max=float(r2.max()), at_2048=float(r2[-1]), fit_r0=float(co[0]), fit_r1=float(co[1]), rms_resid=float(np.sqrt(np.mean(res**2))))
    print(f"  remainder model r0 + r1 c^(-1/3): r0 = {co[0]:+.4f}, r1 = {co[1]:+.4f}, rms {np.sqrt(np.mean(res**2)):.4f}")

    print("== (3) competing log term: Delta = c/Lambda + A c^(1/3) + gamma log c + B   ([B] section 5.3: gamma in [-0.07, -0.005])")
    glist = []
    for cmin in (24, 48, 64, 96, 128, 192):
        m = c >= cmin
        co, res, cov, dof = lsq(c[m], D[m], [lambda c: c, lambda c: c ** (1 / 3), lambda c: np.log(c), lambda c: c**0])
        glist.append([cmin, 1 / co[0], co[1], co[2], co[3]])
        print(f"  c>={cmin:3d}: Lambda = {1/co[0]:.4f}, A = {co[1]:.4f}, gamma = {co[2]:+.4f}, B = {co[3]:+.4f}")
    R["gamma_log"] = dict(min=min(g[3] for g in glist), max=max(g[3] for g in glist), table=glist)
    # same with Lambda fixed to Lambda_V
    gl2 = []
    for cmin in (24, 64, 128):
        m = c >= cmin
        co, res, cov, dof = lsq(c[m], D[m] - c[m] / LV, [lambda c: c ** (1 / 3), lambda c: np.log(c), lambda c: c**0])
        gl2.append([cmin, co[0], co[1], co[2]])
        print(f"  Lambda fixed to Lambda_V, c>={cmin:3d}: A = {co[0]:.4f}, gamma = {co[1]:+.4f}, B = {co[2]:+.4f}")
    R["gamma_log_fixed_slope"] = gl2

    print("== (4) why earlier fits gave 9.08: AHT-type forms fitted to the exact law c/Lambda_V + A_opt c^(1/3)  ([B] section 5.2)")
    law = lambda cc: cc / LV + AOPT * cc ** (1 / 3)
    aht_rows = []
    for (lo, hi, ref) in ((300, 700, (9.085, 0.48)), (20, 300, (9.02, 0.28)), (500, 4000, (9.11, 0.71))):
        cc = np.arange(lo, hi + 1, 1.0)
        co, *_ = lsq(cc, law(cc), [lambda c: c, lambda c: np.log(c), lambda c: c**0])
        aht_rows.append(["c/L+g*log(c)+const on exact law", lo, hi, 1 / co[0], co[1], co[2], ref[0], ref[1]])
        print(f"  window [{lo},{hi}]: (Lambda_fit, gamma_fit) = ({1/co[0]:.3f}, {co[1]:.3f})   paper: ({ref[0]}, {ref[1]})")
        C.append(check(f"AHT-form Lambda_fit on [{lo},{hi}]", 1 / co[0], ref[0], 0.006, "[B] section 5.2"))
        C.append(check(f"AHT-form gamma_fit on [{lo},{hi}]", co[1], ref[1], 0.012, "[B] section 5.2"))
    cc = np.arange(300, 701, 1.0)
    co, *_ = lsq(cc, law(cc), [lambda c: c, lambda c: c**0]); A1 = 1 / co[0]
    co2, *_ = lsq(cc, law(cc), [lambda c: c, lambda c: c**0, lambda c: 1 / c]); A2 = 1 / co2[0]
    aht_rows.append(["c/A+B1 on exact law", 300, 700, A1, "", co[1], 9.004, ""]); aht_rows.append(["c/A+B1+B2/c on exact law", 300, 700, A2, "", co2[1], 9.043, ""])
    print(f"  c/A+B1: A = {A1:.3f} (paper 9.004; AHT 9.01);  c/A+B1+B2/c: A = {A2:.3f} (paper 9.043; AHT 9.04)")
    C.append(check("c/A+B1 on [300,700]", A1, 9.004, 0.004, "[B] section 5.2")); C.append(check("c/A+B1+B2/c on [300,700]", A2, 9.043, 0.004, "[B] section 5.2"))
    # the same AHT form applied to the Table 2 data themselves, sliding windows
    drift = []
    for (lo, hi) in ((24, 300), (100, 500), (300, 700), (500, 2048), (24, 2048)):
        m = (c >= lo) & (c <= hi)
        co, res, *_ = lsq(c[m], D[m], [lambda c: c, lambda c: np.log(c), lambda c: c**0])
        cp, resp, *_ = lsq(c[m], D[m], [lambda c: c, lambda c: c ** (1 / 3), lambda c: c**0])
        drift.append([lo, hi, int(m.sum()), 1 / co[0], co[1], float(np.sqrt(np.mean(res**2))), 1 / cp[0], cp[1], float(np.sqrt(np.mean(resp**2)))])
        print(f"  Table 2 data, window [{lo},{hi}] ({int(m.sum())} rows): log form Lambda = {1/co[0]:.3f} (gamma {co[1]:.3f}, rms {np.sqrt(np.mean(res**2)):.1e}) | "
              f"c^(1/3) form Lambda = {1/cp[0]:.3f} (A {cp[1]:.3f}, rms {np.sqrt(np.mean(resp**2)):.1e})")
    save_csv("table2_window_drift.csv", ["c_lo", "c_hi", "n", "Lambda_logform", "gamma_logform", "rms_logform", "Lambda_cuberoot_form", "A_cuberoot_form", "rms_cuberoot_form"], drift)
    save_csv("table2_aht_forms.csv", ["form", "c_lo", "c_hi", "Lambda_or_A", "gamma", "const", "paper_Lambda", "paper_gamma"], aht_rows)
    R["window_drift"] = drift
    R["drift_logform_Lambda_range"] = [min(d[3] for d in drift), max(d[3] for d in drift)]
    R["drift_cuberoot_Lambda_range"] = [min(d[6] for d in drift), max(d[6] for d in drift)]

    print("== (5) robustness: leave-one-out, implementation I vs II, converged vs extrapolated rows (basis F4, unweighted)")
    basis = BASES["F4 {1,c^-2/3,c^-1,c^-4/3} (paper)"]
    loo = []
    for i in range(len(c)):
        m = np.ones(len(c), bool); m[i] = False
        co, *_ = lsq(c[m], y[m], basis)
        loo.append([int(c[i]), co[0], 1 / (1 / 12 + co[0])])
    lam_loo = np.array([l[2] for l in loo])
    print(f"  leave-one-out: Lambda in [{lam_loo.min():.4f}, {lam_loo.max():.4f}]; most influential row c = {loo[int(np.argmax(np.abs(lam_loo-central[5])))][0]}")
    R["leave_one_out"] = dict(Lambda_min=float(lam_loo.min()), Lambda_max=float(lam_loo.max()), table=loo)
    sub = {}
    for nm, m in (("impl I (9 rows)", impl == "I"), ("impl II (15 rows)", impl == "II"), ("converged Pmax/c>=4 (14 rows)", conv), ("extrapolated Pmax/c<4 (10 rows)", ~conv)):
        b = basis if m.sum() >= 8 else BASES["F3 {1,c^-2/3,c^-1}"]
        co, res, *_ = lsq(c[m], y[m], b)
        sub[nm] = dict(xi=float(co[0]), Lambda=float(1 / (1 / 12 + co[0])), A=float(co[1]), n=int(m.sum()), basis_terms=len(b))
        print(f"  {nm}: Lambda = {sub[nm]['Lambda']:.4f}, A = {sub[nm]['A']:.4f} ({len(b)}-term basis)")
    R["subsets"] = sub
    # cross-prediction: fit on I, predict II
    co, *_ = lsq(c[impl == "I"], y[impl == "I"], basis)
    pred = np.vstack([f(c[impl == "II"]) for f in basis]).T @ co * c[impl == "II"] + (c[impl == "II"] - 1) / 12
    pull = (D[impl == "II"] - pred) / sig[impl == "II"]
    R["cross_prediction_I_to_II"] = dict(max_abs_diff=float(np.max(np.abs(D[impl == "II"] - pred))), max_abs_pull=float(np.max(np.abs(pull))), rms_pull=float(np.sqrt(np.mean(pull**2))))
    print(f"  fit on implementation I predicts the 15 implementation-II gaps to max |diff| {R['cross_prediction_I_to_II']['max_abs_diff']:.2e} (rms pull {R['cross_prediction_I_to_II']['rms_pull']:.2f} sigma, max {R['cross_prediction_I_to_II']['max_abs_pull']:.2f})")

    print("== (6) finite-c drift")
    ratio = c / D
    loc = np.diff(D) / np.diff(c)
    R["drift"] = dict(ratio_c24=float(ratio[0]), ratio_c2048=float(ratio[-1]), LambdaV_minus_ratio_2048=float(LV - ratio[-1]),
                      two_term_prediction_gap_2048=float(LV - 2048 / law(2048.0)),
                      local_slope_inverse_last=float(1 / loc[-1]), c_needed_for_0p01=float((LV**2 * AOPT / 0.01) ** 1.5),
                      c_needed_for_0p002=float((LV**2 * AOPT / 0.002) ** 1.5))
    print(f"  c/Delta rises from {ratio[0]:.4f} (c=24) to {ratio[-1]:.4f} (c=2048); distance to Lambda_V = {LV-ratio[-1]:.4f} "
          f"(two-term law predicts {R['drift']['two_term_prediction_gap_2048']:.4f})")
    print(f"  inverse local slope dc/dDelta between c=1800 and 2048: {1/loc[-1]:.4f}")
    print(f"  leading drift Lambda_V - c/Delta ~ Lambda_V^2 A_opt c^(-2/3): within 0.01 of Lambda_V needs c ~ {R['drift']['c_needed_for_0p01']:.2e}; within 0.002 needs c ~ {R['drift']['c_needed_for_0p002']:.2e}")
    # historical ladder ([B] Table 1 and section 1.2), values as quoted in [B]
    hist = [["Hellerman (2009/2011), lowest order", 6.0, "proved", "[B] Table 1, eq. (2-hellerman)"],
            ["Hartman-Mazac-Rastelli (2019), analytic functionals", 8.503, "proved", "[B] Table 1"],
            ["Afkhami-Jeddi-Hartman-Tajdini (2019), best finite-c bound c/8.956 at c=1800", 8.956, "numerical", "[B] section 1.2"],
            ["[B] Table 2, c=1800 (P->inf extrapolated)", float(ratio[c == 1800][0]), "numerical", "[B] Table 2"],
            ["[B] Table 2, c=2048", float(ratio[-1]), "numerical", "[B] Table 2"],
            ["AHT extrapolation with log c", 9.08, "numerical", "[B] section 1.2"],
            ["[B] extrapolation 24<=c<=2048", 9.1263, "numerical", "[B] eq. (5-meas)"],
            ["this work: refit of Table 2 (F4, unweighted)", central[5], "numerical (reanalysis)", "results/table2_fits.csv"],
            ["Lambda_V = 12 pi^2/(pi^2+4 asinh^2 1)", LV, "proved, computer-assisted ([B] Thm 1)", "[B] Thm 1"],
            ["Friedan-Keller / FKS ceiling", 12.0, "proved", "[B] Table 1, section 2.4"]]
    save_csv("slope_ladder.csv", ["entry", "Lambda", "status", "source"], hist)
    R["n_checks"] = len(C); R["n_pass"] = sum(x["pass"] for x in C)
    print(f"SUMMARY: {R['n_pass']}/{R['n_checks']} checks pass")
    save_json("table2_reanalysis.json", R)
    event("analyze", "Table 2 reanalysed", f"refit Lambda = {central[5]:.4f} (paper 9.1263+-0.002; Lambda_V = {LV:.4f}); log-form window drift {R['drift_logform_Lambda_range'][0]:.3f}-{R['drift_logform_Lambda_range'][1]:.3f}",
          outputs=["results/table2_fits.csv", "results/table2_residuals.csv", "results/table2_reanalysis.json"])


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