"""Run python -B aab_289_290.py NOTEBOOK_EVIDENCE OUTPUT.json.gz. Python 3.10+, NumPy for existing notebook tokenizer."""
from pathlib import Path
from collections import Counter,defaultdict
from fractions import Fraction
import json,gzip,hashlib,re,sys
R='ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
NAMES='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()
CATS=('AAA','AAB','ABA','ABB','ABC')
def shape(v):
 a,b,c=v
 result='AAA' if a==b==c else 'AAB' if a==b else 'ABA' if a==c else 'ABB' if b==c else 'ABC'
 tab={};sig=''.join(tab.setdefault(x,chr(65+len(tab))) for x in v);assert sig==result
 return sig
def full_count(seq):
 k=Counter(shape(v) for v in seq if len(v)==3);return {s:k[s] for s in CATS}
def rat(f):return [f.numerator,f.denominator]
def run(d):
 sys.path.insert(0,str(d))
 from lexical_words import tokenize_words
 src=d/'liber-primus__transcription--master.txt';b=src.read_bytes();h=hashlib.sha256(b).hexdigest();assert h=='b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
 r=b.decode();pg=r[r.index('ᚱ-'):].split('%')[:73];u='%'.join(pg[15:71]); corpus=tokenize_words(u)
 # Separate parser and coordinate walk: build rune words with int tuples, attach the intervening literal characters on their FIRST rune.
 q=re.sub('(?<=['+R+"])[’'](?=["+R+'])','',u);p=0;line=1;col=0;off=0;glob=0;sec=0;gap='';result=[];active=[];meta=None
 def flush():
  if active:result.append((meta,tuple(active)));active.clear()
 for c in q:
  if c in R:
   if not active:
    meta=dict(page=p,row=line,row_rune=col+1,offset=off,section=sec,global_offset=glob,at_row=col==0,at_page=off==0,after_stop=glob==0 or any(a in gap for a in '.&§$'),after_alnum=len(re.findall('[0-9a-zA-Z]',gap))>=8)
   active.append(R.index(c));gap='';off+=1;col+=1;glob+=1
  else:
   gap+=c
   if c=='%':p+=1;line=1;col=off=0
   elif c=='/':line+=1;col=0
   elif c not in '\n\r\t ':
    flush()
    if c=='$':sec+=1
 flush()
 assert len(result)==len(corpus)
 for (a,v),w in zip(result,corpus):assert (a['page'],a['section'],a['offset'],a['global_offset'],v)==(w['page'],w['section'],w['page_rune_offset'],w['rune_offset'],tuple(w['values']))
 three=[dict(**m,v=v,shape=shape(v)) for m,v in result if len(v)==3]
 assert len({m['global_offset'] for m in three})==len(three) and all(y['global_offset']>=x['global_offset']+3 for x,y in zip(three,three[1:]))
 target=[w for w in three if (w['page'],w['offset'])==(51,0)];assert len(target)==1 and target[0]['v']==(7,7,13);target=target[0]
 def by(key):
  a=defaultdict(list)
  for w in three:a[w[key]].append(w['v'])
  return {str(k):full_count(v) for k,v in sorted(a.items())}
 cfg=json.loads((d/'mechanism_coverage_results.json').read_text())['known_method_groups']
 gold={x['name']:x['values'] for x in json.loads((d/'increment_calibration_sources.json').read_text())['groups']}
 sol={}
 for t in cfg:
  nn=t['name'];v=gold[nn];assert hashlib.sha256(bytes(v)).hexdigest()==t['plaintext_rune_values_sha256'];a=0;pw=[];cw=[]
  for w in tokenize_words('%'.join(pg[i] for i in t['parsed_page_indices'])):
   c=w['values'];cw.append(c);pw.append(v[a:a+len(c)]);a+=len(c)
  assert a==len(v)
  sol[nn]={'cipher':full_count(cw),'plain':full_count(pw),'printed_AAB_words':[dict(word_index=i,cipher=c,plain=p) for i,(c,p) in enumerate(zip(cw,pw)) if len(c)==3 and shape(c)=='AAB']}
 def stage(rows):
  ct={}
  for f in ('at_row','at_page','after_stop','after_alnum'):
   g=[m for m in rows if m[f]];oth=[w for w in rows if not w[f]]
   ct[f]={'inside':[sum(w['shape']=='AAB' for w in g),len(g)],'outside':[sum(w['shape']=='AAB' for w in oth),len(oth)]}
  strata=defaultdict(list)
  for w in rows:strata[w['section']].append(w)
  hist=Counter({0:1});details={}
  for k,z in sorted(strata.items()):
   flags={j for j,w in enumerate(z) if w['at_row']};hits=[j for j,w in enumerate(z) if w['shape']=='AAB'];m=len(z)
   per=Counter(sum((j+s)%m in flags for j in hits) for s in range(m))
   details[k]=dict(n=m,hits=len(hits),row_starts=len(flags),rotation_hist=sorted(per.items()))
   h=Counter()
   for a,ca in per.items():
    for b,cb in hist.items():h[a+b]+=ca*cb
   hist=h
  denom=hist.total();obs=ct['at_row']['inside'][0]
  mean=Fraction(sum(i*j for i,j in hist.items()),denom);assert mean==sum(Fraction(z['hits']*z['row_starts'],z['n']) for z in details.values())
  frac=Fraction(sum(j for i,j in hist.items() if i>=obs),denom)
  return dict(counts=ct,section_rotation_hist=details,observed=obs,expected=rat(mean),at_least_observed=rat(frac),rotation_hist=sorted(hist.items()))
 return {'transcription_sha256':h,'protocol_sha256':hashlib.sha256(Path(__file__).with_name('aab_289_290_plan.txt').read_bytes()).hexdigest(),'total_words':len(corpus),'unknown_3':full_count(w['v'] for w in three),'by_page':by('page'),'by_section':by('section'),'solved':sol,'AAB_examples':[dict(m,transliteration=' '.join(NAMES[c] for c in m['v'])) for m in three if m['shape']=='AAB'],'all':stage(three),'without_grid':stage([w for w in three if w is not target]),'alnum_breaks_among_3':[{k:w[k] for k in ['page','offset','section','shape']} for w in three if w['after_alnum']]}
if __name__=='__main__':
 out=Path(sys.argv[2]);data=run(Path(sys.argv[1]).resolve());out.write_bytes(gzip.compress((json.dumps(data,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
