#!/usr/bin/env python3
"""Exact universal algebra checks; Python >= 3.10, standard library only.

No triangulations, manifolds, slopes, or skein configurations are enumerated.
Matrix identities establish bilinear formulas for arbitrary exponent vectors.
The sparse Weyl computations concern the fixed algebra identities in the note.
They do not prove the imported geometric lemmas or the unresolved collar map.
"""

from dataclasses import dataclass


def transpose(m):
    return tuple(zip(*m))


def matmul(a, b):
    return tuple(tuple(sum(x * y for x, y in zip(row, col))
                       for col in transpose(b)) for row in a)


def neg(m):
    return tuple(tuple(-x for x in row) for row in m)


def pairing(a, b, skew):
    return sum(a[i] * skew[i][j] * b[j]
               for i in range(len(a)) for j in range(len(a)))


def basis(n, j, c=1):
    return tuple(c if k == j else 0 for k in range(n))


def addv(a, b):
    return tuple(x + y for x, y in zip(a, b))


def scalev(k, a):
    return tuple(k * x for x in a)


def check(name, condition):
    if not condition:
        raise AssertionError(name)
    print("PASS:", name)


@dataclass
class Weyl:
    """Sparse sum c*i**j*t**n*W(a), with t**2=A and j in {0,1}."""
    skew: tuple
    terms: dict

    @classmethod
    def mono(cls, skew, a=None, i=0, t=0, c=1):
        if a is None:
            a = (0,) * len(skew)
        i %= 4
        if i >= 2:
            c = -c
            i -= 2
        return cls(skew, {(tuple(a), i, t): c} if c else {})

    def __add__(self, other):
        assert self.skew == other.skew
        out = dict(self.terms)
        for key, val in other.terms.items():
            out[key] = out.get(key, 0) + val
            if out[key] == 0:
                del out[key]
        return Weyl(self.skew, out)

    def __neg__(self):
        return Weyl(self.skew, {k: -v for k, v in self.terms.items()})

    def __sub__(self, other):
        return self + (-other)

    def __mul__(self, other):
        assert self.skew == other.skew
        out = Weyl(self.skew, {})
        for (a, i, t), c in self.terms.items():
            for (b, j, u), d in other.terms.items():
                out += Weyl.mono(self.skew, addv(a, b), i + j,
                                 t + u + pairing(a, b, self.skew), c * d)
        return out

    def equal(self, other):
        return self.skew == other.skew and self.terms == other.terms

    def map(self, linear, conjugate=False):
        out = Weyl(self.skew, {})
        for (a, i, t), c in self.terms.items():
            image_a = tuple(sum(row[j] * a[j] for j in range(len(a)))
                            for row in linear)
            out += Weyl.mono(self.skew, image_a, -i if conjugate else i,
                             -t if conjugate else t, c)
        return out


OMEGA = ((0, 1, -1), (-1, 0, 1), (1, -1, 0))
B6 = tuple(tuple(OMEGA[i % 3][j % 3] for j in range(6)) for i in range(6))
C = ((1, 0, 0, 1, 0, 0), (0, 1, 0, 0, 1, 0), (0, 0, 1, 0, 0, 1))
P = tuple(basis(6, j) for j in (2, 1, 0, 5, 4, 3))
MINUS_ID = tuple(basis(6, j, -1) for j in range(6))
B2 = ((0, 2), (-2, 0))


