"""Repro: python -B literal_234_robust.py result.json (requires a C++17 compiler).
From a separate directory, set PYTHONPATH to notebook evidence directory."""
from collections import Counter
from pathlib import Path
from tempfile import TemporaryDirectory
import subprocess,sys,json
import numpy as np
from literal_230_strict import primary,step
from line_mechanism_108 import geometry
from fixed_stream_133_135 import solved
def witness(x,k,m):
    st={0:(0,(),())}
    for i,c in enumerate(x):
        nxt={}
        for h,(co,hh,viol) in st.items():
            for j,hold in [((h+1)%4,False)]+([(h,True)] if c==0 else []):
                bad=(not hold) and c==k[h] and (m==0 or c!=0)
                r=(co+bad,hh+((i,) if hold else ()),viol+((i,) if bad else ()))
                if j not in nxt or r[0]<nxt[j][0]:nxt[j]=r
        st=nxt
    co,hh,viol=min(st.values(),key=lambda v:v[0]);H=set(hh);err=[];h=0;ct=[]
    for i,c in enumerate(x):
        if i in H:assert c==0;ct.append(0);continue
        p=(c-k[h])%29;ct.append((p+k[h])%29)
        if p==0 and (m==0 or c!=0):err.append(i)
        h=(h+1)%4
    assert ct==x and err==list(viol) and co==len(err)
    return dict(cost=co,key=k,exception_local=err,holds_local=list(hh))
def main():
    g,_=geometry();u=[(i,z) for i,z in enumerate(g) if z[1]==8];o=u[0][0];x=[z[3] for i,z in u];s=next(i-o for i,z in u if z[0]==51)
    with TemporaryDirectory() as t:
        exe=Path(t)/'cost';subprocess.run(['c++','-O3','-std=c++17',str(Path(__file__).with_name('literal_234_cost.cpp')),'-o',str(exe)],check=True)
        raw=subprocess.check_output([str(exe)],input=' '.join(map(str,x)),text=True);rows=[list(map(int,l.split())) for l in raw.splitlines()]
    modestats={}
    for m in (0,1):
        rr=[r for r in rows if r[0]==m];assert sum(r[4] for r in rr)==29**4;stats={}
        for name,pred in [('nonidentity',lambda r:r[2]>0),('true_period_four',lambda r:r[1]==4),('four_nonzero',lambda r:r[2]==4),('true_four_and_four_nonzero',lambda r:r[1]==4 and r[2]==4)]:
            z=[r for r in rr if pred(r)];best=min(r[3] for r in z);tied=[r for r in z if r[3]==best]
            w=witness(x,tied[0][5:],m);assert w['cost']==best
            stats[name]=dict(minimum=best,tied=sum(r[4] for r in tied),by_budget={j:sum(r[4] for r in z if r[3]<=j) for j in [0,1,2,3,4,5,10,20,30]},example=w)
        modestats[m]=stats
    panels={}
    origin=np.array([z[0] for _,z in u])
    for name,a,b in [('first half',0,len(x)//2),('second half',len(x)//2,len(x)),('before grid',0,s),('after grid',s,len(x))]:
        k,h=primary(x[a:b]);free={tuple(v[i:]+v[:i]) for v in k for i in range(4)}
        panels[name]=dict(start=a,end=b,slot_zero_survivors=len(k),any_phase_survivors=len(free),nonzero_example=next((list(z) for z in sorted(free) if any(z)),None))
    py,_=solved();gold={}
    for (name,part),(val,_) in py.items():gold.setdefault(name,[]).extend(map(int,val))
    controls={}
    for name,gg in gold.items():
        k=[3,9,14,23];h=0;c=[]
        for p in gg:
            if p==0:c.append(0)
            else:c.append((p+k[h])%29);h=(h+1)%4
        keys,_=primary(c);assert k in keys
        controls[name]=dict(n=len(c),remaining=len(keys),planted_survives=True)
    return dict(origin=o,size=len(x),summaries=modestats,by_mode_period_nonzero_cost_count=[r[:5] for r in rows],independent_segment_tests=panels,planted_solved=controls)
if __name__=='__main__':
    r=main();Path(sys.argv[1]).write_text(json.dumps(r,separators=(',',':'))+'\n')
    for m,v in r['summaries'].items():print(m,[(s,k['minimum'],k['tied'],k['by_budget'][5]) for s,k in v.items()])
    print(r['independent_segment_tests'],r['planted_solved'])
