"""All single reset locations for periods 1..9, strict plaintext-F holds. Run: python -B reset_244_one.py out.json.gz [directory of published evidence]"""
from pathlib import Path
from itertools import product
from collections import Counter
import gzip,hashlib,json,subprocess,tempfile,sys
D=Path(sys.argv[2] if len(sys.argv)>2 else Path(__file__).resolve().parent);sys.path.insert(0,str(D))
from literal_234_verify import scan,rotations,source
def sweep(exe,x,p,keys):
 raw=' '.join(map(str,[len(x),p,*x]+[i for k in keys for i in k]))
 lines=subprocess.check_output([str(exe)],input=raw,text=True).splitlines()
 o={}
 for line in lines:
    v=list(map(int,line.split()));assert v[p]==len(v)-p-1;o[tuple(v[:p])]=v[p+1:]
 return o
def states(x,k):
 r={0}
 for c in x:r=({(h+1)%len(k) for h in r if k[h]!=c}|(r if c==0 else set()))
 return r
def witness(x,k,cut):
 outs=[]
 for part in [x[:cut],x[cut:]]:
    st={0};pr=[]
    for c in part:
        t={}
        for h in sorted(st):
            if c==0:t[h]=(h,0)
            if c!=k[h]:t[(h+1)%len(k)]=(h,(c-k[h])%29)
        st=set(t);pr.append(t)
    assert st;h=min(st);w=[]
    for t in pr[::-1]:h,v=t[h];w.append(v)
    assert h==0;outs.extend(w[::-1])
 h=0;re=[]
 for i,v in enumerate(outs):
    if i==cut:h=0
    if v==0:re.append(0)
    else:re.append((v+k[h])%29);h=(h+1)%len(k)
 assert x==re;return dict(k=list(k),cut=cut,changed=sum(v!=a for a,v in zip(outs,x)),digest=hashlib.sha256(bytes(outs)).hexdigest())
def run():
 x=source(D);mid=len(x)//2;r={}
 with tempfile.TemporaryDirectory() as t:
    e1,e2=[Path(t)/s for s in ['classes','cuts']]
    for f,e in [(D/'literal_234_independent.cpp',e1),(Path(__file__).with_suffix('.cpp'),e2)]:
        subprocess.run(['c++','-O3','-std=c++17',str(f),'-o',str(e)],check=True)
    fx=0
    for p in range(1,4):
        ks=list(product(range(3),repeat=p))
        for z in product(range(2),repeat=5):
            toy=list(z);a=sweep(e2,toy,p,ks)
            ref={k:[j for j in range(1,len(toy)) if states(toy[:j],k) and states(toy[j:],k)] for k in ks if any(k)};assert a=={k:v for k,v in ref.items() if v};fx+=1
    for p in range(1,10):
        halves=[scan(e1,z,p)[0] for z in (x[:mid],x[mid:])]
        can={tuple(k)for cls in halves for kk in cls for k in rotations(kk) if any(k)}
        hits=sweep(e2,x,p,sorted(can));counts=Counter(g for gaps in hits.values() for g in gaps);win=None
        if hits:
            k=min(hits);win=witness(x,k,hits[k][0])
        # Delta coding keeps the evidence small while preserving every address for every key.
        r[p]=dict(half_classes_including_identity=[len(i) for i in halves],candidates=len(can),feasible_gaps=len(counts),feasible_keys=len(hits),key_gap_pairs=sum(counts.values()),at_mark=dict((g,counts[g]) for g in [8,2474,2957,3008,3017]),histogram_over_3315=sorted(Counter(counts.get(j,0) for j in range(1,len(x))).items()),witness=win,per_key_gaps_deltas=[[list(k),[v[0]]+[b-a for a,b in zip(v,v[1:])]] for k,v in hits.items()])
        print(p, r[p]['candidates'],len(hits),len(counts),sum(counts.values()),flush=True)
 return dict(fixture_sweeps=fx,n=len(x),sha256=hashlib.sha256(bytes(x)).hexdigest(),reports=r)
if __name__=='__main__':
 r=run();Path(sys.argv[1]).write_bytes(gzip.compress(json.dumps(r,separators=(',',':')).encode(),mtime=0))
