"""Offline paired section controls; python -B plant_305_308.py EVIDENCE OUT.json.gz [N=120].
Results include the individual planted boundaries, omissions and ALL tied minimum partitions.
"""
import collections, gzip, hashlib, itertools, json, random, sys
from pathlib import Path
SEED=3310305; BUDGET=100000; SECTIONS=(1,2,4,5,6,7,8)
def mask(vs):
    return sum(1<<v for v in set(vs))
def members(m):
    while m:
        bit=m&-m
        yield bit.bit_length()-1
        m^=bit
def graph(edges):
    out=[0]*29; inc=[0]*29
    for a,b in edges:
        out[a]|=1<<b; inc[b]|=1<<a
    nodes=[v for v in range(29) if out[v]|inc[v]]
    sig={v:tuple(m.bit_count() for m in (out[v],inc[v],out[v]&inc[v],out[v]|inc[v])) for v in nodes}
    return out,inc,nodes,sig
def sat_embed(es,gt):
    """Exact optional Z3 check: one Boolean per allowed source/target pair."""
    import ctypes as c,ctypes.util
    lib=c.CDLL(ctypes.util.find_library('z3') or 'libz3.so.4')
    F=lambda nm,rt,*a:configure(getattr(lib,nm),rt,a)
    def configure(f,r,a):
        f.argtypes=a;f.restype=r;return f
    P=c.c_void_p;S=c.c_char_p
    cfg=F('Z3_mk_config',P)();ctx=F('Z3_mk_context',P,P)(cfg)
    query=F('Z3_eval_smtlib2_string',S,P,S)
    try:
        so,si,vs,ss=graph(es);to,ti,ts,st=gt
        D={v:[x for x in ts if all(a<=b for a,b in zip(ss[v],st[x]))] for v in vs}
        def lit(v,x):return 'q%d_%d'%(v,x)
        qq=['(set-option :timeout 15000)']
        for v in vs:
            for x in D[v]:qq.append('(declare-const %s Bool)'%lit(v,x))
        def atleast(choices):return '(or '+' '.join(choices)+')' if choices else 'false'
        def add(cl):qq.append('(assert '+cl+')')
        def atmost(ls):
            if len(ls)>1:add('((_ at-most 1) '+' '.join(ls)+')')
        for v in vs:
            ls=[lit(v,x) for x in D[v]];add(atleast(ls));atmost(ls)
        for x in ts:atmost([lit(v,x) for v in vs if x in D[v]])
        for a,b in es:
            for x in D[a]:
                add('(=> %s %s)'%(lit(a,x),atleast([lit(b,y) for y in D[b] if (to[x]>>y)&1])))
            for y in D[b]:
                add('(=> %s %s)'%(lit(b,y),atleast([lit(a,x) for x in D[a] if (to[x]>>y)&1])))
        rep=query(ctx,('\n'.join(qq)+'\n(check-sat)').encode()).decode().strip()
        if rep=='unsat':return False
        if rep=='unknown':return None
        assert rep=='sat',rep
        import re
        syms=[lit(v,x) for v in vs for x in D[v]]
        vals=query(ctx,('(get-value ('+' '.join(syms)+'))').encode()).decode()
        pairs=[(int(v),int(x)) for v,x in re.findall(r'\(q(\d+)_(\d+) true\)',vals)]
        f=dict(pairs)
        assert len(pairs)==len(f)==len(vs)==len(set(f.values())) and all((to[f[a]]>>f[b])&1 for a,b in es)
        return True
    finally:
        F('Z3_del_context',None,P)(ctx);F('Z3_del_config',None,P)(cfg)

