"""Wilson lattice gauge theory, SU(2). Round 6: second seed.

Same measurement setup as Round 5 (8^4, 400 thermalization + 1500
measurement sweeps, Metropolis checkerboard, APE smearing alpha 0.5
levels 0/2/4, GEVP, jackknife), but a SECOND independent seed:
seed base 20261121 instead of 20261120, at beta 2.5 and 2.6.

The question is whether the Round 5 five-point torelon
extrapolation instability was seed noise. Round 5 (seed 1) put the
beta 2.6 point above the beta 2.5 point, breaking the prior downward
trend and weakening the fit (intercept 2.423 +/- 0.739, chi2/dof
7.60/3). If the second seed reproduces the seed 1 points within
combined errors, the instability is a property of the setup, not of
one Monte Carlo chain. If it overturns them, the points were noise.

Comparisons reported:
  - Per beta (2.5, 2.6): seed 1 vs seed 2 for plaquette, string
    tension, torelon (pick_mass rule), and variational GEVP 0++
    ground state, with agree-within-combined-errors verdicts.
  - Torelon extrapolation A: the Round 5 five-point series (seed 1
    at all betas), reproduced for reference.
  - Torelon extrapolation B: five-point series with seed 2 points at
    2.5 and 2.6 (seed 1 at 2.2, 2.3, 2.4).
  - Torelon extrapolation C: five-point series with inverse-variance
    weighted seed means at 2.5 and 2.6.

Same caveats as every round: finite spacing only, possible
excited-state contamination in the torelon, uncontrolled
finite-volume effects, linear a^2 form assumed, no continuum claim.

Run: python3 wilson_lattice_r6.py (from the lab root).
Output: data/yang_mills_r6.json; checkpoint
data/yang_mills_r6_checkpoint.json after each beta.
"""

import json
import math
import os
import sys
import time

import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from wilson_lattice_r5 import run, SMEAR_LEVELS, APE_ALPHA  # noqa: E402


def pick_mass(masses):
    """Best effective mass: m_eff(1) when it exists with relative
    jackknife error under 50 percent, else m_eff(0). Same rule as
    rounds 1-5."""
    m1 = masses.get("m_eff(1)", {})
    if (m1.get("value") is not None and m1.get("error") is not None
            and m1["error"] < 0.5 * abs(m1["value"])):
        return m1
    return masses.get("m_eff(0)", {})


def usable(m):
    return (m.get("value") is not None and m.get("error") is not None
            and m["error"] < 0.5 * abs(m["value"]))


def agree(a, b):
    """True when two estimates agree within combined errors, False
    when they disagree, None when the comparison cannot be made."""
    if a.get("value") is None or b.get("value") is None:
        return None
    if a.get("error") is None or b.get("error") is None:
        return None
    diff = abs(a["value"] - b["value"])
    comb = math.sqrt(a["error"] ** 2 + b["error"] ** 2)
    return diff <= comb


def weighted_mean(a, b):
    """Inverse-variance weighted mean of two estimates."""
    wa = 1.0 / a["error"] ** 2
    wb = 1.0 / b["error"] ** 2
    val = (a["value"] * wa + b["value"] * wb) / (wa + wb)
    err = math.sqrt(1.0 / (wa + wb))
    return {"value": val, "error": err}


def fit_torelon(points):
    """Weighted linear fit y = c0 + c1 * x, x = sigma a^2, weights
    1 / ey^2. Same method as rounds 2, 3 and 5."""
    xs = np.array([p["sigma_a2"] for p in points])
    ys = np.array([p["m_tor_over_sqrt_sigma"] for p in points])
    es = np.array([p["m_tor_over_sqrt_sigma_error"] for p in points])
    X = np.column_stack([np.ones_like(xs), xs])
    W = np.diag(1.0 / es ** 2)
    XtWX = X.T @ W @ X
    cov = np.linalg.inv(XtWX)
    coef = cov @ (X.T @ W @ ys)
    resid = ys - X @ coef
    chi2 = float(np.sum((resid / es) ** 2))
    dof = len(points) - 2
    return {
        "continuum_value_c0": float(coef[0]),
        "continuum_value_error": float(math.sqrt(cov[0, 0])),
        "slope_c1": float(coef[1]),
        "slope_error": float(math.sqrt(cov[1, 1])),
        "chi2": chi2,
        "dof": dof,
    }


