#!/usr/bin/env python3
"""Derive the 2O analogue of the 2T F6 local identity, along the order-8 axis.

Run: /workspace/tools/pari-venv/bin/python3 derive_identity.py
"""
from __future__ import annotations
import json, time
from pathlib import Path
import sympy as sp

OUT = Path(__file__).resolve().parent / "derive-identity-results.json"
t0 = time.time()

# ----------------------------------------------------------------------
# Character table and eigenvalues of 2O = GAP [48,28]
# Classes:
#   C1, C-1, C4a (±i,±j,±k, size 6, ε=+1), C4b (size 12, ε=-1),
#   C6 (size 8), C3 (size 8), C8+ (Re=√2/2, size 6), C8- (Re=-√2/2, size 6)
# ----------------------------------------------------------------------
I, sqrt = sp.I, sp.sqrt
sqrt2 = sqrt(2)
w3 = -sp.Rational(1, 2) + I * sqrt(3) / 2          # e^{2πi/3}
w3b = sp.conjugate(w3)
e8 = (sqrt2 / 2) + I * (sqrt2 / 2)                   # e^{iπ/4}
e8b = sp.conjugate(e8)
e83 = (-sqrt2 / 2) + I * (sqrt2 / 2)                 # e^{i3π/4}
e83b = sp.conjugate(e83)
e6 = sp.Rational(1, 2) + I * sqrt(3) / 2             # e^{iπ/3}
e6b = sp.conjugate(e6)

# eigenvalues of each irrep on each class
# irrep order: 1, eps, chi2, psi3, psi3eps, rho, rhoeps, sig4
IRREPS = ["1", "eps", "chi2", "psi3", "psi3eps", "rho", "rhoeps", "sig4"]
CLASSES = ["C1", "Cm1", "C4a", "C4b", "C6", "C3", "C8p", "C8m"]
IN_SLICE = {"C1", "Cm1", "C4a", "C8p", "C8m"}  # can be represented in <e^{iπ/4}>

# aligned ψ (the i-plane value with Im ≥ 0)
PSI = {
    "C1":  sp.Integer(1),
    "Cm1": sp.Integer(-1),
    "C4a": I,
    "C4b": None,  # out of slice
    "C6":  None,
    "C3":  None,
    "C8p": e8,
    "C8m": e83,
}

EIGS = {
    # class: {irrep: tuple of eigenvalues}
    "C1": {
        "1": (1,), "eps": (1,), "chi2": (1, 1), "psi3": (1, 1, 1),
        "psi3eps": (1, 1, 1), "rho": (1, 1), "rhoeps": (1, 1),
        "sig4": (1, 1, 1, 1),
    },
    "Cm1": {
        "1": (1,), "eps": (1,), "chi2": (1, 1), "psi3": (1, 1, 1),
        "psi3eps": (1, 1, 1), "rho": (-1, -1), "rhoeps": (-1, -1),
        "sig4": (-1, -1, -1, -1),
    },
    "C4a": {  # i; S4-image is a double transposition
        "1": (1,), "eps": (1,), "chi2": (1, 1),
        "psi3": (1, -1, -1), "psi3eps": (1, -1, -1),
        "rho": (I, -I), "rhoeps": (I, -I),
        "sig4": (I, I, -I, -I),
    },
    "C4b": {  # S4-image a transposition
        "1": (1,), "eps": (-1,), "chi2": (1, -1),
        "psi3": (1, 1, -1), "psi3eps": (1, -1, -1),
        "rho": (I, -I), "rhoeps": (I, -I),
        "sig4": (I, I, -I, -I),
    },
    "C6": {
        "1": (1,), "eps": (1,), "chi2": (w3, w3b),
        "psi3": (1, w3, w3b), "psi3eps": (1, w3, w3b),
        "rho": (e6, e6b), "rhoeps": (e6, e6b),
        "sig4": (-1, -1, e6, e6b),
    },
    "C3": {
        "1": (1,), "eps": (1,), "chi2": (w3, w3b),
        "psi3": (1, w3, w3b), "psi3eps": (1, w3, w3b),
        "rho": (w3, w3b), "rhoeps": (w3, w3b),
        "sig4": (1, 1, w3, w3b),
    },
    "C8p": {
        "1": (1,), "eps": (-1,), "chi2": (1, -1),
        "psi3": (I, -1, -I), "psi3eps": (I, 1, -I),
        "rho": (e8, e8b), "rhoeps": (e83, e83b),
        "sig4": (e8, -e8, e8b, -e8b),
    },
    "C8m": {
        "1": (1,), "eps": (-1,), "chi2": (1, -1),
        "psi3": (I, -1, -I), "psi3eps": (I, 1, -I),
        "rho": (e83, e83b), "rhoeps": (e8, e8b),
        "sig4": (e83, -e83, e83b, -e83b),
    },
}

