"""python -B known_holdout_318_319.py EVIDENCE OUTPUT.json.gz — exact finite prediction sets; Python 3.10+."""
from pathlib import Path
from itertools import permutations,combinations,product
from collections import defaultdict,Counter
from statistics import median
import json, gzip,sys,random,hashlib,math

def attr(w):
 u=list(dict.fromkeys(w))
 return tuple(u.index(c) for c in w)
def extend(m,inv,c,p):
 m=m.copy();inv=inv.copy()
 for x,y in zip(c,p):
  if (x in m and m[x]!=y) or (y in inv and inv[y]!=x):return None
  m[x]=y;inv[y]=x
 return m,inv
def pred(anc,q,vocab,probes,exact=False):
 # Each candidate is tried as a pin. No unused symbol is fixed by a completed witness.
 rows=[(c,([pt] if exact else vocab.get(attr(c),()))) for c,pt in anc]
 rows=sorted(set((c,tuple(tuple(w) for w in options)) for c,options in rows),key=lambda r:(len(r[1]),r[0]))
 def ok(rows,m,iv):
  if not rows:return True
  i=min(range(len(rows)),key=lambda j:(-sum(x in m for x in set(rows[j][0])),len(rows[j][1]),j))
  c,pts=rows[i];rest=rows[:i]+rows[i+1:]
  for p in pts:
   a=extend(m,iv,c,p)
   if a and ok(rest,*a):return True
  return False
 def chk(w):
  pin=extend({},{},q,w)
  return pin is not None and ok(rows,*pin)
 return {w for w in probes if chk(w)},ok(rows,{},{})

def controls():
 # Independent brute force over all 4! alphabets, checking the entire prediction set.
 seed=random.Random(3301318);univ=list(product(range(4),repeat=3));abc={p for p in univ if len(set(p))==3}
 rep=[p for p in univ if len(set(p))==2];n=0
 for _ in range(100):
  anc=[(seed.choice(rep),seed.choice(univ)) for j in range(seed.randint(1,4))]
  v=defaultdict(list)
  for w in seed.sample(rep,seed.randint(2,18)):v[attr(w)].append(w)
  q=seed.choice(sorted(abc));mode=seed.randrange(2);expected=set();fit=False
  for f in permutations(range(4)):
   rd=lambda c:tuple(f[x] for x in c)
   if all((rd(c)==p if mode else rd(c) in v[attr(c)]) for c,p in anc):fit=True;expected.add(rd(q))
  assert pred(anc,q,v,abc,mode)==(expected,fit);n+=1
 return n
def window(rs):
 anchor=[i for i,(offset,c,p) in enumerate(rs) if len(c)==3 and len(set(c))==2]
 held=defaultdict(list);unused=[]
 for i in anchor:
  ix=next((j for j in range(i+1,len(rs)) if len(rs[j][1])==3 and len(set(rs[j][1]))==3),None)
  if ix is None:unused.append(rs[i][0])
  else:held[ix].append(i)
 motif=[]
 for i,j,k,l in combinations(anchor,4):
  a,e,b,w=(rs[n][1] for n in (i,j,k,l))
  if attr(a)==(0,1,0) and attr(e)==attr(w)==(0,0,1) and attr(b)==(0,1,1) and e[-1]==w[0] and a[1]==b[1]==w[-1] and len(set(a+e+b+w))==5:motif.append([rs[n][0] for n in (i,j,k,l)])
 return held,anchor,unused,motif
def calc(d):
 sys.path.insert(0,str(d))
 from lexicon_293 import inputs,gp,LET
 hist,_,_=inputs(d);source=json.loads((d/'mechanism_coverage_results.json').read_text())['known_method_groups']
 lower=json.loads(gzip.decompress((d/'lexical_309_forms.json.gz').read_bytes()))
 vocab={k:sorted({gp(w) for w in v['accepted_lower']}) for k,v in lower['shapes'].items()}
 train={attr(words[0]):words for k,words in vocab.items() if k in ('ABA','ABB','AAB')}
 abc=set(vocab['ABC']);tiny=controls();rng=random.Random(3310318)
 groups={g['name']:g['mechanism'] for g in source};allrecords=[];pairs=[]
 for name,meth in groups.items():
  f=rng.sample(range(29),29)
  truth=[(i,c,p) for g,i,c,p in hist if g==name]
  fixed=[(i,tuple(f[x] for x in p),p) for i,c,p in truth]
  by={}
  for mode,rs in [('planted_fixed',fixed),('authentic',truth)]:
   held,anchor,last,motif=window(rs);tr=[]
   for j,selectors in held.items():
    pos,q,gold=rs[j];anc=[(rs[i][1],rs[i][2]) for i in anchor if i<j]
    plus={k:list(v) for k,v in train.items()}
    for c,p in anc:
     if len(set(p))==2 and p not in plus[attr(p)]:plus[attr(p)].append(p)
    cell={}
    for tag,tab,exact in [('dictionary',train,False),('covered_anchors',plus,False),('given_anchor_plaintexts',train,True)]:
     ps,fit=pred(anc,q,tab,abc|{gold},exact)
     predictions=ps&abc
     cell[tag]=dict(compatible_anchor_map=fit,listed_options=len(predictions),gold_legal=gold in ps,gold_in_predictions=gold in predictions,options_sha256=hashlib.sha256(bytes(x for w in sorted(predictions) for x in w)).hexdigest())
    # Independent exact count without the output word list under known anchor plaintext.
    pin=({}, {})
    for c,p in anc:
     pin=extend(*pin,c,p) if pin is not None else None
    if pin is None:rawcount=0
    else:
     remaining=29-len(pin[0]);unknown=sum(x not in pin[0] for x in q)
     rawcount=math.perm(remaining,unknown)
    cell['given_anchor_plaintexts']['raw_options']=rawcount
    assert bool(rawcount)==cell['given_anchor_plaintexts']['compatible_anchor_map']
    assert rawcount>=cell['given_anchor_plaintexts']['listed_options']
    if mode=='planted_fixed':
     assert cell['given_anchor_plaintexts']['gold_legal'] and cell['covered_anchors']['gold_legal']
     assert cell['given_anchor_plaintexts']['listed_options']<=cell['covered_anchors']['listed_options']
    tr.append(dict(offset=pos,selector_offsets=[rs[i][0] for i in selectors],anchor_offsets=[rs[i][0] for i in anchor if i<j],training_gold_missing=sum(p not in train.get(attr(p),()) for c,p in anc),query=q,gold=gold,gold_listed_ABC=gold in abc,prediction=cell))
   allrecords.append(dict(group=name,mechanism=meth,mode=mode,anchor_offsets=[rs[i][0] for i in anchor],no_next=last,grid_motif=motif,targets=tr))
   by[mode]={row['offset']:row for row in tr}
  ai=set(by['authentic']);fi=set(by['planted_fixed'])
  if meth in ('identity','reflection_28','reflection_2'):
   assert ai==fi
   for i in fi:assert by['authentic'][i]['prediction']==by['planted_fixed'][i]['prediction']
  pairs.append(dict(group=name,historical_only=sorted(ai-fi),fixed_only=sorted(fi-ai),both=sorted(ai&fi)))
 return dict(baseline=len(abc),alphabet=LET,comparison=pairs,controls=tiny,groups=allrecords)
if __name__=='__main__':
 d=Path(sys.argv[1]).resolve();sys.path.insert(0,str(d));from shortkey_303 import save
 save(Path(sys.argv[2]),calc(d))
