"""Machine checks for the general-p proofs of the P6 and Q local factors (note: octonion-odd-conductor-general-p-20261111.md).
(1) Block maps: every right multiplication R_y, y in the Z_p-basis of Lambda_P6, acts on the Zorn coordinates exactly as the
    proof says (checked symbolically: the maps are integer coordinate maps, independent of p, times 1 or p).
(2) Reduced count: pairs (L1, L2) of lattices in Z_p^2 satisfying conditions (i), (ii) of the proof, enumerated with a
    bound larger than the proof needs, give P_O = 1 + x^2 + (p+1)x^4 + x^6 + p x^8 and P_Lambda = 1 + (p+1)x^2 + x^4 + p x^6.
(3) Soundness, independent of the block analysis: each lattice M built from such a pair is checked to be a right
    Lambda-ideal by direct octonion multiplication.
(4) Comparison with the exhaustive programs (genp / method_Bp) wherever their results exist.
Run: python3 proof_P6.py"""
import json, glob, itertools
from zorn import mul, E
A_IDX=[0,4,5,6]; B_IDX=[1,2,3,7]          # A = (a, v1, v2, v3), B = (u1, u2, u3, b)
SHAPE={'P6':([0,1,2,4,6,7],[3,5]),'Q':([0,1,4,7],[2,3,5,6])}   # coordinates kept mod p / multiplied by p
# (1) block maps claimed in the note: (source coordinate -> target coordinate) for each basis y
CLAIM={0:{0:0,4:4,5:5,6:6}, 7:{1:1,2:2,3:3,7:7},
       1:{0:1,4:7,3:5,2:6}, 2:{0:2,5:7,3:4,1:6}, 3:{0:3,6:7,2:4,1:5},     # u1,u2,u3: phi_j on A, psi_j on B
       4:{6:2,5:3,1:0,7:4}, 5:{6:1,4:3,2:0,7:5}, 6:{5:1,4:2,3:0,7:6}}     # v1,v2,v3: chi_j on A, omega_j on B
def check_blocks():
    for y,cl in CLAIM.items():
        for i in range(8):
            img=mul(E[i],E[y]); nz=[(j,c) for j,c in enumerate(img) if c]
            if i in cl: assert len(nz)==1 and nz[0][0]==cl[i] and abs(nz[0][1])==1,(y,i,nz)
            else: assert not nz,(y,i,nz)
    # derived facts used in the proof: projections onto (a,v1),(v2,v3),(u1,b),(u2,u3) are compositions of full maps
    return True
