"""Round 2 Yang-Mills hunt: beta 2.3 on 8^4, plus a 10^4 volume check.

Same protocol as round 1: Metropolis checkerboard, eps 0.35, cold
start, 400 thermalization + 1500 measurement sweeps. Seed convention
is the same as compute/wilson_lattice.py: seed = 20261120 + int(beta*100),
so beta 2.3 uses seed 20261350. That seed is recorded in the output JSON.

Writes data/yang_mills_r2.json (same schema shape as
data/yang_mills.json, single beta plus a 10^4 volume check).

Run: cd ~/workspace/millennium-lab && python3 compute/run_r2.py > data/wilson_r2.log 2>&1
"""
import json
import math
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from wilson_lattice import run


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 round 1."""
    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 main():
    t_start = time.time()
    print("Round 2: beta=2.3 on 8^4 SU(2), same protocol as round 1", flush=True)
    print("Seed convention: 20261120 + int(beta*100) = 20261350 for beta 2.3", flush=True)
    r23 = run(2.3)
    print(f"beta 2.3 8^4 done in {r23['runtime_seconds']:.1f} s", flush=True)

    print("Volume check: beta=2.3 on 10^4, same sweeps and seed family", flush=True)
    r23_10 = run(2.3, size=10)
    print(f"beta 2.3 10^4 done in {r23_10['runtime_seconds']:.1f} s", flush=True)
    total = time.time() - t_start

    # Gap estimates, same pick rule as round 1.
    gap_estimates = []
    for r in (r23, r23_10):
        for key, label in (
            ("glueball_effective_masses",
             "0++ glueball effective mass from time-slice plaquette correlator (m_eff(1) preferred, m_eff(0) otherwise)"),
            ("tensor_effective_masses",
             "2++ tensor glueball effective mass from orientation-difference plaquette correlator"),
            ("torelon_effective_masses",
             "torelon effective mass from spatial Polyakov loop correlator"),
        ):
            g = pick_mass(r[key])
            if g.get("value") is not None:
                gap_estimates.append({
                    "beta": r["beta"],
                    "lattice": r["lattice"],
                    "gap_estimate": g["value"],
                    "error": g["error"],
                    "method": label,
                })

    # Gap in units of sqrt(sigma), primary channel 0++ glueball.
    ratios = {}
    for r in (r23, r23_10):
        g = pick_mass(r["glueball_effective_masses"])
        s = r["string_tension"]
        if g.get("value") is not None and s["value"] > 0:
            ratios[r["lattice"]] = g["value"] / math.sqrt(s["value"])

    # Torelon mass in units of sqrt(sigma), per beta, for the
    # three-point extrapolation. Round 1 values are read from
    # data/yang_mills.json and recorded here with their source.
    r1_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           "..", "data", "yang_mills.json")
    with open(r1_path) as f:
        r1 = json.load(f)
    tor_r1 = {}
    sig_r1 = {}
    for b in ("2.2", "2.4"):
        run_r1 = [x for x in r1["runs"] if str(x["beta"]) == b][0]
        tor_r1[b] = pick_mass(run_r1["torelon_effective_masses"])
        sig_r1[b] = run_r1["string_tension"]

    tor23 = pick_mass(r23["torelon_effective_masses"])
    sig23 = r23["string_tension"]
    # a^2 proxy: sigma a^2 itself is proportional to a^2 at fixed
    # physical sigma, so fit m_tor / sqrt(sigma) vs sigma a^2.
    pts = []
    for b, tor, sig in (("2.2", tor_r1["2.2"], sig_r1["2.2"]),
                        ("2.3", tor23, sig23),
                        ("2.4", tor_r1["2.4"], sig_r1["2.4"])):
        pts.append({
            "beta": float(b),
            "sigma_a2": sig["value"],
            "sigma_a2_error": sig["error"],
            "m_tor": tor["value"],
            "m_tor_error": tor["error"],
            "m_tor_over_sqrt_sigma": tor["value"] / math.sqrt(sig["value"]),
        })
    # Weighted linear fit y = c0 + c1 * x, y = m_tor/sqrt(sigma),
    # x = sigma a^2. Errors on y propagated from m_tor and sigma
    # errors (treated as independent); x errors ignored in the fit.
    xs = [p["sigma_a2"] for p in pts]
    ys = [p["m_tor_over_sqrt_sigma"] for p in pts]
    yerr = []
    for p in pts:
        rel = math.sqrt((p["m_tor_error"] / p["m_tor"]) ** 2
                        + (0.5 * p["sigma_a2_error"] / p["sigma_a2"]) ** 2)
        yerr.append(abs(p["m_tor_over_sqrt_sigma"]) * rel)
    w = [1.0 / (e * e) for e in yerr]
    sw = sum(w)
    sx = sum(wi * xi for wi, xi in zip(w, xs))
    sy = sum(wi * yi for wi, yi in zip(w, ys))
    sxx = sum(wi * xi * xi for wi, xi in zip(w, xs))
    sxy = sum(wi * xi * yi for wi, xi, yi in zip(w, xs, ys))
    det = sw * sxx - sx * sx
    c0 = (sxx * sy - sx * sxy) / det
    c1 = (sw * sxy - sx * sy) / det
    # Covariance of (c0, c1) for weighted least squares.
    var_c0 = sxx / det
    var_c1 = sw / det
    # Chi squared with 1 degree of freedom (3 points, 2 parameters).
    chi2 = sum(wi * (yi - c0 - c1 * xi) ** 2
               for wi, xi, yi in zip(w, xs, ys))
    extrapolation = {
        "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)",
        "points": pts,
        "continuum_value_c0": c0,
        "continuum_value_error": math.sqrt(var_c0),
        "slope_c1": c1,
        "slope_error": math.sqrt(var_c1),
        "chi2": chi2,
        "dof": 1,
        "note": "Three points, two fit parameters, one degree of freedom. "
                "The fit is thin: 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. This is an "
                "extrapolation attempt, not a continuum result.",
    }

    out = {
        "method": "Metropolis, checkerboard even/odd updates, random SU(2) rotation near identity, eps=0.35, seed 20261120 + int(beta*100) (= 20261350 for beta 2.3), cold start",
        "lattice": "8^4",
        "gauge_group": "SU(2)",
        "beta": [2.3],
        "thermalization_sweeps": 400,
        "measurement_sweeps": 1500,
        "seed": 20261350,
        "avg_plaquette": {"2.3": r23["avg_plaquette"]},
        "plaquette_error": {"2.3": r23["plaquette_error"]},
        "creutz_ratios": {"2.3": r23["creutz_ratios"]},
        "string_tension": {"2.3": r23["string_tension"]},
        "string_tension_note": "sigma a^2 from Creutz ratio chi(2,2); chi(3,3) also reported in creutz_ratios for comparison. Finite 8^4 volume, no continuum limit taken.",
        "gap_estimates": gap_estimates,
        "gap_over_sqrt_sigma": ratios,
        "continuum_extrapolation_torelon": extrapolation,
        "runs": [r23, r23_10],
        "volume_check": {
            "beta": 2.3,
            "lattice_8": "8^4",
            "lattice_10": "10^4",
            "note": "Same beta, sweeps and seed family on 10^4. Compare plaquette, sigma a^2 and gap estimates between the two volumes in the runs list.",
        },
        "runtime_seconds": round(total, 1),
        "date": "2026-11-20",
    }

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

    print("=" * 60)
    for r in (r23, r23_10):
        print(f"beta={r['beta']}  lattice={r['lattice']}  SU(2)  "
              f"acceptance={r['acceptance_rate']:.3f}")
        print(f"  avg plaquette = {r['avg_plaquette']:.6f} "
              f"+/- {r['plaquette_error']:.6f}")
        for k, v in r["creutz_ratios"].items():
            err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
            print(f"  {k} = {v['value']:.4f} +/- {err}")
        s = r["string_tension"]
        serr = f"{s['error']:.4f}" if s['error'] is not None else "n/a"
        print(f"  string tension sigma a^2 = {s['value']:.4f} +/- {serr} (chi(2,2))")
        for label, key in (("glueball", "glueball_effective_masses"),
                           ("tensor 2++", "tensor_effective_masses"),
                           ("torelon", "torelon_effective_masses")):
            for k, v in r[key].items():
                if v["value"] is None:
                    print(f"  {label} {k}: no positive correlator")
                else:
                    err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
                    print(f"  {label} {k} = {v['value']:.4f} +/- {err}")
        v1 = r["static_potential_V1"]
        if v1["value"] is None:
            print("  static potential V(1): C_P(1) not positive")
        else:
            verr = f"{v1['error']:.4f}" if v1['error'] is not None else "n/a"
            print(f"  static potential V(1) = {v1['value']:.4f} +/- {verr}")
        print(f"  runtime = {r['runtime_seconds']:.1f} s")
    print(f"Torelon extrapolation: continuum m_tor/sqrt(sigma) = {c0:.3f} "
          f"+/- {math.sqrt(var_c0):.3f}, slope = {c1:.3f} "
          f"+/- {math.sqrt(var_c1):.3f}, chi2/dof = {chi2:.2f}/1")
    print(f"total runtime = {total:.1f} s")
    print(f"wrote {out_path}")


if __name__ == "__main__":
    main()
