"""Public independent replay: python -B literal_234_verify.py literal_234_verify.json
Requires a C++17 compiler and the notebook source directory. Pass --evidence DIR for a split working tree."""
import argparse, hashlib, itertools, json, subprocess, tempfile
from pathlib import Path

def source(e):
    from sys import path
    path.insert(0,str(e));from lp_core import R,lp
    j=json.loads((e/'three_tests_plan.json').read_text())
    assert hashlib.sha256((e/'liber-primus__transcription--master.txt').read_bytes()).hexdigest()==j['source_sha256']
    return [R.index(c) for c in ('%'.join(lp[:56])).split('$')[8] if c in R]

def rotations(k):return [k[i:]+k[:i] for i in range(len(k))]
def scan(exe,x,p,q=29):
    raw=subprocess.check_output([str(exe),str(q)],text=True,input=' '.join(map(str,[len(x),p,*x]))).splitlines()
    levels=[list(map(int,row.split())) for row in raw[:3]]
    return [list(map(int,r[2:].split())) for r in raw[3:]],dict(tried=levels[0][1:],after_strip_filter=levels[1][1:],after_window_filter=levels[2][1:])

def paths(x,k,st,witness=False):
    # Python state sets and backward trace; primitive legality uses no strip tests.
    n=len(k);live={st};hist=[]
    for c in x:
        nxt={}
        for i in sorted(live):
            if c!=k[i]:nxt[(i+1)%n]=(i,False)
            if c==0:nxt[i]=(i,True)
        if witness:hist.append(nxt)
        live=set(nxt)
        if not live:return None
    if not witness:return sorted(live)
    end=min(live);cur=end;held=[]
    for ix in range(len(x)-1,-1,-1):
        cur,h=hist[ix][cur]
        if h:held.append(ix)
    assert cur==st;held.reverse();assert all(x[i]==0 for i in held)
    p=st;hs=set(held);plain=[];cipher=[]
    for i,z in enumerate(x):
        y=0 if i in hs else (z-k[p])%29
        assert (y==0)==(i in hs);plain.append(y)
        cipher.append(0 if y==0 else (y+k[p])%29)
        if y:p=(p+1)%n
    assert p==end and cipher==x
    return dict(start=st,end=end,end_options=sorted(live),holds=len(held),held_offsets=held,
                plaintext_byte_sha256=hashlib.sha256(bytes(plain)).hexdigest())

def plant(n,key,seed):
    b=b'';j=0
    while len(b)<n:
        b+=hashlib.sha256((seed+':'+str(j)).encode()).digest();j+=1
    y=[i%29 for i in b[:n]];p=2;r=[];held=[]
    for i,v in enumerate(y):
        if v==0:r.append(0);held.append(i)
        else:r.append((v+key[p])%29);p=(p+1)%len(key)
    return r,dict(seed=seed,start=2,expected_key=key,known_holds=len(held),ordinary_wraps_to_printed_F=r.count(0)-len(held))

def run(path,evd):
    x=source(evd);assert len(x)==3316 and x.count(0)==131
    with tempfile.TemporaryDirectory(prefix='cicada_strict_independent_') as t:
        exe=Path(t)/'proof';subprocess.run(['c++','-O3','-std=c++17',str(path/'literal_234_independent.cpp'),'-o',str(exe)],check=True)
        data=dict(source_rune_byte_sha256=hashlib.sha256(bytes(x)).hexdigest(),positions=len(x),printed_F=x.count(0),solved={},planted=[])
        for p in range(1,10):
            ks,c=scan(exe,x,p)
            records=[]
            for kk in ks:
                # Display the sparse key with its nonzero entry first, otherwise use the canonical orientation.
                k=max(rotations(kk));starts=[s for s in range(p) if paths(x,k,s) is not None]
                assert starts
                if any(k):tr=[paths(x,k,s,True) for s in starts]
                else:tr=[];assert starts==list(range(p))
                records.append(dict(key=k,legal_starts=starts,ordered_keys_at_start_zero=len(set(tuple(k[s:]+k[:s]) for s in starts)),direct_witnesses=tr))
            data['solved'][p]=dict(cyclic_classes=records,counts=c,
                nonidentity_ordered=sum(rr['ordered_keys_at_start_zero'] for rr in records if any(rr['key'])))
        for p,k in ((7,[1,3,5,7,11,13,17]),(8,[2,4,6,8,11,13,15,17])):
            x0,rec=plant(len(x),k,'literal_verify:'+str(p))
            ks,_=scan(exe,x0,p);assert min(rotations(k)) in ks and rec['ordinary_wraps_to_printed_F']>0 and rec['known_holds']>0
            assert paths(x0,k,2) is not None
            rec.update(period=p,found=True,cyclic_classes=len(ks),ciphertext_sha256=hashlib.sha256(bytes(x0)).hexdigest())
            data['planted'].append(rec)
        count=0
        for p in range(1,5):
            for seq in itertools.product(range(2),repeat=4):
                ks,_=scan(exe,list(seq),p,2);truth=set()
                for rank in itertools.product(range(2),repeat=p):
                    if paths(seq,rank,0) is not None:truth.add(min(rotations(rank)))
                assert {tuple(k) for k in ks}==truth
                count+=1
        data['exhaustive_tiny_corpora_times_periods']=count
    return data
if __name__=='__main__':
    here=Path(__file__).resolve().parent
    a=argparse.ArgumentParser();a.add_argument('output',type=Path);a.add_argument('--evidence',type=Path,default=here);r=a.parse_args()
    z=run(here,r.evidence.resolve());r.output.write_text(json.dumps(z,indent=2,sort_keys=True)+'\n')
