"""Reproduce the cube reanalysis with Python 3 and the exact moments below.

Run: python3 spin-check.py
Optional original-trajectory check (NumPy 2.4.2): python3 -B spin-check.py --replay PROJECT

Each row contains K, seed, the trace of R, four unordered pair sums of R
(in LABELS order), the two half-run total occupations in slice units,
sum_e delta_e**2, and 3 sum_a delta_a**2 - (sum_e delta_e)**2.
x[t,e] is the integer sum of the 12 occupations on edge e at sweep t.
R = n x.T @ x - outer(x.sum(0), x.sum(0)). Divide by (n M)**2 for covariance.
delta_e is the second-half sum of x[:,e] minus the first-half sum.
delta_a is the sum of delta_e over edges parallel to axis a.
"""

import argparse
import json
import math
import sys
from itertools import combinations, product
from pathlib import Path
from statistics import mean, stdev

N, M, E, BETA = 240, 12, 54, 2
DEN = (N * M) ** 2
LABELS = ("touching parallel", "touching perpendicular",
          "disjoint parallel", "disjoint perpendicular")
WEIGHT_TIMES_THREE = (2, -1, 2, -1)
ROWS = (
    (0, 1, 528071079, 2750418, 9045443, 9847589, -12009634, 56498, 57289, 2814589, 998216),
    (0, 2, 490186302, 3752205, -483075, -4900572, -4744221, 55221, 55467, 2478230, 6520392),
    (0, 3, 504156488, 5656481, -202068, -18265690, 16023841, 54852, 57576, 2432756, 5203302),
    (0, 4, 495911361, 64558, 19327648, -11179809, -11473678, 52671, 55930, 2406923, 5077982),
    (0, 5, 514439393, 2275179, 4922434, 25087620, -27412690, 57201, 58310, 1323179, 10620926),
    (0, 6, 508788171, 2088196, 11238878, -1112342, 17715450, 55944, 55261, 2540565, 1690754),
    (0, 7, 474171603, 2104068, 8950868, 966214, 10858516, 53010, 53785, 2011629, 2706446),
    (0, 8, 532403171, -5400449, 3269403, -459327, -17179397, 59214, 57699, 1985769, 1318002),
    (0.02, 1, 1801889122, 361010619, 1477108365, 3813180647, 7059987006, 224426, 357392, 544489086, 487522698),
    (0.02, 2, 1573523936, 184397725, 729411797, 840242492, 1938950080, 153472, 199494, 164463448, 46405202),
    (0.02, 3, 1925783664, 281707965, 1505172867, 2034816608, 3705392966, 142959, 248663, 468889640, 224502662),
    (0.02, 4, 1507416632, 160168644, 1000161376, 1516743918, 2674129184, 109475, 190563, 295070996, 175631384),
    (0.02, 5, 2123120478, 398681105, 2213392373, 4673847139, 8292404326, 125196, 279390, 751176194, 945209166),
    (0.02, 6, 1892134391, 295701307, 1748672522, 2937065512, 5781702599, 180084, 299203, 614933837, 167170856),
    (0.02, 7, 1833219029, 321064901, 1465261735, 3369429440, 6573124365, 185767, 327206, 630453763, 63729806),
    (0.02, 8, 1811734012, 277184730, 1546956800, 1929384482, 3608105524, 123013, 222721, 419793224, 405907272),
)


def geometry():
    """Enumerate unordered edge pairs on the open cube, in archive edge order."""
    edges, axes = [], []
    for axis, stride in enumerate((9, 3, 1)):
        for x, y, z in product(range(3), repeat=3):
            if (x, y, z)[axis] < 2:
                u = 9 * x + 3 * y + z
                edges.append((u, u + stride))
                axes.append(axis)
    groups = [[], [], [], []]
    for i, j in combinations(range(E), 2):
        offset = 2 if set(edges[i]).isdisjoint(edges[j]) else 0
        groups[offset + int(axes[i] != axes[j])].append((i, j))
    assert [len(g) for g in groups] == [27, 144, 432, 828]
    return edges, axes, groups