def chi_val(irrep, cl):
    return sum(EIGS[cl][irrep])

def power_sum(irrep, cl, k):
    return sum(lam ** k for lam in EIGS[cl][irrep])

# sanity: characters match the table
TABLE = {
    "1":       [1, 1, 1, 1, 1, 1, 1, 1],
    "eps":     [1, 1, 1, -1, 1, 1, -1, -1],
    "chi2":    [2, 2, 2, 0, -1, -1, 0, 0],
    "psi3":    [3, 3, -1, 1, 0, 0, -1, -1],
    "psi3eps": [3, 3, -1, -1, 0, 0, 1, 1],
    "rho":     [2, -2, 0, 0, 1, -1, sqrt2, -sqrt2],
    "rhoeps":  [2, -2, 0, 0, 1, -1, -sqrt2, sqrt2],
    "sig4":    [4, -4, 0, 0, -1, 1, 0, 0],
}
for ir, row in TABLE.items():
    for cl, expected in zip(CLASSES, row):
        got = sp.simplify(chi_val(ir, cl) - expected)
        assert got == 0, f"{ir} on {cl}: {chi_val(ir, cl)} != {expected}"
print("character table / eigenvalues: OK")

# sizes and orthogonality
SIZES = {"C1": 1, "Cm1": 1, "C4a": 6, "C4b": 12, "C6": 8, "C3": 8, "C8p": 6, "C8m": 6}
assert sum(SIZES.values()) == 48
for ir1 in IRREPS:
    for ir2 in IRREPS:
        ip = sum(SIZES[cl] * sp.simplify(sp.conjugate(chi_val(ir1, cl)) * chi_val(ir2, cl))
                 for cl in CLASSES)
        ip = sp.simplify(ip)
        expect = 48 if ir1 == ir2 else 0
        assert ip == expect, f"<{ir1},{ir2}> = {ip}, expected {expect}"
print("orthogonality: OK")

# ----------------------------------------------------------------------
# k=1: expand the class function f(g) = ψ(g) if in-slice else 0
# in the irrep basis: f = Σ a_χ χ
# ----------------------------------------------------------------------
# f(g) as a column, character table as matrix, solve M a = f
f1 = []
Mrows = []
for cl in CLASSES:
    f1.append(PSI[cl] if cl in IN_SLICE else 0)
    Mrows.append([chi_val(ir, cl) for ir in IRREPS])
M = sp.Matrix(Mrows)
f1v = sp.Matrix(f1)
# M is 8x8, characters are a basis of class functions
a = M.solve(f1v)
a = sp.simplify(a)
print("\n=== exponents a_χ of L(χ, s) from k=1 ===")
A = {ir: a[i] for i, ir in enumerate(IRREPS)}
for ir, val in A.items():
    print(f"  L({ir}, s)^{val}")

# ----------------------------------------------------------------------
# Higher k: after subtracting the a_χ contribution, the remainder
# must be explained by L(χ, 2s), L(χ, 4s), ... and H.
#
# For a prime of class g, power k coefficient of log (times k):
#   lhs_k = ψ^k          if in-slice else 0
#   a-part = Σ a_χ χ(g^k)
#   L(χ, 2s) contributes to even k=2m:  2 b_χ χ(g^m)
#   L(χ, 4s) contributes to k=4m:       4 c_χ χ(g^m)
#   L(χ, 8s) contributes to k=8m:       8 d_χ χ(g^m)
# ----------------------------------------------------------------------

