"""Post-hoc diagnosis of the failed adjacent-double extension in manuscript section 8."""
import sys,itertools
from pathlib import Path
from transfer_314 import shape,solve
def run(d):
 sys.path.insert(0,str(d))
 from shortkey_303 import inp
 from lp_core import lp
 from lexical_words import tokenize_words
 rows,_,broad,letters=inp(d)
 ts={t:{(a,b) for w in broad if (z:=shape(w)) and z[0]==t for _,a,b in [z]} for t in ('ABA','AAB','ABB')}
 wr=[(w['page'],w['page_rune_offset'],tuple(w['values']),z) for w in tokenize_words('%'.join(lp[:56])) if w['section']==8 and len(w['values'])==3 and (z:=shape(w['values'])) is not None]
 cs=sorted({r[-1] for r in wr});assert len(cs)==9
 def go(sub):return solve([(True,*cs[i]) for i in sub],ts)
 # Enumerate all inclusion-minimal conflicting sets in increasing size, skipping supersets only by proven monotonicity.
 cores=[];fits={};inferred=0;checks=0
 for n in range(len(cs)+1):
  for ss in itertools.combinations(range(len(cs)),n):
   s=frozenset(ss)
   if any(c<=s for c in cores):inferred+=1;continue
   f=go(ss);checks+=1
   if f is None:
    assert all(s-{i} in fits for i in s);cores.append(s)
   else:fits[s]=f
 U=set(range(len(cs)));rem={}
 for j,w in enumerate(cs):rem[str(w)]={'feasible':frozenset(U-{j}) in fits,'witness':fits.get(frozenset(U-{j}))}
 assert len(fits)+len(cores)+inferred==2**len(cs)
 return dict(letters=letters,forms=cs,words=wr,cores=[dict(ids=sorted(c),deletion_witnesses={str(i):fits[c-{i}] for i in c}) for c in cores],subset_count=2**len(cs),fully_tested=checks,inferred_impossible=inferred,possible=len(fits),single_deletion=rem)
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]),run(d))
