"""Run in the evidence directory, or pass --evidence DIR and --independent path/to/reset_238_search.cpp.
Builds two C++17 implementations, recomputes the geometry selection, and emits a deterministic compressed record."""
from pathlib import Path
import argparse,itertools,hashlib,gzip,json,random,subprocess,tempfile,os
from collections import Counter
from marks_240_241_coords import coordinates
H=Path(__file__).resolve().parent
def brute(x,p,q,maps):
    # Direct product of all ordered keys and every printed-F choice within each segment; no bitset traversal.
    def supported(k,cuts):
        for a,b in zip([0]+cuts,cuts+[len(x)]):
            good=False;fs=[i for i in range(a,b) if not x[i]]
            for flags in itertools.product([0,1],repeat=len(fs)):
                held={i for i,val in zip(fs,flags) if val};j=0
                for i in range(a,b):
                    if i in held:continue
                    if x[i]==k[j]:break
                    j=(j+1)%p
                else:good=True;break
            if not good:return False
        return True
    return [[tuple(k) for k in itertools.product(range(q),repeat=p) if supported(k,cut)] for cut in maps]
def run(args):
    import sys
    D=Path(args.evidence).resolve();sys.path.insert(0,str(D))
    from line_mechanism_108 import geometry
    coords=coordinates(D);x=[r[3] for r in geometry()[0] if r[1]==8];sha=hashlib.sha256(bytes(x)).hexdigest()
    assert len(x)==coords['n'] and sha=='e559526547bafe860d99394136b7166a2bf3902f3a7bd439b7dca30aaf487927'
    layout=[coords['primary']]+coords['word']['cuts']+coords['page']['cuts']
    assert len(set(map(tuple,layout)))==len(layout)==74
    with tempfile.TemporaryDirectory() as td:
        td=Path(td)
        def compile_(path,exe):
            subprocess.run([os.getenv('CXX','c++'),'-std=c++17','-O3',str(path),'-o',str(exe)],check=True)
        exe=td/'search';ref=td/'ref';compile_(H/'marks_240_241.cpp',exe);compile_(args.independent or D/'reset_238_search.cpp',ref)
        def production(p,q,x,cuts):
            z=[p,q,len(x),len(cuts)]+list(x)+sum(([len(c)]+c for c in cuts),[])
            txt=subprocess.run([exe],input=' '.join(map(str,z)),text=True,check=True,capture_output=True).stdout.splitlines()
            assert txt[-1]=='END';surv=[[] for _ in cuts];counts=list(map(int,txt[0].split()[1:]));assert counts[0]==p
            for line in txt[1:-1]:
                k,i,*v=line.split();assert k=='K';surv[int(i)].append(tuple(map(int,v)))
            for a in surv:assert a==sorted(set(a))
            return surv,counts[1]
        rng=random.Random(2403301);fix=[]
        for i in range(12):
            q=2+i%3;p=1+i%4;x0=[rng.randrange(q) for _ in range(11)]
            cut=[[2,6],[3,8],[]];expected=brute(x0,p,q,cut);ans,_=production(p,q,x0,cut);assert expected==ans
            fix.append(dict(q=q,p=p,cipher=x0,cuts=cut,key_counts=list(map(len,ans))))
        q=5;p=3;key=[1,4,2];cuts=[6,13];plain=[0,2,3,4,1,0,3,1,4,2,0,3,4,0,3,2,1,4,3];z=[];phase=0
        for i,c in enumerate(plain):
            if i in cuts:phase=0
            if not c:z.append(0);continue
            z.append((c+key[phase])%q);phase=(phase+1)%p
        maps=[cuts,[5,14],[]];expected=brute(z,p,q,maps);ans,_=production(p,q,z,maps);assert ans==expected and tuple(key) in ans[0]
        plant=dict(plain=plain,cipher=z,q=q,key=key,layouts=maps,known_key_survives=[tuple(key) in v for v in ans],ordered_counts=list(map(len,ans)))
        keys={};supercounts={};cross=[]
        for p in range(1,10):
            allkeys,fc=production(p,29,x,layout);supercounts[p]=fc;assert all(tuple([0]*p) in ks for ks in allkeys)
            keys[p]=[[k for k in ks if any(k)] for ks in allkeys]
            if p in (8,9):
                # Verify the actual pair and the first/last emitted control of each arm.
                for i in (0,1,64,65,73):
                    c=layout[i];z=[len(x),p,len(c),29]+x+c
                    txt=subprocess.run([ref],input=' '.join(map(str,z)),text=True,capture_output=True,check=True).stdout.splitlines()
                    other=sorted(tuple(map(int,l.split()[1:])) for l in txt if l.startswith('K '))
                    assert other==allkeys[i];cross.append(dict(p=p,layout=i,count_including_identity=len(other)))
    summary={}
    for tag,idx in [('word',range(1,65)),('page',range(65,74))]:
        s={p:dict(histogram=dict(sorted(Counter(len(keys[p][i]) for i in idx).items())),actual_keys_repeated=sum(bool(set(keys[p][0])&set(keys[p][i])) for i in idx)) for p in (8,9)}
        s['both_periods_nonidentity']=sum(bool(keys[8][i]) and bool(keys[9][i]) for i in idx)
        s['both_marked_ordered_keys']=sum(bool(set(keys[8][i])&set(keys[8][0])) and bool(set(keys[9][i])&set(keys[9][0])) for i in idx)
        summary[tag]=s
    return dict(raw_sha256=sha,layout_order='marked pair; 64 local ordinary word pairs; 9 nearby genuine page pairs; indices start at 0',cuts=layout,coords=coords,identity_survives_every_layout=True,nonidentity_keys=keys,relaxed_ordered_candidates_including_identity=supercounts,summary=summary,fixtures=fix,plant=plant,independent_full_checks=cross)
if __name__=='__main__':
    ap=argparse.ArgumentParser(__doc__);ap.add_argument('--evidence',default=H,type=Path);ap.add_argument('--independent',type=Path);ap.add_argument('--out',type=Path,default=H/'marks_240_241_results.json.gz');args=ap.parse_args()
    b=json.dumps(run(args),separators=(',',':')).encode();args.out.write_bytes(gzip.compress(b,mtime=0));print('SHA256 of uncompressed JSON:',hashlib.sha256(b).hexdigest())
