"""Run with the notebook's earlier /files modules on PYTHONPATH, a C++17 compiler and numpy.
OPENBLAS_NUM_THREADS=1 python -B holds_227_228.py holds_227_228_results.json.gz
"""
from collections import Counter
from itertools import product
from pathlib import Path
import gzip, hashlib, json, math, os, subprocess, sys, tempfile
from line_mechanism_108 import geometry, cfg
from fixed_stream_133_135 import solved

def brute(A, x):
    """No DP: replay all physical hold masks for every possible ordered key."""
    zeros=[i for i,c in enumerate(x) if c==0]
    masks=[set(i for j,i in enumerate(zeros) if (m>>j)&1) for m in range(1<<len(zeros))]
    hist=[Counter(),Counter()]; winners=[[],[]]; high=[-1,-1]
    for k in product(range(A),repeat=4):
        best=[0,0]
        for holds in masks:
            phase=count=0
            for i,c in enumerate(x):
                if i not in holds:
                    count+=(c==k[phase]); phase=(phase+1)%4
            best[0]=max(best[0],count); best[1]=max(best[1],count+len(holds))
        for j,t in enumerate(best):
            hist[j][t]+=1
            if t>high[j]: high[j]=t; winners[j]=[]
            if t==high[j]: winners[j].append(k)
    return hist,winners,len(masks)*A**4

def engine(cases):
    with tempfile.TemporaryDirectory() as tmp:
        exe=str(Path(tmp)/'cap')
        subprocess.run([os.environ.get('CXX','c++'),'-O3','-std=c++17',str(Path(__file__).with_suffix('.cpp')),'-o',exe],check=True)
        inp=''.join(' '.join(map(str,(a,len(x),*x)))+'\n' for a,x in cases)
        out=subprocess.run([exe],input=inp,text=True,check=True,capture_output=True).stdout
    rows=[]
    for line in out.splitlines():
        tag,*t=line.split(); v=list(map(int,t))
        if tag=='BEGIN':
            hist=[Counter(),Counter()]; wins=[[],[]]
            assert tuple(v)==(cases[len(rows)][0],len(cases[len(rows)][1]))
        elif tag=='H':
            for j in (0,1):
                if v[j+1]:hist[j][v[0]]=v[j+1]
        elif tag=='W': wins[v[0]].append(tuple(v[1:]))
        elif tag=='END': rows.append((hist,wins))
        else: raise ValueError(line)
    assert len(rows)==len(cases)
    return rows

def merge(a,b):
    """Return score, path count, min/max holds, shortest then earliest witness."""
    if a is None or a[0]<b[0]: return b
    if a[0]>b[0]: return a
    return (a[0],a[1]+b[1],min(a[2],b[2]),max(a[3],b[3]),min((a[4],b[4]),key=lambda ex:(len(ex),ex)))

def witness(x,d,target,A=29):
    states={0:(0,1,0,0,())}
    for i,c in enumerate(x):
        nxt={}
        for s,(z,count,lo,hi,ex) in states.items():
            s1=(s+1)%4
            nxt[s1]=merge(nxt.get(s1),(z+(c==d[s]),count,lo,hi,ex))
            if c==0:
                nxt[s]=merge(nxt.get(s),(z+(target==0),count,lo+1,hi+1,ex+(i,)))
        states=nxt
    result=None
    for v in states.values(): result=merge(result,v)
    z,mults,lo,hi,ex=result; holds=set(ex); assert len(holds)==lo
    k=[(a-target)%A for a in d]; s=0; count=Counter()
    for i,c in enumerate(x):
        if i in holds:
            assert c==0
            y=0; kind='held_printed_F'
        else:
            y=(c-k[s])%A; s=(s+1)%4; kind='advanced_printed_F' if c==0 else 'advanced_other_rune'
        if y==target: count[kind]+=1
    assert z==sum(count.values()) and s==(len(x)-len(holds))%4
    return dict(adjusted_key=d,key=k,score=z,optimal_mask_count=str(mults),range_holds=[lo,hi],holds=list(ex),
        witness_final_phase=s,witness_target_sources={k:count[k] for k in ['held_printed_F','advanced_printed_F','advanced_other_rune']})

def fixed(x,policy):
    h=[Counter() for _ in range(4)]; held=s=0
    for c in x:
        if c==0 and policy=='always':held+=1
        else:h[s][c]+=1;s=(s+1)%4
    tops=[max(r.values()) for r in h]
    choices=[sorted(c for c,v in row.items() if v==m) for row,m in zip(h,tops)]
    return dict(held=held,phase_max_normal_hits=tops,adjusted_key_choices=choices,number_of_winning_keys=math.prod(map(len,choices)),
                E=sum(tops),F=sum(tops)+held)

def main():
    g,_=geometry(); inds=[i for i,q in enumerate(g) if q[1]==8]; assert inds==list(range(9640,12956))
    x=tuple(g[i][3] for i in inds); assert (len(x),x.count(0))==(3316,131)
    cases=[(2,())]+[(a,x) for a,n in [(2,6),(3,5)] for x in product(range(a),repeat=n)]
    rows=engine(cases+[(29,x)]); trials=keys=0
    for (a,mini),(hist,wins) in zip(cases,rows):
        bh,bw,nt=brute(a,mini);assert bh==hist and bw==wins; trials+=nt;keys+=a**4
    mini_results=dict(cases=len(cases),key_input_combinations=keys,key_mask_input_combinations=trials,
        fixtures='empty binary string plus every length-6 binary and length-5 ternary string; compared both full histograms and complete winner lists to direct unblocked brute replay')
    hist,wins=rows[-1]
    bench=Counter(int(c) for arr,ls in solved()[0].values() for c in arr); nbench=sum(bench.values())
    assert (bench[18],nbench)==(349,2797)
    targets={}
    for j,(name,target) in enumerate([('E',18),('F',0)]):
        mx=max(hist[j]); assert sum(hist[j].values())==29**4
        w=[witness(x,d,target) for d in wins[j]]; assert all(e['score']==mx for e in w)
        assert len(w)==hist[j][mx]
        targets[name]=dict(score=mx,winners=w,ordered_key_histogram=dict(hist[j]))
    out=dict(model='one nominal period-four additive key, start phase zero; optional literal F holds only at printed F, ordinary decryption elsewhere; section-relative zero-based holds',
        phase_convention='d[s]=(target+key[s]) mod 29, ordinary target hit iff c==d[s]',
        witness_tiebreak='fewest holds, then lexicographically earliest sorted offset tuple, per key',
        section_length=len(x),printed_F=x.count(0),distinct_schedules=str(2**x.count(0)),ordered_key_count=29**4,
        source_sha256=cfg['source_sha256'],section_rune_bytes_sha256=hashlib.sha256(bytes(x)).hexdigest(),global_offset_0based=inds[0],
        target_benchmark=dict(E_count=bench[18],F_count=bench[0],solved_runes=nbench,scaled_E_required=math.ceil(bench[18]*len(x)/nbench)),
        targets=targets,fixed_policies={p:fixed(x,p) for p in ['never','always']},brute_validation=mini_results)
    dest=Path(sys.argv[1]);dest.write_bytes(gzip.compress(json.dumps(out,separators=(',',':'),sort_keys=True).encode(),mtime=0))
    for t,v in targets.items():
        for e in v['winners']: print(t,{k:q for k,q in e.items() if k not in ('holds','adjusted_key')})
    print(mini_results)
    print(out['target_benchmark'])
if __name__=='__main__':main()
