"""Optional 7/8 follow-up. Replays any found nonidentity key under the strict encoder.
python -B literal_234_search.py out.json"""
from pathlib import Path
from tempfile import TemporaryDirectory
import subprocess,sys,json
from line_mechanism_108 import geometry
def replay(x,k):
 p=len(k)
 for start in range(p):
    reach={start};hist=[]
    for c in x:
        t={}
        for h in sorted(reach):
            if not c:t[h]=(h,True)
            if c!=k[h]:t[(h+1)%p]=(h,False)
        hist.append(t);reach=set(t)
        if not t:break
    if not reach:continue
    h=min(reach);holds=[];pt=[]
    for i in reversed(range(len(x))):
        h,lit=hist[i][h]
        if lit:holds.append(i)
        pt.append(0 if lit else (x[i]-k[h])%29)
    pt=pt[::-1];assert h==start;actual=[]
    for v in pt:
        if not v:actual.append(0)
        else:actual.append((v+k[h])%29);h=(h+1)%p
    assert actual==x
    return dict(start=start,holds=sorted(holds),changed=sum(a!=b for a,b in zip(pt,x)))
 raise ValueError('false witness')
def main():
 g,_=geometry();x=[z[3] for z in g if z[1]==8]
 with TemporaryDirectory() as t:
    e=Path(t)/'search';subprocess.run(['c++','-O3','-std=c++17',str(Path(__file__).with_suffix('.cpp')),'-o',str(e)],check=True)
    r=subprocess.check_output([str(e)],input=' '.join(map(str,x)),text=True)
 ans=[]
 for line in r.splitlines():
    n,status,cuts,dead,*kk=line.split();key=list(map(int,kk));row=dict(p=int(n),status=status,partial_assignments=int(cuts),impossible=int(dead),key=key)
    if status=='witness':row['replay']=replay(x,key)
    ans.append(row)
 return ans
if __name__=='__main__':
 r=main();Path(sys.argv[1]).write_text(json.dumps(r,separators=(',',':'))+'\n');print([{k:v for k,v in a.items() if k!='replay'} for a in r])
