#!/usr/bin/env python3
"""Independent certificate reconstruction for Arithmetic Compression and Integer Factorization.

Python 3.10+, standard library only. No input data, network or prior logs needed.
Default: all pruned universal widths 0..16, five-type widths 17..22,
and the binary/ternary Golay support classification. Options: --help.

Topology: uses the universal grid modules and analytic pruning in the paper
(coverage37, monic37, prune40, edge41, cap41, remove41, five40, five42).
This is an independent replay, not the original missing code. A nonunit
remainder is INCONCLUSIVE, never a proof of torsion. Only a completed run
with exit status zero certifies the requested scope, conditional on the
paper's analytic reductions. --unpruned bypasses geometric pruning for
small widths (very expensive at large widths). No runtime pilots or
external factoring theorems are certified here.

Colab: upload this file, then run %run arithmetic_compression_verify.py
Optional quick check: %run arithmetic_compression_verify.py --suite golay
All requested scopes must print PASS; an interrupted run is not a certificate.
"""
import argparse
from collections import Counter, defaultdict, deque
from functools import lru_cache
from itertools import combinations, product
from math import comb, factorial
from fractions import Fraction
import time
import sys


def require(test, message):
    if not test:
        raise ArithmeticError(message)


# Sparse module polynomial keys are (total degree, exponent tuple, component).
# Exponents are packed into base 2**16 with high-order variable first.
# The guard bit gives an exact coordinatewise divisibility test. Abort rather
# than silently overflow: this is an implementation limit, not a theorem.
BITS = 16
LOW = (1 << (BITS-1))-1
FIELD = (1 << BITS)-1


@lru_cache(maxsize=65536)
def lcm_shift(a, b):
    x, y = a[1], b[1]
    lcm = da = db = 0
    shift = 0
    while x or y:
        u, v = x & FIELD, y & FIELD
        z = max(u, v)
        lcm |= z << shift
        da += z-u
        db += z-v
        x >>= BITS
        y >>= BITS
        shift += BITS
    return (da, lcm-a[1]), (db, lcm-b[1])


def add_multiple(dst, src, shift, coeff, guard):
    dd, mm = shift
    for (d, m, c), v in src.items():
        ex = m+mm
        require(not ex & guard, 'packed exponent capacity exceeded')
        t = (d+dd, ex, c)
        z = dst.get(t, 0)+coeff*v
        if z:
            dst[t] = z
        else:
            dst.pop(t, None)


def monic_completion(columns, nvar):
    """Integer division and ALL same-component S-pairs; no pair shortcuts."""
    guard = sum(1 << (BITS*i+BITS-1) for i in range(nvar))
    by_component = defaultdict(list)
    queue = deque()
    inserted = pairs = 0

    def insert(poly):
        nonlocal inserted
        p = dict(poly)
        rem = {}
        while p:
            t = max(p)
            coeff = p[t]
            for lead, g in by_component[t[2]]:
                if lead[0] <= t[0] and ((t[1] | guard)-lead[1]) & guard == guard:
                    add_multiple(p, g, (t[0]-lead[0], t[1]-lead[1]), -coeff, guard)
                    break
            else:
                rem[t] = p.pop(t)
        if not rem:
            return
        lead = max(rem)
        if abs(rem[lead]) != 1:
            raise ArithmeticError(f'nonunit leading coefficient {rem[lead]} at {lead}')
        if rem[lead] == -1:
            rem = {t:-v for t,v in rem.items()}
        for old in by_component[lead[2]]:
            queue.append((old, (lead, rem)))
        by_component[lead[2]].append((lead, rem))
        inserted += 1

    for col in columns:
        insert(col)
    while queue:
        (a, f), (b, g) = queue.popleft()
        pairs += 1
        sa, sb = lcm_shift(a, b)
        s = {}
        add_multiple(s, f, sa, 1, guard)
        add_multiple(s, g, sb, -1, guard)
        insert(s)
    return inserted, pairs


