"""Evaluate arXiv:2602.12176v2, Eqs. (30) and (39), for n=4 in R1."""
import json
from collections import Counter
from fractions import Fraction as Q
from itertools import permutations


def bracket(a, b):
    # Eq. (5): [ij] = omega_i omega_j (ztilde_i - ztilde_j).
    return a[1] * b[0] - a[0] * b[1]


def sign(x):
    if x == 0:
        raise ValueError("A required sign is on a wall.")
    return 1 if x > 0 else -1


def sum_spinors(spinors):
    return tuple(map(sum, zip(*spinors)))


def equation30(spinors, flip=False):
    a, b, c, d = spinors
    first_term = sign(bracket(b, c)) * sign(bracket(d, a))
    second_term = sign(bracket(a, b)) * sign(bracket(c, d))
    # Negative control: reverse the sign of only the second term.
    return Q(first_term + (-second_term if flip else second_term), 2)


def equation39(spinors):
    value = Q(1)
    for m in range(2, len(spinors)):
        adjacent = bracket(spinors[m - 1], spinors[m])
        combined = bracket(spinors[0], sum_spinors(spinors[1:m]))
        value *= Q(sign(adjacent) + sign(combined), 2)
    return value


def run():
    retained = []
    excluded = []
    energy_sets = [(1, 1, 1), (1, 2, 3), (2, 3, 5)]
    for weights in energy_sets:
        for slopes in permutations([-2, 0, 2]):
            outgoing = [(w, w * z) for w, z in zip(weights, slopes)]
            incoming = tuple(-x for x in sum_spinors(outgoing))
            spinors = [incoming, *outgoing]
            if sum_spinors(spinors) != (0, 0) or incoming[0] >= 0:
                raise RuntimeError("Expected conserved momenta in the decay frame.")
            # Exclude all two-leg coincidences, in addition to required sign walls.
            if any(bracket(spinors[i], spinors[j]) == 0
                   for i in range(4) for j in range(i)):
                excluded.append({"spinors": spinors, "reason": "zero pair bracket"})
                continue
            a30, a39 = equation30(spinors), equation39(spinors)
            retained.append({"spinors": spinors, "eq30": str(a30), "eq39": str(a39),
                             "mutated_eq30": str(equation30(spinors, flip=True))})
    counts = Counter(row["eq39"] for row in retained)
    mismatches = [i for i, row in enumerate(retained) if row["eq30"] != row["eq39"]]
    caught = sum(row["mutated_eq30"] != row["eq39"] for row in retained)
    passed = not mismatches and counts["0"] > 0 and counts["1"] > 0 and caught > 0
    return {"source": "arXiv:2602.12176v2", "helicities": "-+++",
            "common_undotted_spinor": [1, 0], "frequencies_2_to_4": energy_sets,
            "slopes_2_to_4": "all permutations of [-2,0,2]", "values": dict(counts),
            "mismatch_indices": mismatches, "mutations_rejected": caught,
            "retained": retained, "excluded": excluded, "status": "passed" if passed else "failed"}


if __name__ == "__main__":
    result = run()
    print(json.dumps(result, indent=2))
    raise SystemExit(0 if result["status"] == "passed" else 1)
