"""Exact round-S3 Killing-spinor check in two GLOBAL spin frames.

Coordinates x cover S3 minus y0=-1. The ambient matrix q and both frames
are global; chart residuals alone are not the global-extension argument.
Run with Python 3.13.7, SymPy 1.13.3. No repository imports/network needed.
"""

import argparse
import json
import sympy as sp


def clean(value):
    """Reduce rational functions exactly; never use a numerical tolerance."""
    if isinstance(value, sp.MatrixBase):
        return value.applyfunc(sp.cancel)
    return sp.cancel(value)


def is_zero(value):
    value = clean(value)
    if isinstance(value, sp.MatrixBase):
        return all(entry == 0 for entry in value)
    return value == 0


def geometry():
    x = sp.symbols("x1 x2 x3", real=True)
    ell = sp.symbols("ell", positive=True)
    eye = sp.eye(2)
    gamma = (
        sp.diag(1, -1),
        sp.Matrix([[0, -1], [-1, 0]]),
        sp.Matrix([[0, sp.I], [-sp.I, 0]]),
    )
    dot = lambda v: sum((v[a] * gamma[a] for a in range(3)), sp.zeros(2))
    d = 1 + sum(t * t for t in x)
    y0 = (2 - d) / d
    y = sp.Matrix([2 * t / d for t in x])
    q = y0 * eye + sp.I * dot(y)
    frames = {}
    for name, sign in (("left", 1), ("right", -1)):
        frames[name] = clean(sp.Matrix(3, 3, lambda a, i: ell * (
            y0 * sp.diff(y[a], x[i]) - y[a] * sp.diff(y0, x[i])
            + sign * sum(sp.LeviCivita(a, b, c) * y[b] * sp.diff(y[c], x[i])
                         for b in range(3) for c in range(3)))))
    curved = {name: tuple(dot(e[:, i]) for i in range(3))
              for name, e in frames.items()}
    connection = {name: tuple(clean(sign * sp.I * g / (2 * ell)) for g in curved[name])
                  for name, sign in (("left", 1), ("right", -1))}
    return x, ell, eye, gamma, d, y0, y, q, frames, curved, connection


def residual(psi, connection, curved_gamma, coordinates, H):
    """Columns of psi are separate labels. Return every coordinate equation."""
    return tuple(clean(sp.diff(psi, u) + connection[i] * psi
                       + H * curved_gamma[i] * psi / 2)
                 for i, u in enumerate(coordinates))