def boundary_columns(V, P, delta, k):
    """Boundary from degree k+1 to k, in the universal graded module.
    States are (free directions, lower offset), sorted lexicographically.
    Relative terms outside the retained states are zero.
    """
    d = len(P)
    def states(j):
        for F in combinations(range(d), j):
            weight = sum(P[i] for i in F)
            lo, hi = 0, V-weight
            if delta is not None:
                lo = max(lo, V-delta-weight+1)
                hi = min(hi, delta-1)
            for rho in range(lo, hi+1):
                yield F, rho
    target = {s:i for i,s in enumerate(states(k))}
    cols = []
    for F, rho in states(k+1):
        col = {}
        for j, i in enumerate(F):
            face = F[:j]+F[j+1:]
            for var, off, sign in ((i,rho+P[i],1),(d+i,rho,-1)):
                c = target.get((face,off))
                if c is not None:
                    key = (1, 1 << (BITS*(2*d-1-var)), c)
                    col[key] = sign * (-1 if j%2 else 1)
        if col:
            cols.append(col)
    return cols


def degrees(V, P, delta, unpruned=False):
    d = len(P)
    if unpruned:
        return range(d)
    if delta is None:
        if d <= 4 or P[-1]+P[0] > V:
            return ()
        candidates = range(1, d-3)
    else:
        if d <= 3 or P[-1] >= delta or V-delta < P[0]:
            return ()
        candidates = range(1, d-1)
    out = []
    for k in candidates:
        # Degree-specific removal: no (k+1)-cell with largest direction free.
        if P[-1]+sum(P[:k]) > V:
            continue
        if delta is None:
            if sum(p <= V-P[-1] for p in P[:-1]) <= k+1:
                continue
        else:
            if V < 2*delta and k == d-2:
                continue
            if V >= 2*delta and k == 1:
                continue
            if (sum(p <= V-delta for p in P) <= k+1 and
                (V < 2*delta or (k >= 2 and sum(p <= V-2*delta for p in P) <= k))):
                continue
        out.append(k)
    return out


def presentations(V, five_only=False, unpruned=False):
    weights = range(1,V+1)
    if five_only:
        # All absolute before relative at equal width, and smaller dimensions
        # before larger ones. Five-type localization transfers other cases.
        for P in combinations(weights,5):
            yield P,None
        for P in combinations(weights,5):
            yield P[:-1],P[-1]
        return
    for d in range(V+1):
        if unpruned or d>=5:
            for P in combinations(weights,d):
                yield P,None
    for d in range(V):
        if unpruned or d>=4:
            for delta in weights:
                others = tuple(p for p in weights if p != delta) if unpruned else range(1,delta)
                for P in combinations(others,d):
                    yield P,delta


def topology(universal, five, unpruned):
    for V in range(five+1):
        restricted = V>universal
        if restricted and universal<16:
            raise ValueError('five-type extension requires universal coverage through width 16')
        stats = Counter()
        start = time.monotonic()
        for P,delta in presentations(V,restricted,unpruned):
            stats['enumerated'] += 1
            ks = list(degrees(V,P,delta,unpruned))
            if not ks:
                continue
            stats['retained'] += 1
            for k in ks:
                stats['selected'] += 1
                cols = boundary_columns(V,P,delta,k)
                if not cols:
                    continue
                stats['maps'] += 1
                try:
                    ins,pairs = monic_completion(cols,2*len(P))
                except ArithmeticError as e:
                    raise ArithmeticError(f'INCONCLUSIVE V={V}, P={P}, delta={delta}, k={k}: {e}') from e
                stats['insertions'] += ins
                stats['pairs'] += pairs
        full = 2*comb(V,5) if restricted else (1 if V==0 else 2**V+V*2**(V-1))
        if unpruned or restricted:
            require(stats['enumerated']==full, 'incomplete presentation enumeration')
        if not unpruned and V>=16:
            expected={16:(4442,5797),17:(868,868),18:(1259,1259),
                      19:(1764,1764),20:(2434,2434),21:(3275,3275),22:(4351,4351)}
            require((stats['retained'],stats['selected'])==expected[V],
                    'retained presentation/degree count differs from paper')
        print(f'PASS topology V={V:2d} {"five-type" if restricted else "universal"} full={full} '
              + ' '.join(f'{k}={stats[k]}' for k in ('enumerated','retained','selected','maps','insertions','pairs'))
              + f' seconds={time.monotonic()-start:.2f}',flush=True)


