"""Compare the four-gluon output after (G.2) to (1.1) in arXiv:2408.04720v2."""
import json
from fractions import Fraction as Q


def det(a, b):
    return a[0] * b[1] - a[1] * b[0]


def complete_square(angle, last_two):
    """For each dotted index solve lambda_1 x + lambda_2 y = -(p_3+p_4)."""
    a, b, c, d = angle
    rhs = [tuple(-c[i] * last_two[0][j] - d[i] * last_two[1][j]
                 for i in range(2)) for j in range(2)]
    return [tuple(Q(det(r, b), det(a, b)) for r in rhs),
            tuple(Q(det(a, r), det(a, b)) for r in rhs), *last_two]


def conserved(angle, square):
    return all(sum(a[i] * b[j] for a, b in zip(angle, square)) == 0
               for i in range(2) for j in range(2))


def amplitudes(angle, square):
    if not conserved(angle, square):
        raise ValueError("External momenta must sum to zero.")
    a, b, c, d = angle
    A, B, C, D = square
    parke_taylor = Q(det(a, b)**4, det(a, b) * det(b, c) * det(c, d) * det(d, a))
    model_output = Q(-det(a, b) * det(C, D)**2, det(c, d) * det(A, D) * det(B, C))
    return parke_taylor, model_output


def check_point(angle, square, t):
    reference, output = amplitudes(angle, square)
    if reference != output or reference == 0:
        raise RuntimeError("Formula equality or nonzero-fixture check failed.")
    if -output == reference:
        raise RuntimeError("Sign mutation escaped detection.")
    scaled = []
    for leg, power in enumerate([2, 2, -2, -2]):
        a, s = angle.copy(), square.copy()
        a[leg] = tuple(t * x for x in a[leg])
        s[leg] = tuple(x / t for x in s[leg])
        observed = amplitudes(a, s)
        expected = reference * t**power
        if observed != (expected, expected):
            raise RuntimeError(f"Little-group check failed at leg {leg + 1}.")
        scaled.append(str(expected))
    broken = square.copy()
    broken[0] = (broken[0][0] + 1, broken[0][1])
    try:
        amplitudes(angle, broken)
    except ValueError:
        pass
    else:
        raise RuntimeError("Unbalanced input escaped detection.")
    return {"angle": angle, "square": square, "parke_taylor": str(reference),
            "model_output": str(output), "sign_mutation": str(-output),
            "rescaling_factor": str(t), "one_leg_at_a_time": scaled,
            "unbalanced_input_rejected": True}


def run():
    # Each tuple specifies all undotted spinors and the final two dotted spinors.
    seeds = [
        ([(1, 0), (0, 1), (1, 1), (1, 2)], [(1, 0), (0, 1)]),
        ([(2, 1), (1, -1), (3, 2), (-1, 4)], [(2, 3), (-1, 2)]),
        ([(1, 2), (-2, 3), (2, 1), (3, -1)], [(3, -1), (2, 1)]),
    ]
    points = [check_point(angle, complete_square(angle, tail), Q(3, 2))
              for angle, tail in seeds]
    return {"source": "arXiv:2408.04720v2", "status": "passed", "points": points}


if __name__ == "__main__":
    print(json.dumps(run(), default=str, indent=2))
