"""python witness_375.py EVIDENCE OUTDIR. Archive p31 photo, two repeated key positions."""
import json,sys,io,base64,gzip,hashlib
from pathlib import Path
import numpy as np
from PIL import Image
def main(d,o):
 sys.path.insert(0,str(d.resolve()));from print_322_323 import seg,as_row,R
 raw=(d/'liber-primus__transcription--master.txt').read_text();pp=raw[raw.index('ᚱ-'):].split('%')[46].split('/')
 A=np.asarray(Image.open(d/'48.jpg').convert('L'));out={}; runes=['ᛖ','ᛋ'];found=[]
 for t in (80,128,180):
  rows=seg(A,t);rec=[];masks=[]
  for line,token,ordinal in [(10,'ᛈᛒᚪᛖ',3),(11,'ᚩᛒᛋᛉ',2)]:
   src=pp[line-1].strip().replace('\n','');j=src.index(token)+ordinal; cc=sum(c in R for c in src[:j]);row=rows[line-1];ex=as_row(src)
   cut=[i for i,k in enumerate(ex) if k=='g'][cc]+1
   assert ex[:cut]==''.join(q for q,b in row[:cut])
   box=row[cut-1][1];x,y,X,Y=box;mask=A[y:Y,x:X]<t;rec.append({'physical_line':line,'rune_column_1based':cc+1,'source_rune':src[j],'box':box,'shape':list(mask.shape),'ink':int(mask.sum())});masks.append(mask)
  assert [r['source_rune'] for r in rec]==runes
  ref=Image.fromarray((masks[1]*255).astype('uint8')).resize((32,64),Image.Resampling.NEAREST); cmp=Image.fromarray((masks[0]*255).astype('uint8')).resize((32,64),Image.Resampling.NEAREST)
  disagreements=int(np.count_nonzero(np.asarray(ref)!=np.asarray(cmp)));out[t]={'glyphs':rec,'different_pixels_after_32x64_nearest_stretch':disagreements}
  if t==128:found=[v['box'] for v in rec]
 imgs=[]
 for k,(x,y,X,Y) in enumerate(found):
  buf=io.BytesIO();Image.fromarray(A[y-3:Y+3,x-3:X+3]).save(buf,format='PNG');imgs.append('data:image/png;base64,'+base64.b64encode(buf.getvalue()).decode())
 s=f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 470 175" role="img" aria-labelledby="t"><title id="t">Two different printed glyphs would both have to stand for R.</title><rect width="470" height="175" fill="#f9f8f2"/><g font-family="sans-serif" fill="#292e2c"><text x="13" y="23" font-size="15">LP2 page 31: the two positions needed for R</text><image x="50" y="35" width="106" height="96" href="{imgs[0]}"/><image x="272" y="35" width="106" height="96" href="{imgs[1]}"/><text x="47" y="152" font-size="14">THEIR · last rune</text><text x="241" y="152" font-size="14">NUMBERS · sixth rune</text></g></svg>''';(o/'two_runes_375.svg').write_text(s+'\n')
 (o/'witness_375_results.json').write_text(json.dumps(out,sort_keys=True,indent=2,ensure_ascii=False)+'\n')
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