# lattices in Z_p^2 containing p^K Z^2, as (i, t, j): basis (p^i, t), (0, p^j), 0<=t<p^j
def lattices(p,K):
    for i in range(K+1):
        for j in range(K+1):
            for t in range(p**j):
                if all(((p**K//p**i)*t)%p**j==0 for _ in [0]): yield (i,t,j)
def v(n,p):
    if n==0: return 99
    k=0
    while n%p==0: n//=p; k+=1
    return k
def contains(L,vec,p):
    i,t,j=L; a,b=vec
    if a%p**i: return False
    c=a//p**i
    return (b-c*t)%p**j==0
def feats(L,p):
    i,t,j=L; return dict(cont=min(i,v(t,p),j), r=i, s=min(v(t,p),j), idx=i+j)
def reduced_count(p,K=3,build=False,shape='P6'):
    Ls=list(lattices(p,K)); F=[feats(L,p) for L in Ls]
    PO={};PL={}; pairs=[]
    for L1,f1 in zip(Ls,F):
        m=f1['cont']
        for L2,f2 in zip(Ls,F):
            if min(m,f2['cont'])!=0: continue                           # primitive
            if shape=='P6':
                if not (contains(L2,(0,p**m),p) and contains(L2,(p**(m+1),0),p)): continue   # (i)
                k=min(f2['r'],f2['s']+1)
                if not (contains(L1,(p**k,0),p) and contains(L1,(0,p**k),p)): continue      # (ii)
                inLam=f2['r']>=1; sh=2
            else:   # Q: p*c(L1)Z^2 in L2 and p*c(L2)Z^2 in L1
                k1=m+1; k2=f2['cont']+1
                if not (contains(L2,(p**k1,0),p) and contains(L2,(0,p**k1),p)): continue
                if not (contains(L1,(p**k2,0),p) and contains(L1,(0,p**k2),p)): continue
                inLam=f2['cont']>=1; sh=4
            e=2*(f1['idx']+f2['idx']); PO[e]=PO.get(e,0)+1
            if inLam: PL[e-sh]=PL.get(e-sh,0)+1
            if build: pairs.append((L1,L2))
    return PO,PL,pairs
def basis_M(L1,L2,p):
    # A' = L1 in (a,v1); B' = L1 in (u1,b); A'' = L2 in (v2,v3); B'' = L2 via (u3,-u2) = (y1,y2)
    rows=[]
    for (i,t,j),coords in ((L1,[(0,4),(1,7)]),(L2,[(5,6),(3,2)])):
        pass
    def vecs(L):
        i,t,j=L; return [(p**i,t),(0,p**j)]
    for (x1,x2) in vecs(L1):
        r=[0]*8; r[0]=x1; r[4]=x2; rows.append(r)
        r=[0]*8; r[1]=x1; r[7]=x2; rows.append(r)
    for (y1,y2) in vecs(L2):
        r=[0]*8; r[5]=y1; r[6]=y2; rows.append(r)
        r=[0]*8; r[3]=y1; r[2]=-y2; rows.append(r)
    return rows
def is_right_ideal(rows,p,shape='P6'):
    FULL,PMUL=SHAPE[shape]
    from lat import hnf, solve_rows
    MOD=p**8; H=hnf(rows,8,MOD)
    gens=[E[i] for i in FULL]+[[p*(k==i) for k in range(8)] for i in PMUL]
    return all(solve_rows(H,mul(r,y)) is not None for r in rows for y in gens)
EXPECT={'P6':lambda p:({0:1,2:1,4:p+1,6:1,8:p},{0:1,2:p+1,4:1,6:p}),
        'Q':lambda p:({0:1,2:2*(p+1),4:(p+1)**2+2,6:2*(p+1),8:2*p*(p+1)},{0:1,2:p+1,4:p*(p+1)})}
if __name__=='__main__':
    assert check_blocks(); print('(1) block maps verified against zorn.mul')
    out={}
    for shape in ('P6','Q'):
        data={}
        for f in glob.glob(f'results-genp-{shape}-p*.json')+glob.glob(f'results-Bp-{shape}-p*.json'):
            r=json.load(open(f)); r=r[0] if isinstance(r,list) else r; data.setdefault(r['p'],[]).append((f,r))
        for p in (3,5,7,11,13):
            PO,PL,pairs=reduced_count(p,K=3,build=True,shape=shape)
            ePO,ePL=EXPECT[shape](p)
            assert PO==ePO and PL==ePL,(shape,p,PO,PL)
            assert all(is_right_ideal(basis_M(a,b,p),p,shape) for a,b in pairs)
            cmp=[]
            for f,r in data.get(p,[]):
                ok={int(k):v for k,v in r['P_O'].items()}==ePO and {int(k):v for k,v in r['P_Lambda'].items()}==ePL
                assert ok,(f,r['P_O'],r['P_Lambda']); cmp.append(f)
            out[f'{shape} p={p}']={'P_O':ePO,'P_Lambda':ePL,'n_primitive':len(pairs),'reduced_count_matches':True,'all_built_lattices_are_right_ideals':True,'matches_exhaustive_runs':cmp}
            print(shape,p,'(2) reduced count = formula; (3)',len(pairs),'built lattices are right ideals; (4) matches',cmp)
    json.dump(out,open('proof-blocks-check.json','w'),indent=1)