# Golay codes and design permutation orbits. All coordinates zero based.
def binary_code():
    g=sum(1<<i for i in (0,2,4,5,6,10,11))
    words=[0]
    for i in range(12):
        words += [w^(g<<i) for w in words]
    return [w|((w.bit_count()%2)<<23) for w in words]


def ternary_code():
    g=(-1,0,1,-1,1,1)
    words=[]
    for coeff in product(range(3),repeat=6):
        w=[0]*12
        for i,a in enumerate(coeff):
            for j,b in enumerate(g):
                w[i+j]+=a*b
        w[11]=-sum(w[:11])
        words.append(tuple(x%3 for x in w))
    return words


def compose(a,b):
    return tuple(a[i] for i in b)


def inverse(a):
    b=[0]*len(a)
    for i,j in enumerate(a): b[j]=i
    return tuple(b)


def mask_action(p,m):
    out=0
    while m:
        bit=m&-m
        out|=1<<p[bit.bit_length()-1]
        m^=bit
    return out


def group_closure(gens,identity):
    seen={identity}; q=deque([identity])
    while q:
        p=q.popleft()
        for g in gens:
            h=compose(g,p)
            if h not in seen:
                seen.add(h);q.append(h)
    return seen


def golay():
    start=time.monotonic()
    bc= binary_code(); tc=ternary_code()
    require(Counter(w.bit_count() for w in bc)=={0:1,8:759,12:2576,16:759,24:1},'binary weight distribution')
    require(len(set(tc))==729,'ternary code size')
    tm=[sum(1<<i for i,x in enumerate(w) if x) for w in tc]
    require(Counter(w.bit_count() for w in tm)=={0:1,6:264,9:440,12:24},'ternary weight distribution')
    dodecad=min(w for w in bc if w.bit_count()==12)
    coords=tuple(i for i in range(24) if dodecad>>i&1)
    require(coords==(0,2,3,4,6,7,8,9,10,11,13,14),'dodecad convention')
    bm=[sum(((w>>j)&1)<<i for i,j in enumerate(coords)) for w in bc]
    barr=defaultdict(Counter);tarr=defaultdict(Counter)
    for full,m in zip(bc,bm): barr[full.bit_count(),m.bit_count()][m]+=1
    for m in tm: tarr[m.bit_count()][m]+=1
    B=frozenset(barr[8,6]);T=frozenset(tarr[6])
    for D in (B,T):
        pentads=Counter(m^(1<<i) for m in D for i in range(12) if m>>i&1)
        require(len(D)==132 and len(pentads)==comb(12,5) and set(pentads.values())=={1},'Witt design')
    require(set(barr[8,6].values())=={1} and set(tarr[6].values())=={2},'sextad multiplicities')
    for arrays,design in ((barr,B),(tarr,T)):
        for key,counts in arrays.items():
            size=key[-1] if isinstance(key,tuple) else key
            classes=defaultdict(set)
            for m in range(4096):
                if m.bit_count()==size:
                    classes[size==6 and m in design].add(counts[m])
            require(all(len(vals)==1 for vals in classes.values()),'conditioned support multiplicities')
    identity=tuple(range(12)); adj=[]
    for i in range(11):
        p=list(identity);p[i],p[i+1]=p[i+1],p[i];adj.append(tuple(p))
    masks=tuple(m for m in range(4096) if m.bit_count()==6)
    idx={m:i for i,m in enumerate(masks)}
    def encode(D): return sum(1<<idx[m] for m in D)
    def action_table(p): return tuple(1<<idx[mask_action(p,m)] for m in masks)
    def act(table,D):
        out=0
        while D:
            bit=D&-D;out|=table[bit.bit_length()-1];D^=bit
        return out
    b,t=encode(B),encode(T)
    adjtables=[action_table(p) for p in adj]
    reps={b:identity};q=deque([b]); gens=[]; group={identity}
    # Schreier generators, growing the stabilizer until its verified target
    # order is reached. Orbit size is checked independently below.
    while q:
        D=q.popleft();r=reps[D]
        for p,tab in zip(adj,adjtables):
            E=act(tab,D);s=compose(p,r)
            if E not in reps:
                reps[E]=s;q.append(E)
            elif len(group)<95040:
                h=compose(inverse(reps[E]),s)
                if h not in group:
                    require(act(action_table(h),b)==b,'Schreier generator')
                    gens.append(h);group=group_closure(gens,identity)
                    require(len(group)<=95040,'unexpected stabilizer order')
    require(len(reps)==5040 and t in reps and len(group)==factorial(12)//len(reps),'full design orbit and stabilizer')
    for D,p in reps.items(): require(act(action_table(p),b)==D,'orbit representative')
    tables=[action_table(g) for g in gens]
    unseen=set(reps); rows=[]
    # Representatives map the ternary design to each labeled design.
    t_inverse=inverse(reps[t])
    while unseen:
        D=min(unseen);orb={D};q=deque([D]);unseen.remove(D)
        while q:
            E=q.popleft()
            for tab in tables:
                F=act(tab,E)
                if F not in orb:
                    require(F in unseen,'overlapping stabilizer orbits')
                    orb.add(F);unseen.remove(F);q.append(F)
        alignment=compose(reps[D],t_inverse)
        require(act(action_table(alignment),t)==D,'ternary alignment representative')
        common=[m for m in B if D>>idx[m]&1]
        z=len(common);n=len(orb)
        count4=Counter(sum(1<<i for i in Q) for m in common for Q in combinations([i for i in range(12) if m>>i&1],4))
        h=sum(comb(v,3) for v in count4.values())
        direct=sum((x&y&w).bit_count()==4 for x,y,w in combinations(common,3))
        require(h==direct,'triple incidence identity')
        other=[m for m in masks if D>>idx[m]&1]
        hist=Counter((x&y).bit_count() for x in B for y in other)
        require(tuple(hist[i] for i in range(7))==(z,792-6*z,3960+15*z,7920-20*z,3960+15*z,792-6*z,z),'overlap histogram')
        require(all((b&E).bit_count()==z for E in orb),'invariant overlap')
        rows.append((z,n,h,len(group)//n))
    expected=[(0,144,0,660),(12,990,12,96),(12,1584,0,60),(24,440,36,216),(24,1320,12,72),(36,495,60,192),(60,66,300,1440),(132,1,1980,95040)]
    require(sorted(rows)==expected,'eight double cosets/triple table')
    joint=Counter()
    for (a,bsize),bcnt in barr.items():
        for c,tcnt in tarr.items():
            for x,nx in bcnt.items():
                for y,ny in tcnt.items(): joint[a,bsize,c,(x&y).bit_count()]+=nx*ny
    # defaultdict/Counter lookup above may have populated zero entries.
    joint=+joint
    require(sum(joint.values())==4096*729 and len(joint)==115,'joint histogram count')
    require(tuple(joint[8,6,6,i] for i in range(7))==(24,1440,8280,15360,8280,1440,24),'alignment row')
    print('PASS Golay code distributions, Witt designs, conditioned support arrays, full orbit and stabilizer, joint histogram',flush=True)
    print('  z orbit_size triples stabilizer_order')
    for row in sorted(rows): print(' ',*row)
    # Signed-kernel finite hypotheses and conditioned sixth-moment formula.
    require(Counter(bm)=={m:2 for m in range(4096) if m.bit_count()%2==0},
            'binary even-parity restriction')
    signed=[tuple(0 if x==0 else 1 if x==1 else -1 for x in w) for w in tc]
    require(all(w.count(-1)%2==0 for w,m in zip(signed,tm) if m==4095),
            'full-support ternary sign products')
    # Self-duality: dimension six plus pairwise orthogonality of generators.
    generators=[tc[3**i] for i in range(6)]
    require(all(sum(x*y for x,y in zip(a,b))%3==0 for a in generators for b in generators),
            'ternary self-duality')
    eta={}
    for w,m in zip(signed,tm):
        if m.bit_count()==6:
            v=(-1)**w.count(-1)
            require(eta.get(m,v)==v,'opposite word sign product')
            eta[m]=v
    for S in masks:
        beta=sum((-1)**((S&m).bit_count()) for m in B)
        require(beta==64*(S in B)-12,'binary sextad character sum')
        tau=0
        for w,m in zip(signed,tm):
            if S&m==S:
                neg=sum(1<<i for i,x in enumerate(w) if x==-1)
                tau+=(-1)**((S&neg).bit_count())
        require(tau==-54*eta.get(S,0),'ternary six-coordinate mean')
    for sign in (1,-1):
        # Direct sum over all binary sextads and ternary words, for the
        # identity permutation and the two indicated sign choices.
        W=[(w[0]*sign,)+w[1:] for w in signed]
        moment=0
        for m in B:
            signs=tuple(-1 if m>>i&1 else 1 for i in range(12))
            moment+=sum(sum(x*y for x,y in zip(signs,w))**6 for w in W)
        contraction=sum((64*(S in B)-12)*v*(sign if S&1 else 1) for S,v in eta.items())
        expected=Fraction(20264,3)-Fraction(2*factorial(6),27*132)*contraction
        require(Fraction(moment,132*729)==expected,'conditioned signed sixth moment')
    # Exact parity-conditioned sum distributions; binomial counting is the
    # analytic reduction of the unconditioned signed kernel in the paper.
    hist={}
    for sign in (1,-1):
        counts=Counter()
        for j,nj in ((0,1),(6,264),(9,440),(12,24)):
            for r in range(j+1):
                if j<12:
                    counts[j-2*r]+=nj*comb(j,r)*(4096//2**j)
                elif (-1)**r==sign:
                    counts[j-2*r]+=nj*comb(j,r)*2
        require(sum(counts.values())==4096*729,'signed histogram mass')
        hist[sign]=counts
    diffs=[sum(s**k*(hist[1][s]-hist[-1][s]) for s in set(hist[1])|set(hist[-1])) for k in range(13)]
    require(diffs[:12]==[0]*12 and diffs[12]==4096*48*factorial(12),'signed moment difference')
    print('PASS Golay signed kernel: 924 character sums per code, two direct sixth moments, parity histograms through degree 12',flush=True)
    print(f'PASS Golay seconds={time.monotonic()-start:.2f}',flush=True)


def main():
    p=argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument('--suite',choices=('all','topology','golay'),default='all')
    p.add_argument('--universal-width',type=int,default=16)
    p.add_argument('--five-width',type=int,default=None,help='default 22 if universal width is 16, otherwise universal width')
    p.add_argument('--unpruned',action='store_true',help='full unpruned family for universal widths only (slow)')
    a=p.parse_args()
    five=a.five_width if a.five_width is not None else (22 if a.universal_width==16 else a.universal_width)
    if not 0<=a.universal_width<=16 or not a.universal_width<=five<=22 or (five>a.universal_width and a.universal_width!=16) or (a.unpruned and five>a.universal_width):
        p.error('require 0 <= universal <= 16, universal <= five <= 22; extension needs universal=16 and pruning')
    if a.suite in ('all','golay'): golay()
    if a.suite in ('all','topology'): topology(a.universal_width,five,a.unpruned)
    print('PASS: all requested certificate checks completed',flush=True)

if __name__=='__main__':
    try: main()
    except (ArithmeticError,KeyboardInterrupt) as exc:
        print(f'INCONCLUSIVE / FAILED CHECK: {exc}',file=sys.stderr,flush=True)
        sys.exit(1)
