"""python -B immediate_324.py EVIDENCE OUT [--source en_US.dic en_US.aff]
The optional step rebuilds the compact slice; the primary replay uses only notebook files.
"""
from pathlib import Path
import itertools,gzip,json,sys,re,hashlib
from collections import defaultdict,Counter
def unpack(p):return json.loads(gzip.decompress(p.read_bytes()))
def save(p,x):p.write_bytes(gzip.compress((json.dumps(x,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
def sm(v):return sum(1<<i for i in set(v))
def fit(t,x,p):
 f={**p,**dict(zip(t,x))}
 if len(set(f.values()))!=len(f) or any(f[a]!=b for a,b in p.items()) or any(f[a]!=b for a,b in zip(t,x)):return None
 return f
def frozen(d):
 from lexical_words import tokenize_words
 from lp_core import lp
 from lexicon_293 import LET
 ws=[(w['page_rune_offset'],tuple(w['values'])) for w in tokenize_words('%'.join(lp[:56])) if w['page']==51]
 assert ws[0][0]==0 and ws[0][1]==(7,7,13)
 k=next(i for i,(_,v) in enumerate(ws[1:],1) if len(v)==len(set(v))==3)
 z=unpack(d/'chain_314_results.json.gz')['variants']['lower']['solutions']
 return ws[1:k],ws[k],[(s['readings_JPJ_EEW_BPP_WWP'][-1][0],dict(zip(map(LET.index,['E','W','P','J','B']),s['mapping_EWPJB']))) for s in z]
def make(dic,aff,d,ws,ps):
 from lexicon_293 import gp,sig
 import ctypes,ctypes.util
 dh,ah=[hashlib.sha256(f.read_bytes()).hexdigest() for f in (dic,aff)]
 assert (dh,ah)==('829a043cf078d1e80e886289a13823454977f442a239a859d2133ea61944aa60','70fe5778717d097ce2f3326baaa5c1e4d2206d81a5a81d3ea8e11c4770806dd5')
 cross={};rules=defaultdict(list)
 for l in aff.read_text().splitlines():
  a=l.split()
  if len(a)==4 and a[0] in ('PFX','SFX'):cross[a[0],a[1]]=(a[2]=='Y')
  if len(a)==5 and a[0] in ('PFX','SFX'):
   kind,flag,strip,add,cond=a
   rules[flag].append((kind,'' if strip=='0' else strip,'' if add=='0' else add,re.compile(('^'+cond) if kind=='PFX' else (cond+'$'))))
 def apply(w,r):
  k,s,a,c=r
  if not c.search(w):return
  if k=='PFX' and w.startswith(s):return a+w[len(s):]
  if k=='SFX' and w.endswith(s):return (w[:-len(s)] if s else w)+a
 h=ctypes.CDLL(ctypes.util.find_library('hunspell-1.7'))
 h.Hunspell_create.argtypes=[ctypes.c_char_p]*2;h.Hunspell_create.restype=ctypes.c_void_p
 h.Hunspell_spell.argtypes=[ctypes.c_void_p,ctypes.c_char_p];h.Hunspell_spell.restype=ctypes.c_int
 h.Hunspell_destroy.argtypes=[ctypes.c_void_p];handle=h.Hunspell_create(bytes(aff),bytes(dic));assert handle
 heads=set();expanded=set()
 for row in dic.read_text().splitlines()[1:]:
  w,_,flags=row.partition('/')
  if not re.fullmatch('[a-z]+',w) or 'c' in flags:continue
  heads.add(w);expanded.add(w)
  suf=[];pre=[]
  for flag in flags:
   for rule in rules.get(flag,[]):
    rw=apply(w,rule)
    if rw:
     expanded.add(rw)
     if cross[rule[0],flag]:
      (pre if rule[0]=='PFX' else suf).append(rule)
  for l,r in itertools.product(pre,suf):
   a=apply(w,l)
   if a:
    b=apply(a,r)
    if b:expanded.add(b)
 expanded={w for w in expanded if re.fullmatch('[a-z]+',w) and h.Hunspell_spell(handle,w.encode())}
 h.Hunspell_destroy(handle);assert heads<=expanded
 ss=[sig(t) for _,t in ws];assert len(set(ss))==len(ss);counts=defaultdict(Counter);keep={}
 for w in sorted(expanded):
  q=gp(w);s=sig(q)
  if s not in ss:continue
  i=ss.index(s);counts['expanded'][s]+=1
  if w in heads:counts['head'][s]+=1
  if any(fit(ws[i][1],q,p) for _,p in ps):keep[w]=int(w in heads)
 probe=ws[0][1];qws=[(w,gp(w)) for w in sorted(expanded) if len(w)<=3*len(probe) and sig(gp(w))==sig(probe)]
 failed=[]
 for arm,p in ps:
  if any(fit(probe,q,p) for w,q in qws):continue
  tests=[]
  for i in p:
   m={k:v for k,v in p.items() if k!=i};aa=[w for w,q in qws if fit(probe,q,m)];tests.append([i,len(aa),aa[:2]])
  failed.append(dict(arm=arm,key=sorted(p.items()),release_one=tests))
 return dict(failing_first_ablation=failed,hashes=[dh,ah],words_sorted=keep,matching_shape_spellings=counts,root_count=len(heads),expanded_count=len(expanded),rule='lowercase ASCII roots; at most one applicable prefix and one suffix with compatible flags; verify generated lowercase spelling through Hunspell; not a reference to every possible English word.')
def compute(d,data,ws,target,ps):
 from lexicon_293 import gp,LET,sig
 abc=set(map(gp,unpack(d/'lexical_309_forms.json.gz')['shapes']['ABC']['accepted_lower']))
 c=[v for _,v in ws];t=target[1]
 assert len(c)==3 and set(c[0])&set(c[1])=={c[0][-1]} and not (set(c[2])&(set(c[1])|set(c[0]))) and t==(c[0][4],c[0][1],c[2][2])
 out={}
 for mode in ('head','expanded'):
  opts=sorted({gp(w) for w,h in data['words_sorted'].items() if mode=='expanded' or h})
  tab=defaultdict(list)
  for q in opts:tab[sig(q)].append(q)
  records=[]
  for arm,p in ps:
   seq=[]
   for i,u in enumerate(c):
    a=[]
    for q in tab[sig(u)]:
     f=fit(u,q,p)
     if f is not None:a.append((q,sm(f[n] for n in set(u)-set(p))))
    seq.append(a)
   base=p.values();common=c[0][-1];j=c[1].index(common)
   # Two bridge words overlap once (N). The third is disjoint outside the preassigned letters.
   veto=[0]*29;tails=defaultdict(int)
   for ix,(q,m) in enumerate(seq[2]):
    for h in range(29):
     if m>>h&1:veto[h]|=1<<ix
    tails[q[2]]|=1<<ix
   possible=set();joint=pair=listedJoint=0;wit=None;cc=Counter()
   for x,m in seq[0]:
    for y,n in seq[1]:
     if x[-1]!=y[j] or m&n != 1<<x[-1]:continue
     pair+=1;z=m|n;good=(1<<len(seq[2]))-1
     while z and good:
      bit=z&-z;good&=~veto[bit.bit_length()-1];z-=bit
     if not good:continue
     joint+=good.bit_count()
     for k,tail in tails.items():
      if not (hit:=good&tail):continue
      pt=(x[4],x[1],k);possible.add(pt)
      if pt not in abc:continue
      listedJoint+=hit.bit_count();cc[pt]+=hit.bit_count()
      if wit is None:
       y3=seq[2][(hit&-hit).bit_length()-1][0];f=dict(p)
       for w,q in zip(c,[x,y,y3]):f=fit(w,q,f);assert f is not None
       assert tuple(f[a] for a in t)==pt;wit=dict(bridge_forms=[x,y,y3],holdout=pt,active_map=sorted(f.items()))
   if len(seq[0])*len(seq[1])*len(seq[2])<=175000:
    # Direct Cartesian replay for small cells, no bit masks.
    possibilities=set();nn=0
    for (x,_),(y,_),(z,_) in itertools.product(*seq):
     f=fit(c[1],y,fit(c[0],x,p))
     if f is None:continue
     f=fit(c[2],z,f)
     if f is not None:nn+=1;possibilities.add(tuple(f[a] for a in t))
    assert nn==joint and possibilities==possible
   records.append(dict(arm=arm,pins=sorted(p.items()),alone=[len(v) for v in seq],pairs=pair,joint=joint,joint_also_listed_next=listedJoint,possible=sorted(possible),listed=sorted(cc),witness=wit))
  out[mode]=records
 return dict(bridge=ws,holdout=target,alphabet=LET,cases=out)
if __name__=='__main__':
 d=Path(sys.argv[1]).resolve();o=Path(sys.argv[2]);o.mkdir(exist_ok=True);sys.path.insert(0,str(d))
 ws,t,ps=frozen(d);f='immediate_324_slice.json.gz'
 if len(sys.argv)>3:
  assert sys.argv[3]=='--source'
  from lp_core import lp
  from lexical_words import tokenize_words
  ext=next(w for w in tokenize_words('%'.join(lp[:56])) if w['page']==51 and w['page_rune_offset']==22)
  data=make(Path(sys.argv[4]),Path(sys.argv[5]),d,ws+[(22,tuple(ext['values']))],ps);save(o/f,data)
 else:data=unpack(d/f)
 save(o/'immediate_324_results.json.gz',compute(d,data,ws,t,ps))