def torelon_point(r):
    """One torelon series point from a run dict."""
    s = r["string_tension"]
    m = pick_mass(r["torelon_effective_masses"])
    y = m["value"] / math.sqrt(s["value"])
    ey = y * math.sqrt((m["error"] / m["value"]) ** 2
                       + (0.5 * s["error"] / s["value"]) ** 2)
    return {
        "beta": r["beta"],
        "sigma_a2": s["value"],
        "sigma_a2_error": s["error"],
        "m_tor": m["value"],
        "m_tor_error": m["error"],
        "m_tor_over_sqrt_sigma": y,
        "m_tor_over_sqrt_sigma_error": ey,
    }


def load_runs(fname):
    here = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(here, "..", "data", fname)) as f:
        return json.load(f)["runs"]


def main():
    t_start = time.time()
    here = os.path.dirname(os.path.abspath(__file__))
    ckpt_path = os.path.join(here, "..", "data",
                             "yang_mills_r6_checkpoint.json")
    seed_base = 20261121
    runs = []
    if os.path.exists(ckpt_path):
        with open(ckpt_path) as f:
            runs = json.load(f).get("runs", [])
        print(f"checkpoint found: reusing completed betas "
              f"{[r['beta'] for r in runs]}", flush=True)
    done_betas = {r["beta"] for r in runs}
    for beta in (2.5, 2.6):
        if beta in done_betas:
            print(f"beta {beta} already complete in checkpoint, skipping",
                  flush=True)
            continue
        print(f"Round 6: beta={beta} on 8^4 SU(2), seed base {seed_base}",
              flush=True)
        runs.append(run(beta, seed=seed_base))
        print(f"beta {beta} 8^4 done in {runs[-1]['runtime_seconds']:.1f} s",
              flush=True)
        with open(ckpt_path, "w") as f:
            json.dump({"runs": runs, "date": "2026-11-21",
                       "seed": seed_base}, f, indent=2)
        print(f"checkpoint written: {ckpt_path}", flush=True)
    total = time.time() - t_start

    # Seed 1 reference runs: beta 2.5 from round 3, beta 2.6 from round 5.
    seed1 = {}
    for r in load_runs("yang_mills_r3.json"):
        if str(r["beta"]) == "2.5" and r["lattice"] == "8^4":
            seed1[2.5] = r
    for r in load_runs("yang_mills_r5.json"):
        if str(r["beta"]) == "2.6":
            seed1[2.6] = r

    # Per-beta seed comparison.
    comparison = {}
    for r in runs:
        b = r["beta"]
        s1 = seed1[b]
        tor1 = pick_mass(s1["torelon_effective_masses"])
        tor2 = pick_mass(r["torelon_effective_masses"])
        # Round 3 predates the variational analysis, so the seed 1
        # beta 2.5 run has no GEVP ground state; record the absence
        # instead of crashing.
        vg1 = s1.get("variational_glueball", {}).get("ground_state_mass")
        gevp1 = vg1 if vg1 is not None else {"value": None, "error": None,
                                             "note": "no GEVP in round 3"}
        gevp2 = r["variational_glueball"]["ground_state_mass"]
        comparison[str(b)] = {
            "seed1": {
                "plaquette": s1["avg_plaquette"],
                "plaquette_error": s1["plaquette_error"],
                "string_tension": s1["string_tension"],
                "torelon": tor1,
                "gevp_ground_state_mass": gevp1,
            },
            "seed2": {
                "plaquette": r["avg_plaquette"],
                "plaquette_error": r["plaquette_error"],
                "string_tension": r["string_tension"],
                "torelon": tor2,
                "gevp_ground_state_mass": gevp2,
            },
            "plaquette_agrees_within_errors": agree(
                {"value": s1["avg_plaquette"],
                 "error": s1["plaquette_error"]},
                {"value": r["avg_plaquette"],
                 "error": r["plaquette_error"]}),
            "string_tension_agrees_within_errors": agree(
                s1["string_tension"], r["string_tension"]),
            "torelon_agrees_within_errors": agree(tor1, tor2),
            "gevp_agrees_within_errors": agree(gevp1, gevp2),
        }

    # Torelon series points.
    # Seed 1 base series: 2.2 (round 1), 2.3/2.4 (round 4),
    # 2.5 (round 3), 2.6 (round 5).
    base = []
    for r in load_runs("yang_mills.json"):
        if str(r["beta"]) == "2.2" and r["lattice"] == "8^4":
            base.append(r)
    for r in load_runs("yang_mills_r4.json"):
        if r["lattice"] == "8^4":
            base.append(r)
    for r in load_runs("yang_mills_r3.json"):
        if str(r["beta"]) == "2.5" and r["lattice"] == "8^4":
            base.append(r)
    for r in load_runs("yang_mills_r5.json"):
        base.append(r)
    base.sort(key=lambda r: r["beta"])
    points_A = [torelon_point(r) for r in base]

    # Series B: seed 2 at 2.5 and 2.6, seed 1 elsewhere.
    seed2_by_beta = {r["beta"]: r for r in runs}
    series_B_runs = []
    for r in base:
        if r["beta"] in seed2_by_beta:
            series_B_runs.append(seed2_by_beta[r["beta"]])
        else:
            series_B_runs.append(r)
    points_B = [torelon_point(r) for r in series_B_runs]

    # Series C: inverse-variance weighted seed means at 2.5 and 2.6.
    points_C = []
    for p in points_A:
        b = p["beta"]
        if b in seed2_by_beta:
            p2 = torelon_point(seed2_by_beta[b])
            m_mean = weighted_mean(
                {"value": p["m_tor"], "error": p["m_tor_error"]},
                {"value": p2["m_tor"], "error": p2["m_tor_error"]})
            s_mean = weighted_mean(
                {"value": p["sigma_a2"], "error": p["sigma_a2_error"]},
                {"value": p2["sigma_a2"],
                 "error": p2["sigma_a2_error"]})
            y = m_mean["value"] / math.sqrt(s_mean["value"])
            ey = y * math.sqrt(
                (m_mean["error"] / m_mean["value"]) ** 2
                + (0.5 * s_mean["error"] / s_mean["value"]) ** 2)
            points_C.append({
                "beta": b,
                "sigma_a2": s_mean["value"],
                "sigma_a2_error": s_mean["error"],
                "m_tor": m_mean["value"],
                "m_tor_error": m_mean["error"],
                "m_tor_over_sqrt_sigma": y,
                "m_tor_over_sqrt_sigma_error": ey,
            })
        else:
            points_C.append(p)

    fit_A = fit_torelon(points_A)
    fit_B = fit_torelon(points_B)
    fit_C = fit_torelon(points_C)

    def verdict(fit_a, fit_b):
        if abs(fit_b["continuum_value_c0"] - fit_a["continuum_value_c0"]) \
                <= math.sqrt(fit_a["continuum_value_error"] ** 2
                             + fit_b["continuum_value_error"] ** 2):
            return ("CONFIRMED: the seed 2 series gives a continuum "
                    "intercept consistent with seed 1 within combined "
                    "errors; the Round 5 instability is a property of "
                    "the setup, not of one Monte Carlo chain.")
        return ("OVERTURNED: the seed 2 series gives a continuum "
                "intercept inconsistent with seed 1; the Round 5 "
                "points were seed noise at least in part.")

    out = {
        "method": "Metropolis, checkerboard even/odd updates, random "
                  "SU(2) rotation near identity, eps=0.35, seed "
                  "20261121 + int(beta*100), cold start; APE smearing of "
                  "spatial links, alpha 0.5, levels 0, 2, 4 steps, "
                  "variational GEVP over the three levels",
        "lattice": "8^4",
        "gauge_group": "SU(2)",
        "beta": [2.5, 2.6],
        "thermalization_sweeps": 400,
        "measurement_sweeps": 1500,
        "seed": seed_base,
        "seed1_reference": "seed base 20261120: beta 2.5 from "
                           "data/yang_mills_r3.json, beta 2.6 from "
                           "data/yang_mills_r5.json",
        "avg_plaquette": {str(r["beta"]): r["avg_plaquette"] for r in runs},
        "plaquette_error": {str(r["beta"]): r["plaquette_error"]
                            for r in runs},
        "string_tension": {str(r["beta"]): r["string_tension"]
                           for r in runs},
        "seed_comparison": comparison,
        "continuum_extrapolation_torelon": {
            "channel": "torelon m_eff(1) preferred, m_eff(0) otherwise, "
                       "in units of sqrt(sigma)",
            "fit": "weighted linear fit of m_tor / sqrt(sigma) vs "
                   "sigma a^2 (a^2 proxy at fixed physical sigma)",
            "series_A_seed1_points": points_A,
            "series_A_seed1_fit": fit_A,
            "series_B_seed2_points": points_B,
            "series_B_seed2_fit": fit_B,
            "series_C_seed_mean_points": points_C,
            "series_C_seed_mean_fit": fit_C,
            "seed2_vs_seed1_verdict": verdict(fit_A, fit_B),
            "note": "Five points, two fit parameters, three degrees of "
                    "freedom in each series. The beta 2.2 torelon error "
                    "is large, sigma a^2 is itself an estimate from "
                    "chi(2,2) that overestimates the asymptotic tension, "
                    "the 8^4 volume leaves finite-volume effects "
                    "uncontrolled, and a linear a^2 form is assumed, not "
                    "established. These are extrapolation attempts, not "
                    "continuum results.",
        },
        "runs": runs,
        "runtime_seconds": round(total, 1),
        "date": "2026-11-21",
    }

    out_path = os.path.join(here, "..", "data", "yang_mills_r6.json")
    with open(out_path, "w") as f:
        json.dump(out, f, indent=2)

    print("=" * 60)
    for r in runs:
        b = str(r["beta"])
        c = comparison[b]
        print(f"beta={r['beta']} seed2 plaquette = "
              f"{r['avg_plaquette']:.6f} +/- {r['plaquette_error']:.6f} "
              f"(seed1 {c['seed1']['plaquette']:.6f} +/- "
              f"{c['seed1']['plaquette_error']:.6f}) "
              f"agree={c['plaquette_agrees_within_errors']}")
        s = r["string_tension"]
        s1 = c["seed1"]["string_tension"]
        print(f"  sigma a^2 seed2 = {s['value']:.5f} +/- {s['error']:.5f} "
              f"(seed1 {s1['value']:.5f} +/- {s1['error']:.5f}) "
              f"agree={c['string_tension_agrees_within_errors']}")
        t2 = pick_mass(r["torelon_effective_masses"])
        t1 = c["seed1"]["torelon"]
        print(f"  torelon seed2 = {t2['value']:.4f} +/- {t2['error']:.4f} "
              f"(seed1 {t1['value']:.4f} +/- {t1['error']:.4f}) "
              f"agree={c['torelon_agrees_within_errors']}")
        g2 = r["variational_glueball"]["ground_state_mass"]
        g1 = c["seed1"]["gevp_ground_state_mass"]
        g1s = (f"{g1['value']:.4f} +/- {g1['error']:.4f}"
               if g1['value'] is not None else "no GEVP in round 3")
        print(f"  GEVP 0++ seed2 = {g2['value']:.4f} +/- {g2['error']:.4f} "
              f"(seed1 {g1s}) "
              f"agree={c['gevp_agrees_within_errors']}")
        print(f"  runtime = {r['runtime_seconds']:.1f} s")
    print(f"fit A (seed1): c0 = {fit_A['continuum_value_c0']:.4f} +/- "
          f"{fit_A['continuum_value_error']:.4f}, chi2/dof = "
          f"{fit_A['chi2']:.2f}/{fit_A['dof']}")
    print(f"fit B (seed2): c0 = {fit_B['continuum_value_c0']:.4f} +/- "
          f"{fit_B['continuum_value_error']:.4f}, chi2/dof = "
          f"{fit_B['chi2']:.2f}/{fit_B['dof']}")
    print(f"fit C (seed mean): c0 = {fit_C['continuum_value_c0']:.4f} +/- "
          f"{fit_C['continuum_value_error']:.4f}, chi2/dof = "
          f"{fit_C['chi2']:.2f}/{fit_C['dof']}")
    print(out["continuum_extrapolation_torelon"]["seed2_vs_seed1_verdict"])


if __name__ == "__main__":
    main()