def diagnostics(row, counts):
    diagonal, *sums = row[2:7]
    early, late, delta_norm2, axis_norm2_times_three = row[7:]
    pair_cov = [s / (DEN * count) for s, count in zip(sums, counts)]
    factor = BETA / (3 * E * DEN)
    weighted = [2 * factor * w * s for w, s in zip(WEIGHT_TIMES_THREE, sums)]
    off = sum(weighted)
    between = factor * (axis_norm2_times_three - 2 * delta_norm2)
    half_scale = 1 / ((N // 2) * M * E)
    return {
        "raw": pair_cov, "weighted": weighted,
        "single": 2 * factor * diagonal, "off": off, "total": off + 2 * factor * diagonal,
        "between": between, "within": off - between,
        "early": half_scale * early, "late": half_scale * late,
        "late minus early": half_scale * (late - early),
        "touching parallel minus perpendicular": pair_cov[0] - pair_cov[1],
    }


def summary(values):
    values = list(values)
    return f"{mean(values):+.6f} ± {stdev(values) / math.sqrt(len(values)):.6f}"


def report(counts):
    stats = {(row[0], row[1]): diagnostics(row, counts) for row in ROWS}
    seeds = range(1, 9)
    assert set(stats) == set(product((0, 0.02), seeds))
    print("K=0.02, mean ± SEM across eight seeds")
    print("geometry | unordered pairs | covariance per pair | contribution per edge")
    for j, label in enumerate(LABELS):
        values = [stats[0.02, s]["raw"][j] for s in seeds]
        weights = [stats[0.02, s]["weighted"][j] for s in seeds]
        print(f"{label} | {counts[j]} | {summary(values)} | {summary(weights)}")
    print("\nquantity | K=0 | K=0.02 | same-seed difference")
    for key in ("single", "total", "off", "between", "within", "early", "late",
                "late minus early", "touching parallel minus perpendicular"):
        base = [stats[0, s][key] for s in seeds]
        test = [stats[0.02, s][key] for s in seeds]
        print(f"{key} | {summary(base)} | {summary(test)} | "
              f"{summary(b - a for a, b in zip(base, test))}")
    print("Coupled seeds with all four class means positive:",
          sum(min(stats[0.02, s]["raw"]) > 0 for s in seeds), "/ 8")
    print("Coupled seeds with increasing half-run occupation:",
          sum(stats[0.02, s]["late minus early"] > 0 for s in seeds), "/ 8")


def verify_replay(project, edges, axes, groups):
    """Regenerate only the 16 frozen larger-cube runs and check the moment table."""
    import numpy as np
    phase = project / "hardware" / "phase0_qpu"
    sys.dont_write_bytecode = True
    sys.path.insert(0, str(phase / "qmc_full"))
    import cube3d
    directory = phase / "results" / "qmc_full"

    def load_scan(name):
        rows = json.loads((directory / f"phase2d_bond_coupled_{name}_chi10_beta2.json").read_text())
        return {(r["E"], r["bond_bond_J"], r["seed"]): r for r in rows}

    frozen, candidate = load_scan("connected"), load_scan("candidate")
    assert len(frozen) == 32 and frozen.keys() == candidate.keys()
    assert all(r["chi_T_per_edge"] == candidate[k]["chi_T_per_edge"] for k, r in frozen.items())
    pair_indices = [tuple(zip(*g)) for g in groups]
    counts = [len(g) for g in groups]
    max_saved_error = max_half_error = 0.0
    for row in ROWS:
        k, seed = row[:2]
        saved = frozen[E, k, seed]
        assert (saved["n_meas"], saved["n_therm"], saved["M"], saved["chi"], saved["beta"]) == (N, 30, M, 10, BETA)
        run = cube3d.run_cube(dict(omega=1., J0=.12, dB=.55, lam=.35, bond_bond_J=k),
                              chi=10, beta=BETA, M=M, n_therm=30, n_meas=N, seed=seed,
                              dims=(3, 3, 3), return_measurements=True)
        assert edges == run["edges"] and np.array_equal(axes, run["axis"])
        samples = run["edge_samples"]
        x = np.rint(M * samples).astype(np.int64)
        assert np.array_equal(x / M, samples)
        q = N * (x.T @ x) - np.outer(x.sum(axis=0), x.sum(axis=0))
        first, last = np.split(x, 2)
        delta = last.sum(axis=0) - first.sum(axis=0)
        by_axis = np.array([delta[run["axis"] == a].sum() for a in range(3)])
        integers = [q.trace(), *(q[g].sum() for g in pair_indices), first.sum(), last.sum(),
                    delta @ delta, 3 * (by_axis @ by_axis) - delta.sum() ** 2]
        assert tuple(map(int, integers)) == row[2:], (k, seed, "moments")
        for name in ("chi_T_total", "chi_T_per_edge", "single_edge_chi_T_per_edge",
                     "connected_inter_edge_chi_T_per_edge", "connected_inter_edge_fraction",
                     "adjacent_inter_edge_chi_T_per_edge", "nonadjacent_inter_edge_chi_T_per_edge"):
            max_saved_error = max(max_saved_error, abs(run[name] - saved[name]))
        max_saved_error = max(max_saved_error, abs(float(run["occ"].mean()) - saved["mean_bond_occupation"]))
        check = diagnostics(row, counts)
        assert abs(check["total"] - saved["chi_T_per_edge"]) < 1e-10
        assert abs(check["off"] - saved["connected_inter_edge_chi_T_per_edge"]) < 1e-10
        halves = [cube3d.tensor_decomposition_from_edge_samples(h, axes, BETA, edges)
                  for h in np.split(samples, 2)]
        direct = mean(h["connected_inter_edge_chi_T_per_edge"] for h in halves)
        max_half_error = max(max_half_error, abs(direct - check["within"]))
    assert max_saved_error < 1e-10 and max_half_error < 1e-10
    print(f"\n16 replays matched. Maximum saved-field error {max_saved_error:.3g}, "
          f"maximum within-half identity error {max_half_error:.3g}.")
    print("Candidate and subtraction scans have identical totals in all 32 matched rows.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--replay", metavar="PROJECT", type=Path, help="also check against original QMC code")
    args = parser.parse_args()
    edges, axes, groups = geometry()
    report([len(group) for group in groups])
    if args.replay:
        verify_replay(args.replay.resolve(), edges, axes, groups)