SATCOUNTS=collections.Counter()
def embed(es,gt,strict=False):
    so,si,vs,ss=graph(es); to,ti,ts,st=gt
    D=[0]*29
    for v in vs:
        a=ss[v]; D[v]=mask(x for x,b in st.items() if all(i<=j for i,j in zip(a,b)))
    arcs=[(v,w,(2 if (si[v]>>w)&1 else 0)+(1 if (so[v]>>w)&1 else 0)) for v in vs for w in members(so[v]|si[v])]
    support=[None,to,ti,[a&b for a,b in zip(to,ti)]]
    nodes=0
    prior=[(u,v) for u in vs for v in vs if u<v and so[u]==so[v] and si[u]==si[v]]
    seen=set()
    def local_ok(v,x,d):
        neigh=so[v]|si[v]; choices=[]
        for w in members(neigh):
            label=(2 if si[v]>>w&1 else 0)+(1 if so[v]>>w&1 else 0)
            q=d[w]&support[label][x]
            if not q:return False
            choices.append(q)
        choices.sort(key=int.bit_count);match={}
        def aug(j,seen):
            for y in members(choices[j]):
                if y in seen:continue
                seen.add(y)
                if y not in match or aug(match[y],seen):match[y]=j;return True
            return False
        return all(aug(j,set()) for j in range(len(choices)))
    def go(d):
        nonlocal nodes
        nodes+=1
        if nodes>(BUDGET if strict else 1000):raise TimeoutError
        while True:
            if any(not d[v] for v in vs):return False
            fixed=0
            for v in vs:
                m=d[v]
                if not m&(m-1):
                    if fixed&m:return False
                    fixed|=m
            dirty=False
            for v in vs:
                m=d[v]
                if m&(m-1) and m&fixed:d[v]&=~fixed;dirty=True
            for v,w,di in arcs:
                old=d[v]; mw=d[w];sp=support[di]
                # Enumerate from smaller endpoint; reverse arcs swap incoming/outgoing.
                if old.bit_count()<mw.bit_count():
                    new=mask(x for x in members(old) if sp[x]&mw)
                else:
                    new=0
                    sr=support[{1:2,2:1,3:3}[di]]
                    for y in members(mw):new|=sr[y]
                    new&=old
                if not new:return False
                if old!=new:d[v]=new;dirty=True
            if strict:
                # Identical source neighborhoods are exchangeable: select increasing images.
                for u,v in prior:
                    mu,mv=d[u],d[v]
                    if not mu or not mv:return False
                    d[u]&=(1<<(mv.bit_length()-1))-1
                    d[v]&=~((mu&-mu)*2-1)
                    dirty|=mu!=d[u] or mv!=d[v]
                # Each candidate must accommodate all distinct neighbors simultaneously.
                for v in vs:
                    if (so[v]|si[v]).bit_count()<2:continue
                    old=d[v];d[v]=mask(x for x in members(old) if local_ok(v,x,d))
                    if not d[v]:return False
                    dirty|=old!=d[v]
            if not dirty:break
        todo=sorted((v for v in vs if d[v]&(d[v]-1)),key=lambda v:(d[v].bit_count(),-ss[v][-1],v))
        if not todo:
            mapping={v:d[v].bit_length()-1 for v in vs}
            assert len(set(mapping.values()))==len(vs) and all(to[mapping[a]]>>mapping[b]&1 for a,b in es)
            return True
        if strict:
            # All constraints from fixed vertices have flowed into remaining domains.
            state=tuple((v,d[v]) for v in todo)
            if state in seen:return False
            seen.add(state)
        match={}
        def aug(v,vis):
            for x in members(d[v]):
                if x in vis:continue
                vis.add(x)
                if x not in match or aug(match[x],vis):
                    match[x]=v;return True
            return False
        if any(not aug(v,set()) for v in todo):return False
        v=todo[0]
        orbits=set()
        for x in members(d[v]):
            if strict:
                # Only skip actual graph twins with identical membership in every domain.
                sig=(to[x],ti[x],tuple(bool(d[w]&(1<<x)) for w in todo))
                # Source-order restrictions break general target-label symmetry: avoid target pruning when present.
                if not prior and sig in orbits:continue
                orbits.add(sig)
            q=d[:];q[v]=1<<x
            if go(q):return True
        return False
    try: ans=go(D)
    except TimeoutError:
        if not strict:
            v=sat_embed(es,gt); SATCOUNTS[str(v)]+=1
            if v is not None:return v,nodes
            v,extra=embed(es,gt,True)
            return v,nodes+extra
        ans=None
    return ans,nodes
