"""Exploratory counterexample: independent check on keys w/ exactly one nonzero slot at periods 1–32. Run in evidence folder: python -B literal_234_neighbor.py result.json"""
from pathlib import Path
import json,sys
from line_mechanism_108 import geometry
from lp_core import LET
def main():
 g,_=geometry();x=[v[3] for v in g if v[1]==8];out={};ex=None
 for p in range(1,33):
    allb=(1<<p)-1;good=[]
    def rot(m):return ((m<<1)&allb)|(m>>(p-1))
    for d in range(1,29):
        # Exactly one nonzero shift d at slot 0; every starting phase simultaneously. Normal branch at F advances ONLY slot zero.
        m=allb
        for c in x:
            if c==0:m|=rot(m&1)
            else:m=rot(m & (~1 if c==d else allb))
            if not m:break
        if m:good.append(d)
    out[p]=good
    if good and ex is None:
        d=good[0];k=[d]+[0]*(p-1)
        # An ordinary per-rune parent chain, with free starting phase, to independently replay this witness.
        reach=set(range(p));pre=[]
        for c in x:
            tr={}
            for h in sorted(reach):
                if not c:tr[h]=(h,True)
                if c!=k[h]:tr[(h+1)%p]=(h,False)
            reach=set(tr);pre.append(tr)
        assert reach
        h=min(reach);dec=[];held=[]
        for i in range(len(x)-1,-1,-1):
            h,lit=pre[i][h]
            dec.append(0 if lit else (x[i]-k[h])%29)
            if lit:held.append(i)
        first=h;dec=dec[::-1];check=[]
        for v in dec:
            if v==0:check.append(0)
            else:check.append((v+k[h])%29);h=(h+1)%p
        assert check==x and [i for i,v in enumerate(dec) if v==0]==sorted(held)
        ex=dict(period=p,nonzero_shift=d,key=k,initial_phase=first,holds_local=sorted(held),different_positions=sum(a!=b for a,b in zip(x,dec)),example_only=True)
 return dict(scope='keys with exactly one nonzero slot, all cyclic rotations and all literal-F paths, periods 1..32. Not an exhaustive search across dense keys at periods other than four.',feasible_nonzero_shifts_by_period=out,first_example=ex)
if __name__=='__main__':
 r=main();Path(sys.argv[1]).write_text(json.dumps(r,separators=(',',':'))+'\n');print([(p,len(v)) for p,v in r['feasible_nonzero_shifts_by_period'].items()][:18]);print({k:v for k,v in r['first_example'].items() if k!='holds_local'})
