# -*- coding: utf-8 -*-
"""
DEEP DIVE 3 — DC_1 Sweep 2, seeded by the equivariance mechanism.

A_1 has the parity automorphism omega: x -> -x, d -> -d. Mechanism II says:
hunt for PARITY-EQUIVARIANT endomorphism candidates — P, Q both ODD elements
(images of the odd generators stay odd). This prunes the ansatz space hard and
matches the structural style of the only known JC counterexample.

Two-term parity-odd ansatz: P = x + a*x^i d^j, Q = d + b*x^r d^s,
i+j odd, r+s odd, 3 <= weight <= 5. Solve [Q,P] = 1 exactly.
"""
import sympy as sp
from sympy import binomial, ff
import itertools, time, json

t0 = time.time()

def wmul(A, B):
    out = {}
    for (a1, b1), ca in A.items():
        for (c1, e1), cb in B.items():
            for k in range(0, min(b1, c1) + 1):
                key = (a1 + c1 - k, b1 + e1 - k)
                out[key] = sp.expand(out.get(key, 0) + ca*cb*binomial(b1, k)*ff(c1, k))
    return {k: v for k, v in out.items() if v != 0}

def comm(A, B):
    m1, m2 = wmul(A, B), wmul(B, A)
    out = dict(m1)
    for k, v in m2.items():
        out[k] = sp.expand(out.get(k, 0) - v)
    return {k: v for k, v in out.items() if v != 0}

ONE = {(0, 0): sp.Integer(1)}
a, b = sp.symbols('a b')

odd = [(i, j) for i in range(6) for j in range(6)
       if (i + j) % 2 == 1 and 3 <= i + j <= 5]
print(f"parity-odd perturbation monomials (weight 3-5): {len(odd)}")

results, anomalies, n = [], [], 0
for (i, j) in odd:
    for (r, s) in odd:
        n += 1
        P = {(1, 0): sp.Integer(1), (i, j): a}
        Q = {(0, 1): sp.Integer(1), (r, s): b}
        E = comm(Q, P)
        E[(0, 0)] = sp.expand(E.get((0, 0), 0) - 1)
        eqs = [v for v in E.values() if v != 0]
        sols = sp.solve(eqs, [a, b], dict=True)
        for sol in sols:
            av, bv = sol.get(a, a), sol.get(b, b)
            if av == 0 or bv == 0:
                continue
            entry = {"P": f"x + ({av})*x^{i}d^{j}", "Q": f"d + ({bv})*x^{r}d^{s}"}
            results.append(entry)
            triangular = (j == 0 and s == 0) or (i == 0 and r == 0)
            if not triangular:
                anomalies.append(entry)

print(f"[DONE] {n} parity-equivariant two-term patterns tested")
print(f"        nontrivial commuting families: {len(results)}")
print(f"        non-triangular anomalies:      {len(anomalies)}")
for e in results:
    print("        ", e["P"], "|", e["Q"])

json.dump({"sweep": "DC1 parity-equivariant two-term, weight 3-5",
           "patterns": n, "families": results, "anomalies": anomalies,
           "elapsed_sec": round(time.time()-t0, 2)},
          open('post-jc-program/breakthrough/dc1_sweep2_parity.json', 'w'), indent=2)
print(f"artifact: dc1_sweep2_parity.json  ({round(time.time()-t0,2)}s)")