def get(d):
    sys.path.insert(0,str(d))
    from shortkey_303 import inp
    rows,_,broad,_=inp(d)
    lex=sorted({(w[0],w[1]) for w in broad if w[0]==w[2]!=w[1]})
    types=sorted(set(row[-1] for row in rows))
    groups=[[types.index(w) for s,p,o,w in rows if s==sec] for sec in SECTIONS]
    assert len(lex)==51 and len(types)==30 and list(map(len,groups))==[4,1,4,4,6,7,6]
    return lex,groups
def pack(gs,target,cache,perf,one=False):
    gt=graph(target); tkey=tuple(sorted(target))
    def ask(lo,hi):
        source=tuple(sorted(set(e for g in gs[lo:hi] for e in g)))
        key=(source,tkey)
        if key not in cache:
            v,n=embed(source,gt)
            perf['solves']+=1;perf['nodes']+=n;perf['max_nodes']=max(perf['max_nodes'],n)
            if v is None:perf['undecided']+=1
            cache[key]=v
        return cache[key]
    whole=ask(0,7)
    if whole:return [0]
    if one: return [] if whole is False else None
    # Never silently convert an exhausted search into 'no'.
    pieces={}
    def fit(a,b):
        if (a,b) not in pieces:pieces[a,b]=ask(a,b)
        return pieces[a,b]
    for k in range(1,7):
        yes=[];unknown=False
        for cuts in itertools.combinations(range(1,7),k):
            positions=(0,)+cuts+(7,)
            statuses=[fit(a,b) for a,b in zip(positions,positions[1:])]
            if all(v is True for v in statuses):yes.append(sum(1<<(c-1) for c in cuts))
            elif False not in statuses:unknown=True
        if whole is None or unknown:return None
        if yes:return yes
    return []