def main():
    print("Six-root peripheral attack: exact algebra verification")
    print("Ring: Z[i,t,t^-1], i^2=-1, A=t^2.")
    check("opposite-exponent collapse pulls back the full six-root skew form",
          matmul(transpose(C), matmul(OMEGA, C)) == B6)
    check("the prime-reversal permutation is anti-symplectic",
          matmul(transpose(P), matmul(B6, P)) == neg(B6))
    check("prime reversal is an involution",
          matmul(P, P) == tuple(basis(6, j) for j in range(6)))

    # This matrix identity proves the eliminated Weyl formula for all a,b.
    # Write p=r-s and u=t_*-s. Its product factor is u(a)p(b)-p(a)u(b).
    p = tuple(C[0][j] - C[1][j] for j in range(6))
    u = tuple(C[2][j] - C[1][j] for j in range(6))
    eliminated_form = tuple(tuple(u[i] * p[j] - p[i] * u[j]
                                  for j in range(6)) for i in range(6))
    check("central-vertex elimination has the universal exact Weyl product factor",
          eliminated_form == B6)
    beta = (0, 0, 0, 1, 1, 1)
    check("prime reversal preserves the full opposite-root sign row beta",
          tuple(sum(beta[i] * P[i][j] for i in range(6)) for j in range(6)) == beta)

    def w6(a=None, **kw):
        return Weyl.mono(B6, a, **kw)

    one6 = w6()
    f_gy = w6(basis(6, 0, -2)) + w6(basis(6, 2, 2)) - one6
    f_ck = w6(basis(6, 0, 2)) + w6(basis(6, 2, -2)) - one6
    check("fixed-parameter anti-map sends the native Lagrangian to CK's",
          f_gy.map(P).equal(f_ck))
    check("conjugate inverse-root anti-map sends the native Lagrangian to CK's",
          f_gy.map(MINUS_ID, conjugate=True).equal(f_ck))
    vertices = ((1, 1, 1, 0, 0, 0), (1, 0, 0, 0, 1, 1),
                (0, 1, 0, 1, 0, 1), (0, 0, 1, 1, 1, 0))
    permuted = {tuple(sum(row[j] * a[j] for j in range(6)) for row in P)
                for a in vertices}
    check("fixed-parameter anti-map permutes all four central vertex monomials",
          permuted == set(vertices))
    v = w6(vertices[0])
    vi = w6(scalev(-1, vertices[0]))
    vg = v - w6(i=1, t=2)
    conjugate_vertex = vg.map(MINUS_ID, conjugate=True)
    check("inverse vertex relation has an exact generated-ideal witness",
          conjugate_vertex.equal(w6(i=1, t=-2) * vi * vg))

    z, zp = w6(basis(6, 0)), w6(basis(6, 1))
    lhs = (z * zp).map(MINUS_ID)
    rhs = zp.map(MINUS_ID) * z.map(MINUS_ID)
    expected_defect = (w6(t=1) - w6(t=-1)) * w6((-1, -1, 0, 0, 0, 0))
    check("naive same-parameter inverse-root anti-map has a nonzero defect",
          (lhs - rhs).equal(expected_defect) and bool(expected_defect.terms))

    def w(a=None, **kw):
        return Weyl.mono(B2, a, **kw)

    def h(a):
        return w(a) + w(scalev(-1, a))

    a, b = (1, 0), (0, 1)
    L, M = w(a), w(b)
    Li, Mi = w((-1, 0)), w((0, -1))
    A, Ai, D = w(t=2), w(t=-2), w(t=4) - w(t=-4)
    Hplus, Hminus = h((1, 1)), h((1, -1))
    check("ordered peripheral Weyl monomials obey LM=A^2 ML",
          (L * M).equal(w(t=4) * M * L))
    check("first exact torus product-to-sum identity",
          (h(a) * h(b)).equal(A * Hplus + Ai * Hminus))
    check("second exact torus product-to-sum identity",
          (h(b) * h(a)).equal(Ai * Hplus + A * Hminus))
    numerator = A * h(a) * h(b) - Ai * h(b) * h(a)
    check("two-generator commutator determines the named sum slope",
          numerator.equal(D * Hplus))
    check("both signs of the sum slope carry the same ordered A^-1 factor",
          Hplus.equal(Ai * (L * M + Li * Mi)))
    check("the reciprocal of A^-1 LM is A^-1 L^-1 M^-1",
          ((Ai * L * M) * (Ai * Li * Mi)).equal(w()))
    check("inverse edge generator has its exact scalar witness",
          (Li + w(t=-4)).equal(w(t=-4) * Li * (L + w(t=4))))

    # A fixed-parameter right action reverses composition; this is the same
    # operator multiplication after replacing the skew form by its negative.
    check("opposite multiplication reverses the full peripheral skew form",
          transpose(B2) == neg(B2))

    # Cup comparisons are scalars, not a proof of a collar map.
    half_twist = w(i=1, t=3)
    gy_cup_pm, gy_cup_mp = w(t=-1), -w(t=-5)
    ck_cup_pm, ck_cup_mp = w(i=1, t=2), -w(i=1, t=-2)
    check("both cup coefficients differ by the same i A^(3/2) half-twist",
          (half_twist * gy_cup_pm).equal(ck_cup_pm)
          and (half_twist * gy_cup_mp).equal(ck_cup_mp))
    check("the half-twist squares to the usual -A^3 framing scalar",
          (half_twist * half_twist).equal(-w(t=6)))

    print("All exact algebra checks passed.")
    print("Not certified by this script: GY's geometric diagram setup and local skein lemmas;")
    print("the raw GY/CK endpoint-duality and collar square; any nonvanishing theorem.")
    print("No manifold, triangulation, slope, or skein-configuration census was performed.")


if __name__ == "__main__":
    main()