def run(omit_frame_term=False):
    x, ell, eye, gamma, d, y0, y, q, frames, curved, connection = geometry()
    groups = {}

    def check(group, condition):
        if not condition:
            raise AssertionError(group)
        groups[group] = groups.get(group, 0) + 1

    for a in range(3):
        for b in range(3):
            expected = (eye if a == b else sp.zeros(2)) + sp.I * sum(
                (sp.LeviCivita(a, b, c) * gamma[c] for c in range(3)), sp.zeros(2))
            check("Clifford_matrices", is_zero(gamma[a] * gamma[b] - expected))
    check("ambient_spin_lift", is_zero(q.adjoint() * q - eye))
    check("ambient_spin_lift", is_zero(q.det() - 1))
    metric = 4 * ell**2 * sp.eye(3) / d**2
    for name in frames:
        e = frames[name]
        check("coframe_metric_orientation", is_zero(e.T * e - metric))
        check("coframe_metric_orientation", is_zero(e.det() - (2 * ell / d)**3))

    # Test candidate connections against the torsion-free Cartan equation.
    # Omega_ab = sign * epsilon_abc e^c / ell, with BOTH b,c ordered.
    for name, sign in (("left", 1), ("right", -1)):
        e = frames[name]
        for a in range(3):
            for i in range(3):
                for j in range(i + 1, 3):
                    cartan = sp.diff(e[a, j], x[i]) - sp.diff(e[a, i], x[j])
                    cartan += sign / ell * sum(sp.LeviCivita(a, b, c) * (
                        e[c, i] * e[b, j] - e[c, j] * e[b, i])
                        for b in range(3) for c in range(3))
                    check("Cartan_input_checks", is_zero(cartan))

    for i, u in enumerate(x):
        check("Maurer_forms", is_zero(q.adjoint() * sp.diff(q, u) - sp.I * curved['left'][i] / ell))
        check("Maurer_forms", is_zero(sp.diff(q, u) * q.adjoint() - sp.I * curved['right'][i] / ell))
        check("spin_frame_transition", is_zero(curved['right'][i] - q * curved['left'][i] * q.adjoint()))
        check("spin_frame_transition", is_zero(connection['right'][i]
              - q * connection['left'][i] * q.adjoint() + sp.diff(q, u) * q.adjoint()))

    H = -sp.I / ell
    left_residual = residual(eye, connection['left'], curved['left'], x, H)
    right_residual = residual(q, connection['right'], curved['right'], x, H)
    for name, residues in (("left", left_residual), ("right", right_residual)):
        for value in residues:
            check("complete_Killing_matrices", is_zero(value))

    # Deliberately conjugating WITHOUT the derivative term is incorrect.
    bad_connection = tuple(clean(q * a * q.adjoint()) for a in connection['left'])
    bad_residual = residual(q, bad_connection, curved['right'], x, H)
    for i, u in enumerate(x):
        check("omitted_frame_term_control", is_zero(bad_residual[i] - sp.diff(q, u)))
        check("omitted_frame_term_control", not is_zero(bad_residual[i]))
    origin = dict.fromkeys(x, 0)
    north_error = clean(sum(sp.trace(v.subs(origin).adjoint() * v.subs(origin))
                            for v in bad_residual))
    check("omitted_frame_term_control", north_error == 24)

    # A point sample at the pole misses this nonconstant scalar multiplier.
    c = sp.Matrix([1, 0])
    profile_residual = residual(y0 * c, connection['left'], curved['left'], x, H)
    for i, u in enumerate(x):
        check("scalar_profile_control", is_zero(profile_residual[i] - sp.diff(y0, u) * c))
    profile_norm = clean(d**2 / (4 * ell**2) * sum((v.adjoint() * v)[0] for v in profile_residual))
    check("scalar_profile_control", is_zero(profile_norm - (1 - y0**2) / ell**2))
    check("scalar_profile_control", all(is_zero(v.subs(origin)) for v in profile_residual))
    check("scalar_profile_control", not is_zero(profile_norm))

    selected_right = bad_residual if omit_frame_term else right_residual
    right_pass = all(is_zero(v) for v in selected_right)
    assert right_pass == (not omit_frame_term)
    return {
        "mode": "omit-frame-term diagnostic" if omit_frame_term else "correct connection",
        "arithmetic": "exact rational functions over complex coefficients",
        "chart": "x in R^3; missing point y0=-1, y1=y2=y3=0",
        "background": "A=V=C=0, H=-i/ell, ell>0; trivial R bundle",
        "global_extension": "ambient polynomial q in SU(2); global left and right frames",
        "grouped_exact_assertions": groups,
        "total": sum(groups.values()),
        "scalar_equations_per_frame_per_charge_family": 12,
        "charge_families": "independent zeta and tilde_zeta; identical operators here",
        "left_Killing_residual_zero": True,
        "right_Killing_residual_zero": right_pass,
        "omitted_term_north_coordinate_Frobenius_square": str(north_error),
        "profile_residual_norm_square": "(1-y0^2)/ell^2",
        "profile_pole_sample_zero": True,
        "profile_global_residual_zero": False,
    }


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--omit-frame-term', action='store_true',
                        help='Report the deliberately incorrect right-frame connection.')
    options = parser.parse_args()
    print(json.dumps(run(options.omit_frame_term), indent=2))