def cnt(xs):return dict(sorted(collections.Counter(xs).items()))
def summary(cases):
    dom=sorted(cases[0]['fit'])
    out={}
    for tag in dom:
        allres=[c['fit'][tag] for c in cases]
        ks=[None if r is None else (r[0].bit_count()+1 if r else 8) for r in allres]
        out[tag]={'minimum_runs_hist':cnt('undecided' if k is None else ('no_partition' if k==8 else str(k)) for k in ks),'pooled_rejected':sum(x is not None and x!=1 for x in ks),'pooled_yes':ks.count(1),'pooled_no_but_each_section_yes':sum(k is not None and 2<=k<=7 for k in ks),'three_or_more_but_each_section_yes':sum(k is not None and 3<=k<=7 for k in ks),'tied_minima':sum(r is not None and len(r)>1 for r in allres)}
        if tag in ['k2','k3']:
            truths=[c['cutmasks'][int(tag[1])-2] for c in cases]
            nk=int(tag[1]);hit=sum(r is not None and truth in r for r,truth in zip(allres,truths))
            out[tag].update(planted_partition_in_minima=hit,unique_correct=sum(r==[truth] for r,truth in zip(allres,truths)),correct_count_only=ks.count(nk),wrongly_unique=sum(r is not None and len(r)==1 and r!=[truth] for r,truth in zip(allres,truths)),median_tie_count_if_right_size=sorted(len(r) for r,k in zip(allres,ks) if k==nk)[ks.count(nk)//2] if nk in ks else None)
    return out
def main(d,n):
    lex,tmpl=get(d); rng=random.Random(SEED); split=list(range(1,7));pairs=list(itertools.combinations(split,2));cases=[]
    # Schedule balanced blocks independently of words and key labels; no random stopping.
    s2=[];s3=[]
    while len(s2)<n:rng.shuffle(split);s2+=split[:]
    while len(s3)<n:rng.shuffle(pairs);s3+=pairs[:]
    perf=collections.Counter(); crossaudit=0
    from graph_304 import test as original
    # Exhaustive edge masks on 3 symbols vs independent permutation enumeration.
    tiny=[(a,b) for a in range(3) for b in range(3) if a!=b]; small=0
    for j in range(64):
        E=[e for k,e in enumerate(tiny) if j>>k&1]
        for l in range(64):
            T={e for k,e in enumerate(tiny) if l>>k&1}
            exp=any(all((p[a],p[b]) in T for a,b in E) for p in itertools.permutations(range(3)))
            assert embed(E,graph(T))[0] is exp and embed(E,graph(T),True)[0] is exp
            small+=1
    for rep in range(n):
        drawn=rng.sample(lex,30);used=rng.sample(drawn,6);unused=rng.sample(sorted(set(lex)-set(drawn)),6)
        keys=[rng.sample(range(29),29) for j in range(3)]
        assert len({tuple(key) for key in keys})==3
        cuts2=(s2[rep],); cuts3=s3[rep];cache={}
        def panel(cuts):
            gs=[]
            for j,section in enumerate(tmpl):
                key=keys[sum(j>=c for c in cuts)]
                gs.append([(key[drawn[i][0]],key[drawn[i][1]]) for i in section])
            return gs
        gs=panel(())
        fit={'k1':pack(gs,lex,cache,perf),'k2':pack(panel(cuts2),lex,cache,perf),'k3':pack(panel(cuts3),lex,cache,perf)}
        assert fit['k1']==[0]
        for i,(tag,cuts) in enumerate([('k2',cuts2),('k3',cuts3)]):
            ms=fit[tag]; truth=sum(1<<(c-1) for c in cuts)
            assert ms is None or (ms and (ms[0].bit_count()<len(cuts) or truth in ms))
        if rep<4:
            # Compare with Session 304's distinct set-based solver on nontrivial subpanels.
            for gg,loss in [(gs,[]),(gs,used[:3]),(panel(cuts2),[]),(panel(cuts3),[])]:
                t=set(lex)-set(loss)
                for a,b in [(0,7),(1,6),(0,4)]:
                    e=set(x for group in gg[a:b] for x in group)
                    old=original(e,t,budget=BUDGET)['status']
                    v,_=embed(e,graph(t))
                    assert old in ('yes','no') and (old=='yes') is v and embed(e,graph(t),True)[0] is v and sat_embed(e,graph(t)) is v
                    crossaudit+=1
        for k in (1,3,6):
            for prefix,drop in [('used',used),('unused',unused)]:
                tag=prefix+str(k)
                fit[tag]=pack(gs,set(lex)-set(drop[:k]),cache,perf)
                if prefix=='unused':assert fit[tag]==[0]
        cases.append({'rep':rep,'drawn':[lex.index(x) for x in drawn],'used':[lex.index(x) for x in used],'unused':[lex.index(x) for x in unused],'cutmasks':[sum(1<<(c-1) for c in cuts) for cuts in (cuts2,cuts3)],'fit':fit})
    hist=summary(cases)
    return dict(seed=SEED,N=n,quick_budget=1000,z3_timeout_ms=15000,enhanced_budget=BUDGET,sat_solves=dict(SATCOUNTS),solver_counts=dict(perf),tiny=small,original_solver_crosschecks=crossaudit,sections=SECTIONS,edge_order=lex,template=tmpl,cut_encoding='bit i = break after sections[i]. [0] = single run; [] = no partition; null = undecided.',cases=cases,summary=hist)
if __name__=='__main__':
    z=main(Path(sys.argv[1]).resolve(),int(sys.argv[3]) if len(sys.argv)>3 else 120)
    Path(sys.argv[2]).write_bytes(gzip.compress((json.dumps(z,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
    print(json.dumps({k:z[k] for k in ['N','solver_counts','summary']},sort_keys=True))
