"""Reproduce: python -B reset_244_min.py result.json. Requires C++17 and existing notebook transcription helpers."""
import itertools,json,subprocess,sys,tempfile
from pathlib import Path
from collections import Counter
from line_mechanism_108 import geometry
def walk(x,k,mode,budget):
 # Exact shortest-cost trace with changed-rune flag, phase state; do not discard the feasibility of actual changed text.
 st={(0,False):0};prev=[]
 for i,c in enumerate(x):
    nx={};back={}
    for (h,changed),cost in st.items():
        choices=[(h,0)]
        if i and cost<budget:choices+=[(q,1) for q in (range(4) if mode else (0,)) if q!=h]
        for q,r in choices:
            moves=([(q,0,1)] if c==0 else [])+([((q+1)%4,(c-k[q])%29,0)] if c!=k[q] else [])
            for j,p,held in moves:
                key=(j,changed or p!=c);co=cost+r
                if co<nx.get(key,10**9):nx[key]=co;back[key]=((h,changed),q,r,p,held)
    st=nx;prev.append(back)
    if not st:return None,None
 best=min(st.values());opts=[(c,h)for h,c in st.items() if h[1]]
 if not opts:return best,None
 co,at=min(opts);trace=[];holds=[];pt=[]
 for i in range(len(x)-1,-1,-1):
    at,q,r,p,held=prev[i][at]
    if r:trace.append([i,q])
    if held:holds.append(i)
    pt.append(p)
 pt=pt[::-1];phase=0;rst=dict(trace);re=[]
 for i,p in enumerate(pt):
    if i in rst:phase=rst[i]
    if not p:re.append(0)
    else:re.append((p+k[phase])%29);phase=(phase+1)%4
 assert re==x and len(trace)==co and sum(p!=c for p,c in zip(pt,x))>0
 return best,dict(key=k,required=co,restarts=trace[::-1],holds=holds[::-1],changed=sum(p!=c for p,c in zip(pt,x)))
def run():
 g,_=geometry();x=[z[3] for z in g if z[1]==8]
 with tempfile.TemporaryDirectory() as t:
    exe=Path(t)/'min';subprocess.run(['c++','-O3','-std=c++17',str(Path(__file__).with_suffix('.cpp')),'-o',str(exe)],check=True)
    data=[list(map(int,l.split())) for l in subprocess.check_output([str(exe)],text=True,input=' '.join(map(str,x))).splitlines()]
    fixtures=[[1,2,0,1,2,1,0,2],[1,2,1,1,2,2,1],[1,0,0,2,1,2,0],[2,1,0,2,2,1]]
    trials=0;needed=0
    for toy in fixtures:
        recs=[list(map(int,l.split())) for l in subprocess.check_output([str(exe),'3'],text=True,input=' '.join(map(str,toy))).splitlines()]
        base={(m,nz,b):n for m,nz,b,n,*_ in recs};checks=Counter()
        for k in itertools.product(range(3),repeat=4):
            for m in (0,1):
                best=13
                for b in range(len(toy)):
                    for cs in itertools.combinations(range(1,len(toy)),b):
                        st={0}
                        for i,c in enumerate(toy):
                            if st and i in cs:st=set(range(4)) if m else {0}
                            st=({(h+1)%4 for h in st if k[h]!=c}|(st if c==0 else set()))
                        if st:best=b;break
                    if best==b:break
                checks[m,sum(v!=0 for v in k),best]+=1;trials+=1;needed+=0<best<13
        assert checks==base
    assert needed
 def key(e):return [(e//29**s)%29 for s in range(4)]
 res={}
 for m in (0,1):
    rr=[r for r in data if r[0]==m];assert sum(r[3] for r in rr)==29**4
    nz=[r for r in rr if r[1]];mi=min(r[2] for r in nz);win=[r for r in nz if r[2]==mi]
    wit=[]
    for r in win:
        for e in r[4:]:
            co,w=walk(x,key(e),m,mi);assert co==mi
            if w and w['required']==mi:wit.append(w)
    assert wit,'need further testing of changed text'
    for r in rr:
        e=r[4];cost=r[2]
        if cost<=12:
            co,_=walk(x,key(e),m,cost);assert co==cost
        else:assert walk(x,key(e),m,12)==(None,None)
    res[m]=dict(minimum_nonzero=mi,n_at_min=sum(r[3] for r in win),key_counts_cumulative_nonzero=[sum(r[3] for r in nz if r[2]<=b) for b in range(13)],witnesses=wit[:4],hist_by_nz=[[r[1],r[2],r[3]]for r in rr])
 return dict(toy_key_mode_cases=trials,toy_cases_needing_a_restart=needed,n=len(x),mode0='reset to slot zero',mode1='jump to any slot',hist_last_bin='13 means greater than 12',results=res)
if __name__=='__main__':
 r=run();Path(sys.argv[1]).write_text(json.dumps(r,separators=(',',':'))+'\n')
 for m,v in r['results'].items():print(m,v['minimum_nonzero'],v['n_at_min'],v['key_counts_cumulative_nonzero'],[(w['key'],w['restarts'],w['changed'])for w in v['witnesses']])
