"""Replay in notebook evidence directory: python -B mass_231_232.py mass_231_232_results.json.gz
Needs C++17 compiler and existing pinned LP1, LP2 evidence helpers; supply optional evidence directory."""
from pathlib import Path
import os,sys,subprocess,gzip,json,hashlib,math,tempfile
from collections import Counter,deque
from itertools import product
HERE=Path(__file__).resolve().parent;D=Path(sys.argv[2]).resolve() if len(sys.argv)>2 else HERE
sys.path.insert(0,str(D));from fixed_stream_133_135 import solved
from line_mechanism_108 import geometry
from lp_core import LET

def clock(x,k,hs,A):
    p=0;out=[]
    for i,c in enumerate(x):
        if i in hs:
            assert c==0;out.append(0)
        else:out.append((c-k[p%4])%A);p+=1
    return out
def witness(x,k,use,T,A):
    # Per-rune DP, not the non-F-block implementation of the global search.
    best=None
    for rot in range(4):
        key=k[rot:]+k[:rot];v={0:0};back=[]
        for i,c in enumerate(x):
            u={};prev={}
            for st,val in sorted(v.items()):
                opts=[((st+1)%4,val+use[i]*((c-key[st])%A in T),0)]
                if c==0:opts.append((st,val+use[i]*(0 in T),1))
                for z,n,h in opts:
                    if n>u.get(z,-1):u[z]=n;prev[z]=(st,h)
            v=u;back.append(prev)
        st=max(v,key=v.get);score=v[st];hs=[]
        for i in range(len(x)-1,-1,-1):
            st,h=back[i][st]
            if h:hs.append(i)
        hs.reverse();y=clock(x,key,set(hs),A);hits=Counter(a for a,m in zip(y,use) if m and a in T)
        assert sum(hits.values())==score
        if best is None or score>best['cap']:best=dict(cap=score,key=key,holds=hs,counts=dict(sorted(hits.items())))
    return best
def never(x,use,T,A):
    tab=[[sum(m and ((c-k)%A in T) for c,m in zip(x[j::4],use[j::4])) for k in range(A)] for j in range(4)]
    key=[v.index(max(v)) for v in tab];return dict(cap=sum(map(max,tab)),key=key)
def fixture(A,x,use,T):
    m=len(x);i0=[i for i,c in enumerate(x) if c==0];best=-1
    for h in product((0,1),repeat=len(i0)):
        hs={i for i,b in zip(i0,h) if b}
        for k in product(range(A),repeat=4):
            y=clock(x,k,hs,A)
            best=max(best,sum(bool(m) and z in T for z,m in zip(y,use)))
    return best
def inventory(x,T):
    # Fixed F mask, no holds. Integral maximum flow, with one node per non-F value and key slot.
    A=29;k=[0,7,14,21];freq=Counter(x);slots=[sum(c!=0 and i%4==j for i,c in enumerate(x)) for j in range(4)]
    source=0;sink=33;adj=[{} for _ in range(sink+1)]
    def edge(a,b,cap):adj[a][b]=cap;adj[b][a]=0
    for c in range(1,A):
        edge(source,c,freq[c])
        for j in range(4):
            if (c-k[j])%A in T:edge(c,29+j,len(x))
    for j,n in enumerate(slots):edge(29+j,sink,n)
    flow=0
    while True:
        prev={source:-1};q=deque([source])
        while q and sink not in prev:
            a=q.popleft()
            for b,n in adj[a].items():
                if n>0 and b not in prev:q.append(b);prev[b]=a
        if sink not in prev:break
        path=[];b=sink
        while b!=source:path.append((prev[b],b));b=prev[b]
        n=min(adj[a][b] for a,b in path);flow+=n
        for a,b in path:adj[a][b]-=n;adj[b][a]+=n
    rows=[[] for _ in range(4)];un=[]
    for c in range(1,A):
        done=0
        for j in range(4):
            n=adj[29+j].get(c,0);rows[j].extend([c]*n);done+=n
        un.extend([c]*(freq[c]-done))
    for j,row in enumerate(rows):
        add=slots[j]-len(row);row.extend(un[:add]);del un[:add]
    assert not un
    z=[rows[i%4].pop() if c else 0 for i,c in enumerate(x)]
    assert Counter(z)==freq and [i for i,c in enumerate(x) if c==0]==[i for i,c in enumerate(z) if c==0]
    h=sum((c-k[i%4])%29 in T for i,c in enumerate(z))
    f=sum(c==0 and (-k[i%4])%29 in T for i,c in enumerate(x))
    assert h==flow+f
    return dict(key=k,count=h,fixed_F_contribution=f,nonF_flow=flow,layout_sha256=hashlib.sha256(bytes(z)).hexdigest())
