"""python -B lexicon_293.py EVIDENCE OUT_DIR [original_en_US.dic]
No 3rd-party language models. Optional last argument rebuilds published slice.
"""
import re,json,hashlib,gzip,sys,collections
from pathlib import Path
LET='F U TH O R K G W H N I J EO P X S T B E M L ING OE D A AE Y IO EA'.split()
MULTI=('ING','TH','EO','OE','AE','IO','EA')
def gp(w):
 s=w.upper().translate(str.maketrans(dict(V='U',C='K',Q='K',Z='S')));r=[]
 while s:
  a=next((x for x in MULTI if s.startswith(x)),s[0]);r.append(LET.index(a));s=s[len(a):]
 return tuple(r)
def sig(w):
 d={};return '.'.join(str(d.setdefault(x,len(d))) for x in w)
def pack(p,x):p.write_bytes(gzip.compress((json.dumps(x,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
def inputs(d):
 sys.path.insert(0,str(d));from lp_core import pages,lp;from lexical_words import tokenize_words
 gr=json.loads((d/'mechanism_coverage_results.json').read_text())['known_method_groups']
 gs={g['name']:g['values'] for g in json.loads((d/'increment_calibration_sources.json').read_text())['groups']}
 raw=(d/'liber-primus__transcription--master.txt').read_bytes()
 assert hashlib.sha256(raw).hexdigest()=='b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
 hist=[]
 for g in gr:
  pp=gs[g['name']];assert hashlib.sha256(bytes(pp)).hexdigest()==g['plaintext_rune_values_sha256']
  words=tokenize_words('%'.join(pages[i] for i in g['parsed_page_indices']));p=0
  for w in words:
   ct=tuple(w['values']);pt=tuple(pp[p:p+len(ct)]);hist.append((g['name'],p,ct,pt));p+=len(ct)
  assert p==len(pp)
 sec=[w for w in tokenize_words('%'.join(lp[:56])) if w['section']==8]; origin=sec[0]['rune_offset']
 flank=[tuple(w['values']) for w in sec if 2336<=w['rune_offset']-origin<2644]
 assert len(hist)==739 and len(flank)==73 and sum(map(len,flank))==308 and flank[33]==(7,7,13)
 return hist,flank,sec
def prepare(raw,need):
 assert hashlib.sha256(raw).hexdigest()=='829a043cf078d1e80e886289a13823454977f442a239a859d2133ea61944aa60'
 lines=raw.decode().splitlines();assert int(lines[0])==len(lines)-1
 heads=set()
 for line in lines[1:]:
  w,_,flags=line.partition('/')
  if re.fullmatch(r'[a-z]+',w) and 'c' not in flags:heads.add(w)
 three=[];counts={s:0 for s in need};wit={s:[] for s in need}
 for w in sorted(heads):
  seq=gp(w);s=sig(seq)
  if len(seq)==3:three.append(w)
  if s in counts:
   counts[s]+=1
   if len(wit[s])<3:wit[s].append(w)
 return dict(raw_sha256=hashlib.sha256(raw).hexdigest(),input_lines=len(lines)-1,heads=len(heads),length3=three,tested_shape_base_headword_counts=counts,tested_shape_examples=wit)
def main(d,out,src=None):
 out.mkdir(exist_ok=True);hist,flank,_=inputs(d)
 wanted={sig(w) for w in flank};name='lexicon_293_slice.json.gz'
 if src:
  sliced=prepare(src.read_bytes(),wanted);pack(out/name,sliced)
 else:sliced=json.loads(gzip.decompress((d/name).read_bytes()))
 assert set(sliced['tested_shape_base_headword_counts'])==wanted
 ix=collections.defaultdict(list)
 for w in sliced['length3']:
  c=gp(w);assert len(c)==3;ix[c].append(w)
 hh={p for g,j,c,p in hist if len(p)==3};hhsh={sig(p) for g,j,c,p in hist}
 aff=[];c=(7,7,13)
 for a in range(1,29):
  for b in range(29):
   p=tuple((a*v+b)%29 for v in c)
   if p in ix:aff.append(dict(a=a,b=b,plain=p,spellings=ix[p]))
 aab={p for p in ix if p[0]==p[1]!=p[2]};assert len(aff)==len(aab) and {tuple(x['plain']) for x in aff}==aab
 obs=[]
 for j,w in enumerate(flank):
  s=sig(w)
  obs.append(dict(index=j,length=len(w),shape=s,seen_solved=s in hhsh,base_words=sliced['tested_shape_base_headword_counts'][s],examples=sliced['tested_shape_examples'][s]))
 rhs=flank[43]; entries=sliced['tested_shape_examples'][sig(rhs)]
 assert len(entries)==sliced['tested_shape_base_headword_counts'][sig(rhs)]==3
 tested=[]
 for rw in entries:
  rp=gp(rw)
  for lw in sorted(w for k in aab for w in ix[k]):
   lp=gp(lw);pairs=list(zip(c+rhs,lp+rp));mapping=dict(pairs)
   ok=all(mapping[k]==v for k,v in pairs) and len(mapping)==len(set(mapping.values()))
   coeff=[(a,b) for a in range(1,29) for b in range(29) if all((a*k+b)%29==v for k,v in pairs)]
   assert not coeff or ok
   tested.append(dict(left=lw,right=rw,fits_substitution=ok,affine=coeff))
 return dict(two_word_followup=tested,source=sliced['raw_sha256'],input_lines=sliced['input_lines'],distinct_heads=sliced['heads'],english_three_heads=len(sliced['length3']),english_three_rune_forms=len(ix),historic_3rune_forms=len(hh),historic_3rune_forms_in_slice=len(hh&ix.keys()),AAB_heads=sorted(w for k in aab for w in ix[k]),AAB_forms=len(aab),affine=aff,flank=obs)
if __name__=='__main__':
 d=Path(sys.argv[1]).resolve();o=Path(sys.argv[2]);r=main(d,o,Path(sys.argv[3]) if len(sys.argv)>3 else None);pack(o/'lexicon_293_results.json.gz',r)
