"""Exact bridge from the binary seed clock to its signed mismatch operator.
Standard library only. No data, measured constants, optimized weights or tolerances.
"""
from fractions import Fraction
from itertools import product
from pathlib import Path
import json

def eye(n): return [[int(i == j) for j in range(n)] for i in range(n)]
def transpose(a): return list(map(list, zip(*a)))
def mul(a,b): return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]
def add(a,b,k=1): return [[x+k*y for x,y in zip(ar,br)] for ar,br in zip(a,b)]
def scale(a,k): return [[k*x for x in r] for r in a]
def power(a,n):
    out=eye(len(a))
    for _ in range(n): out=mul(out,a)
    return out
def rank(rows):
    a=[list(map(Fraction,r)) for r in rows]; pivot=0
    if not a: return 0
    for j in range(len(a[0])):
        hit=next((i for i in range(pivot,len(a)) if a[i][j]),None)
        if hit is None: continue
        a[pivot],a[hit]=a[hit],a[pivot]
        q=a[pivot][j]; a[pivot]=[x/q for x in a[pivot]]
        for i in range(len(a)):
            if i!=pivot and a[i][j]:
                q=a[i][j]; a[i]=[x-q*y for x,y in zip(a[i],a[pivot])]
        pivot+=1
        if pivot==len(a): break
    return pivot
def flat(a): return sum(a,[])
def shift(eps):
    n=len(eps); t=[[0]*(2*n) for _ in range(2*n)]
    for i,b in product(range(n),range(2)): t[2*i+b][2*((i+1)%n)+(b^eps[i])]=1
    return t
def embedding(n,odd): return [[int(i==j)*((-1)**b if odd else 1) for j in range(n)] for i,b in product(range(n),range(2))]
def restrict(a,e):
    a=mul(transpose(e),mul(a,e)); assert all(x%2==0 for x in flat(a))
    return [[x//2 for x in r] for r in a]
def constraints_dimension(t, symmetric=False, local=False, zero_constant=False):
    n=len(t); basis=[]
    for i,j in product(range(n),repeat=2):
        b=[[0]*n for _ in range(n)];b[i][j]=1;basis.append(b)
    def constraints(b):
        out=flat(add(mul(b,t),mul(t,b),-1))
        if symmetric: out+=flat(add(b,transpose(b),-1))
        if local:
            out += [b[i][j] for i,j in product(range(n),repeat=2) if i!=j and not t[i][j] and not t[j][i]]
        if zero_constant: out += [sum(r) for r in b]
        return out
    columns=[constraints(b) for b in basis]
    return n*n-rank(transpose(columns))

def main():
    t=shift((1,1,1));ident=eye(6);d=add(ident,t,-1)
    lap=mul(transpose(d),d)
    assert lap==add(add(scale(ident,2),t,-1),transpose(t),-1)
    even,odd=embedding(3,False),embedding(3,True)
    le,lo=restrict(lap,even),restrict(lap,odd)
    assert le==[[2,-1,-1],[-1,2,-1],[-1,-1,2]]
    assert lo==[[2,1,1],[1,2,1],[1,1,2]]
    assert rank(le)==2 and rank(add(le,scale(eye(3),3),-1))==1
    assert rank(add(lo,eye(3),-1))==1 and rank(add(lo,scale(eye(3),4),-1))==2
    assert mul(transpose(even),mul(lap,odd))==[[0]*3 for _ in range(3)]
    assert mul(lap,even)==mul(even,le) and mul(lap,odd)==mul(odd,lo)
    # Each paired clock link gives the corresponding rank-one signed edge term.
    local=[]
    for i in range(3):
        edge=[[0]*6 for _ in range(6)]
        for b in range(2):
            u,v=2*i+b,2*((i+1)%3)+(b^1)
            edge[u][u]+=1;edge[v][v]+=1;edge[u][v]-=1;edge[v][u]-=1
        block=restrict(edge,odd);assert rank(block)==1;local.append(block)
    assert lo==add(add(local[0],local[1]),local[2])
    signs=[]
    for bits in product(range(2),repeat=3):
        tt=shift(bits);dd=add(ident,tt,-1);ll=mul(transpose(dd),dd)
        block=restrict(ll,odd)
        expected=[[0]*3 for _ in range(3)]
        for i in range(3):
            j=(i+1)%3;s=(-1)**bits[i]
            expected[i][i]+=1;expected[j][j]+=1;expected[i][j]-=s;expected[j][i]-=s
        assert block==expected
        signs.append({'edge_flips':list(bits),'odd_block':block,'kernel_dimension':3-rank(block)})
    # Real six-clock operators constrained by stationarity and locality.
    dims={'clock_commuting_real':constraints_dimension(t),
          'clock_commuting_real_symmetric':constraints_dimension(t,True),
          'also_nearest_neighbor':constraints_dimension(t,True,True),
          'also_annihilates_constant':constraints_dimension(t,True,True,True)}
    assert dims=={'clock_commuting_real':6,'clock_commuting_real_symmetric':4,'also_nearest_neighbor':2,'also_annihilates_constant':1}
    # On contrast coordinates the clock is -P. Its zero-sum plane carries a rotation.
    s=restrict(t,odd);assert power(s,3)==scale(eye(3),-1)
    k=add(scale(s,2),eye(3),-1)
    assert power(k,2)==add(scale(eye(3),-3),[[4]*3 for _ in range(3)])
    result={'construction':'T(i,b)=(i+1 mod 3,b XOR 1); D=I-T; L=D^T D',
        'full_clock':t,'full_mismatch_operator':lap,
        'pair_even_embedding':even,'pair_odd_embedding':odd,
        'even_block':le,'odd_block':lo,'odd_local_edge_blocks':local,
        'even_spectrum':[0,3,3],'odd_spectrum':[1,1,4],
        'all_triangle_signings':signs,'operator_space_dimensions':dims,
        'contrast_clock':s,'rotation_plane_K':k,
        'rotation_identity':'K^2=-3I+4*ones; on sum(x)=0, J=K/sqrt(3) obeys J^2=-I',
        'conclusions':[
            'The odd contrast f(i,b)=(-1)^b*x_i obtains its sign from seed-pole exchange.',
            'Ordinary clock differences restrict to x_i+x_j; this reproduces the prior signed edge operators.',
            'Local real symmetric clock-stationary operators killing constants form one scale family: a*L.',
            'The real contrast plane supports one intrinsic complex structure; this is not yet a three-complex-dimensional color state space.'],
        'scope':[
            'Scalar readouts and the squared-difference observable are the representation under investigation.',
            'Locality, real symmetry, stationarity and the zero-constant condition specify the uniqueness class.',
            'No law of physical expansion, splitting rate, quantum amplitudes, or physical gauge action is claimed by these identities.',
            'A symmetric scalar function of L cannot equal the directed clock: L has paired opposite frequencies while T distinguishes them.']}
    out=Path(__file__).with_name('clock-transport-results.json')
    out.write_text(json.dumps(result,indent=2)+'\n',encoding='utf8')
    print('Clock-to-contrast restrictions, three local edge blocks, all eight signings and operator-space dimensions verified exactly.')
    print(json.dumps(dims));print('Saved',out)

if __name__=='__main__': main()