def run(exe):
    P,_=solved();src={g:list(map(int,y)) for (g,s),(y,l) in sorted(P.items())};pool=sum(src.values(),[]);fr=Counter(pool);rank=sorted((v for v in fr if v),key=lambda v:(-fr[v],v))
    assert [LET[v] for v in rank[:6]]==list('EOASRT')
    targets={'E':rank[:1],'EO':rank[:2],'EOA':rank[:3],'EOASR':rank[:5],'EOAST':rank[:4]+[rank[5]]}
    g,w=geometry();coord=[i for i,t in enumerate(g) if t[1]==8];assert coord==list(range(coord[0],coord[-1]+1));x=[g[i][3] for i in coord];N=len(x)
    omit={i-coord[0] for a in w if (a['page'],a['page_rune_offset']) in {(40,101),(42,112),(46,7),(51,89)} for i in range(a['rune_offset'],a['rune_offset']+len(a['values']))};assert len(omit)==16
    y=(pool*(N//len(pool)+1))[:N];key=[3,9,14,22];hs=set([i for i,c in enumerate(y) if c==0][::2]);z=[];ph=0
    for i,v in enumerate(y):
        if i in hs:z.append(0)
        else:z.append((v+key[ph%4])%29);ph+=1
    assert clock(z,key,hs,29)==y
    tasks=[];meta=[]
    def task(A,x,u,T,name):
        tasks.append(' '.join(map(str,[A,len(x)]+x+u+[int(i in T) for i in range(A)])))
        meta.append((A,x,u,set(T),name))
    import random
    rng=random.Random(231330100)
    for j in range(18):
        A=[3,5][j%2];xx=[rng.randrange(A) for _ in range(10)];xx[j%10]=0;u=[rng.randint(0,1) for _ in xx];u[1]=1;T=[i for i in range(A) if rng.random()<.5]
        if not T:T=[1]
        task(A,xx,u,T,('fixture',str(j)))
    for tag,xx,u in [('section8',x,[1]*N),('without4',x,[int(i not in omit) for i in range(N)]),('planted',z,[1]*N)]:
        for label,T in targets.items():task(29,xx,u,T,(tag,label))
    raw=subprocess.run([exe],input='\n'.join(tasks)+'\n',text=True,check=True,stdout=subprocess.PIPE).stdout.splitlines();assert len(raw)==len(meta)
    dst={tag:{} for tag in ['section8','without4','planted']};fixtures=[]
    for line,(A,xx,u,T,(tag,label)) in zip(raw,meta):
        val,*k,orbits=map(int,line.split())
        if tag=='fixture':
            assert val==fixture(A,xx,u,T);fixtures.append(dict(A=A,x=xx,use=u,T=sorted(T),cap=val));continue
        win=witness(xx,k,u,T,A);assert win['cap']==val
        b=never(xx,u,T,A);assert b['cap']<=val
        records=dict(witness=win,never=b,key_orbits=orbits,n=sum(u))
        if tag=='planted':records['known']=sum(v in T for v in y);assert records['known']<=val
        dst[tag][label]=records
    cal={label:{g:[sum(v in T for v in yy),len(yy)] for g,yy in src.items()} for label,T in targets.items()}
    return dict(targets=targets,reference=cal,pooled_denominator=len(pool),pooled_counts={s:sum(fr[v] for v in T) for s,T in targets.items()},fixture_checks=fixtures,F_count=x.count(0),section_sha256=hashlib.sha256(bytes(x)).hexdigest(),omit=sorted(omit),planted=dict(cipher_sha256=hashlib.sha256(bytes(z)).hexdigest(),plain_sha256=hashlib.sha256(bytes(y)).hexdigest(),holds=sorted(hs),key=key,F_count=z.count(0)),records=dst,shuffles={label:inventory(x,T) for label,T in targets.items()})
if __name__=='__main__':
    with tempfile.TemporaryDirectory() as tmp:
        exe=str(Path(tmp)/'cap');subprocess.run([os.getenv('CXX','c++'),'-std=c++17','-O3',str(HERE/'mass_231_232.cpp'),'-o',exe],check=True)
        out=run(exe);Path(sys.argv[1]).write_bytes(gzip.compress(json.dumps(out,separators=(',',':')).encode(),mtime=0))
