"""python -B lexical_309.py EVIDENCE OUTPUT [--source DIC AFF]
Rebuild optional slice with Hunspell 1.7 and the pinned en_US source files.
"""
from pathlib import Path
import re, itertools, sys, json, gzip, hashlib, ctypes
from collections import defaultdict
def pack(p,d):
 p.write_bytes(gzip.compress((json.dumps(d,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
def load(p):return json.loads(gzip.decompress(p.read_bytes()))
def hs(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def prepare(dic,aff,gp,letters,side):
 assert hs(dic)=='829a043cf078d1e80e886289a13823454977f442a239a859d2133ea61944aa60'
 assert hs(aff)=='70fe5778717d097ce2f3326baaa5c1e4d2206d81a5a81d3ea8e11c4770806dd5'
 import ctypes.util
 lib=ctypes.CDLL(ctypes.util.find_library('hunspell-1.7'))
 p=ctypes.c_void_p;b=ctypes.c_char_p;i=ctypes.c_int
 lib.Hunspell_create.argtypes=[b,b];lib.Hunspell_create.restype=p
 lib.Hunspell_destroy.argtypes=[p];lib.Hunspell_destroy.restype=None
 lib.Hunspell_spell.argtypes=[p,b];lib.Hunspell_spell.restype=i
 h=lib.Hunspell_create(bytes(aff),bytes(dic));assert h
 alt=dict(u='uv',k='kcq',s='sz')
 def spells(a):
  return [''.join(x) for x in itertools.product(*(alt.get(c,c) for c in a.lower()))]
 alphabet=[spells(a) for a in letters]
 patterns=('ABA','AAB','ABB','AAA','ABC')
 # Enumerate all 29^3 rune forms, their possible ASCII preimages, then re-tokenize.
 # A greedy ligature at a rune boundary can invalidate a concatenation.
 cs={k:set() for k in patterns}
 def shape(i,j,k):
  return 'AAA' if i==j==k else 'AAB' if i==j else 'ABB' if j==k else 'ABA' if i==k else 'ABC'
 for i,j,k in itertools.product(range(29),repeat=3):
  cand=cs[shape(i,j,k)]
  for q in itertools.product(alphabet[i],alphabet[j],alphabet[k]):
   w=''.join(q)
   if gp(w)==(i,j,k):cand.add(w)
 tab={z:{'candidate_count':len(cs[z]),'accepted_lower':sorted(w for w in cs[z] if lib.Hunspell_spell(h,w.encode())),'headwords':{c:[] for c in ('base','title','caps','mixed')}} for z in patterns}
 lib.Hunspell_destroy(h)
 for row in dic.read_text().splitlines()[1:]:
  s,_,ff=row.partition('/')
  if not s.isascii() or not s.isalpha() or 'c' in ff:continue
  seq=gp(s)
  if len(seq)!=3:continue
  z=shape(*seq);assert s.lower() in cs[z]
  c='base' if s.islower() else 'caps' if s.isupper() else 'title' if s.istitle() else 'mixed'
  tab[z]['headwords'][c].append(s)
 for z in patterns:
  tab[z]['headwords']={c:sorted(set(ws)) for c,ws in tab[z]['headwords'].items()}
 pack(side,dict(dic_sha256=hs(dic),aff_sha256=hs(aff),shapes=tab))
 cand=cs['ABA'];lower=set(tab['ABA']['accepted_lower']);classes=tab['ABA']['headwords']
 af=[x.split() for x in aff.read_text().splitlines() if x.startswith(('SFX','PFX')) and len(x.split())>=5]
 # Explain each additional spelling by one explicit lower-case stem + flag + rule.
 added=lower-set(classes['base']);der=defaultdict(set)
 for line in dic.read_text().splitlines()[1:]:
  s,_,ff=line.partition('/')
  if not re.fullmatch('[a-z]+',s) or len(s)>10 or 'c' in ff:continue
  for kind,flag,strip,add,cond,*_ in af:
   if flag not in ff:continue
   sub='' if strip=='0' else strip
   if kind=='PFX' and s.startswith(sub) and re.match(cond,s):w=add+s[len(sub):]
   elif kind=='SFX' and s.endswith(sub) and re.search(cond+'$',s):w=s[:len(s)-len(sub)]+add
   else:continue
   if w in added:der[w].add((s,kind,flag,strip,add,cond))
 return dict(dic_sha256=hs(dic),aff_sha256=hs(aff),candidates=len(cand),accepted_lower=sorted(lower),headwords={c:sorted(set(v)) for c,v in classes.items()},additional_derivations={k:sorted(v) for k,v in der.items()})
def edge(w,gp):
 p=gp(w);assert len(p)==3 and p[0]==p[2]!=p[1];return tuple(p[:2])
def runs(groups,t,test):
 sec=sorted(groups);data={}
 for i,s in enumerate(sec):
  e=set()
  for j in range(i,len(sec)):
   e|=groups[sec[j]];z=test(e,t)
   assert z['status']!='undecided'
   data[i,j+1]=z
 for n in range(1,len(sec)+1):
  ans=[]
  for cuts in itertools.combinations(range(1,len(sec)),n-1):
   ix=(0,)+cuts+(len(sec),)
   if all(data[l,r]['status']=='yes' for l,r in zip(ix,ix[1:])):
    ans.append([[sec[l],sec[r-1]] for l,r in zip(ix,ix[1:])])
  if ans:break
 return dict(edges=len(t),min_partitions=ans,pooled=data[0,len(sec)],interval_status={f'{sec[i]}-{sec[j-1]}':z['status'] for (i,j),z in data.items()})
def get(d):
 sys.path.insert(0,str(d));from graph_304 import test;from shortkey_303 import inp;from lexicon_293 import gp
 rows,_,v,letters=inp(d);groups=defaultdict(set)
 for s,p,o,w in rows:groups[s].add(tuple(w[:2]))
 target={tuple(w[:2]) for w in v if w[0]==w[2]!=w[1]}
 return gp,letters,groups,target,test
def main():
 d=Path(sys.argv[1]).resolve();out=Path(sys.argv[2]);out.mkdir(exist_ok=True);gp,L,G,T,test=get(d)
 sn='lexical_309_slice.json.gz'
 if len(sys.argv)>3:
  assert sys.argv[3]=='--source';sl=prepare(Path(sys.argv[4]),Path(sys.argv[5]),gp,L,out/'lexical_309_forms.json.gz');pack(out/sn,sl)
 else:sl=load(d/sn)
 F=lambda xs:{edge(w,gp) for w in xs}
 heads=sl['headwords'];assert F(heads['base'])==T;lo=F(sl['accepted_lower']);assert T<=lo
 title=F(heads['title']);caps=F(heads['caps']);mixed=F(heads['mixed'])
 refs=dict(base=T,spell_lower=lo,lower_plus_title=lo|title,lower_plus_caps=lo|caps,lower_plus_all=lo|title|caps|mixed)
 z={k:runs(G,t,test) for k,t in refs.items()}
 extra={k:sorted(t-T) for k,t in refs.items()}
 pack(out/'lexical_309_results.json.gz',dict(variants=z,added_over_base=extra))
if __name__=='__main__':main()
