"""Verify the finite premises and projections of the cubic lift at selected sizes.

The manuscript's equivariant pullback argument establishes the general theorem.
"""
from pathlib import Path
from collections import defaultdict
from itertools import combinations
import hashlib, json
DATA=Path(__file__).resolve().parent/'N6.json'
def need(ok,why):
    if not ok: raise RuntimeError(why)
def rot(v,n):r,c=v;return c,n+1-r
def flip(v,n):r,c=v;return r,n+1-c
def transform(a,n,k,f):
    out={flip(v,n) if f else v for v in a}
    for _ in range(k):out={rot(v,n) for v in out}
    return out
def marker(a,n):s=(n-6)//2;return int((s+1,s+3) in a)
def extend(a,n):
    m=n+2;u=marker(a,n);out={(r+1,c+1) for r,c in a}
    out.update({(1,1),(1,m),(m,1),(m,m)})
    for c in range(2,m):
        if (u if c%2==0 else 1-u):
            v=(1,c)
            for _ in range(4):out.add(v);v=rot(v,m)
    return out
def bitmask(a,n):return sum(1<<((r-1)*n+c-1) for r,c in a)
def moment_compare(a,b,n):
    aa=[bitmask(transform(a,n,k,f),n) for f in (False,True) for k in range(4)]
    bb=[bitmask(transform(b,n,k,f),n) for f in (False,True) for k in range(4)]
    totals=[]
    for d in (1,2,3):
        count=0
        for inds in combinations(range(n*n),d):
            mask=sum(1<<i for i in inds)
            need(sum((x&mask)==mask for x in aa)==sum((x&mask)==mask for x in bb),f'moment mismatch {n} {inds}')
            count+=1
        totals.append(count)
    return totals
def edge(a,b):return tuple(sorted((a,b)))
def canonical(seq):
    seq=tuple(seq);rev=seq[::-1]
    return min(t[i:]+t[:i] for t in (seq,rev) for i in range(len(t)))
def walk(a,n):
    owners={};around=defaultdict(list)
    for r in range(n+1):
        for c in range(n+1):
            if (r+c)%2:continue
            corners=[(r,c),(r,c+1),(r+1,c+1),(r+1,c)]
            for x,y in zip(corners,corners[1:]+corners[:1]):
                e=edge(x,y);need(e not in owners,'support edges shared')
                owners[e]=(r,c);around[x].append(e);around[y].append(e)
    paired={}
    for v,incident in around.items():
        need(len(incident) in (2,4),'support valency')
        for e in incident:
            candidates=[q for q in incident if q!=e]
            if len(incident)==2:chosen=candidates
            elif v not in a:chosen=[q for q in candidates if owners[q]==owners[e]]
            else:
                other=e[1] if e[0]==v else e[0]
                desired=(2*v[0]-other[0],2*v[1]-other[1])
                chosen=[q for q in candidates if desired in q]
            need(len(chosen)==1,'unique continuation');paired[v,e]=chosen[0]
    unseen=set(owners);words=[]
    while unseen:
        start=min(unseen);e=start;v=start[0];word=[]
        while e in unseen:
            unseen.remove(e);word.append(e)
            v=e[1] if e[0]==v else e[0]
            e=paired[v,e]
        need(e==start and v==start[0],'closed circuit')
        words.append(canonical(word))
    need(sum(map(len,words))==2*n*n+4*n+4,'edge total')
    return sorted(words)
def main():
    data=json.loads(DATA.read_bytes())
    a,b=[{(r+1,c+1) for r,line in enumerate(rows) for c,ch in enumerate(line) if ch=='1'} for rows in data['matrices']]
    rows=[];old_words=None
    for n in (6,8,10):
        words=[walk(x,n) for x in (a,b)]
        need([len(w) for w in words]==[1,3],'one versus three')
        checks=0
        for x in (a,b):
            for f in (False,True):
                for k in range(4):
                    y=transform(x,n,k,f)
                    need(marker(y,n)==(marker(x,n)^f),'marker character')
                    need(extend(y,n)==transform(extend(x,n),n+2,k,f),'equivariance')
                    checks+=1
        moments=moment_compare(a,b,n)
        if old_words is not None:
            old_edges=set(e for w in old_words[0] for e in w)
            for previous,current in zip(old_words,words):
                reduced=[]
                for w in current:
                    projected=[]
                    for e in w:
                        old=edge(*[(r-1,c-1) for r,c in e])
                        if old in old_edges:projected.append(old)
                    need(bool(projected),'extra exterior circuit')
                    reduced.append(canonical(projected))
                need(sorted(reduced)==previous,'word projection')
        s=(n-6)//2;t={(r+s,c+s) for r,c in data['quartic_separator']['support']}
        cards={tuple(sorted(transform(t,n,k,f))) for f in (False,True) for k in range(4)}
        q=[sum(set(card)<=x for card in cards) for x in (a,b)]
        need(q==[1,0],'persistent quartic separator')
        rows.append({'N':n,'full_labelled_supports_checked':moments,'group_equivariance_checks':checks,'circuit_lengths':[sorted(map(len,w)) for w in words],'quartic_counts':q,'matrices':[[''.join('1' if (r,c) in x else '0' for c in range(1,n+1)) for r in range(1,n+1)] for x in (a,b)]})
        old_words=words;a,b=extend(a,n),extend(b,n)
    print(json.dumps({'status':'PASS_FINITE','script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'historical_N6_sha256':hashlib.sha256(DATA.read_bytes()).hexdigest(),'rows':rows,'limits':['Finite checks are not the uniform proof.','Full labelled group sums differ from distinct-support coordinates by fixed stabilizer factors; equality is equivalent.','No source image, knot or historical attribution follows.']},sort_keys=True,indent=2))
if __name__=='__main__':main()