def remainder_k(k, B=None, C=None, D=None):
    """lhs_k - a-part - 2s - 4s - 8s, as a dict class -> value."""
    B = B or {ir: 0 for ir in IRREPS}
    C = C or {ir: 0 for ir in IRREPS}
    D = D or {ir: 0 for ir in IRREPS}
    out = {}
    for cl in CLASSES:
        psi = PSI[cl]
        lhs = (psi ** k) if psi is not None else 0
        apart = sum(A[ir] * power_sum(ir, cl, k) for ir in IRREPS)
        bpart = 0
        if k % 2 == 0:
            m = k // 2
            bpart = sum(2 * B[ir] * power_sum(ir, cl, m) for ir in IRREPS)
        cpart = 0
        if k % 4 == 0:
            m = k // 4
            cpart = sum(4 * C[ir] * power_sum(ir, cl, m) for ir in IRREPS)
        dpart = 0
        if k % 8 == 0:
            m = k // 8
            dpart = sum(8 * D[ir] * power_sum(ir, cl, m) for ir in IRREPS)
        out[cl] = sp.simplify(lhs - apart - bpart - cpart - dpart)
    return out

# First, see remainders with only a_χ, for k=1..8
print("\n=== remainders with only L(χ,s)^{a} (should be 0 at k=1) ===")
for k in range(1, 9):
    rem = remainder_k(k)
    print(f"  k={k}: " + ", ".join(f"{cl}:{rem[cl]}" for cl in CLASSES))

# Solve for b_χ from k=2: remainder = 2 Σ b_χ χ(g)
# (the 2s contribution at k=2 is 2 b_χ χ(g^1))
print("\n=== solving b_χ from k=2 remainder ===")
rem2 = remainder_k(2)
# rem2[cl] should equal 2 Σ b_χ χ(cl)
rhs = sp.Matrix([rem2[cl] for cl in CLASSES])
# 2 M b = rhs, so b = M^{-1} rhs / 2
b = sp.simplify(M.solve(rhs) / 2)
B = {ir: b[i] for i, ir in enumerate(IRREPS)}
for ir, val in B.items():
    print(f"  L({ir}, 2s)^{val}")

print("\n=== remainders after a and b ===")
for k in range(1, 13):
    rem = remainder_k(k, B=B)
    print(f"  k={k}: " + ", ".join(f"{cl}:{rem[cl]}" for cl in CLASSES))

# Solve for c_χ from k=4
print("\n=== solving c_χ from k=4 remainder ===")
rem4 = remainder_k(4, B=B)
rhs4 = sp.Matrix([rem4[cl] for cl in CLASSES])
# rem4 = 4 Σ c_χ χ(g)
c = sp.simplify(M.solve(rhs4) / 4)
C = {ir: c[i] for i, ir in enumerate(IRREPS)}
for ir, val in C.items():
    print(f"  L({ir}, 4s)^{val}")

print("\n=== remainders after a, b, c ===")
for k in range(1, 17):
    rem = remainder_k(k, B=B, C=C)
    nonzero = {cl: rem[cl] for cl in CLASSES if rem[cl] != 0}
    print(f"  k={k}: " + (str(nonzero) if nonzero else "0 everywhere"))

# Solve for d_χ from k=8
print("\n=== solving d_χ from k=8 remainder ===")
rem8 = remainder_k(8, B=B, C=C)
rhs8 = sp.Matrix([rem8[cl] for cl in CLASSES])
d = sp.simplify(M.solve(rhs8) / 8)
D = {ir: d[i] for i, ir in enumerate(IRREPS)}
for ir, val in D.items():
    print(f"  L({ir}, 8s)^{val}")

print("\n=== remainders after a, b, c, d ===")
all_zero = True
rems = {}
for k in range(1, 25):
    rem = remainder_k(k, B=B, C=C, D=D)
    nonzero = {cl: str(rem[cl]) for cl in CLASSES if rem[cl] != 0}
    rems[k] = nonzero
    if nonzero:
        all_zero = False
        print(f"  k={k}: {nonzero}")
    else:
        print(f"  k={k}: 0 everywhere")
print("all zero through k=24?", all_zero)

# If not all zero, the remainder is H: look at which classes and what power series
# Maybe H is supported only on out-of-slice classes, or is a cyclotomic factor.

report = {
    "A_s": {ir: str(A[ir]) for ir in IRREPS},
    "B_2s": {ir: str(B[ir]) for ir in IRREPS},
    "C_4s": {ir: str(C[ir]) for ir in IRREPS},
    "D_8s": {ir: str(D[ir]) for ir in IRREPS},
    "remainders_after_abcd_1_to_24": rems,
    "all_zero_through_24": all_zero,
    "secs": time.time() - t0,
}
OUT.write_text(json.dumps(report, indent=2))
print("wrote", OUT)
