"""Blinded source-pixel morphology. Usage: python shapes_249.py DIRECTORY_WITH_66_67_68_JPG geometry.json OUTDIR
Does not read a transcription or a table of symbol identities."""
import sys, hashlib, json, gzip
from pathlib import Path
from collections import Counter, defaultdict
from functools import lru_cache
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from scipy import ndimage
S=112
def tight(a):
 y,x=np.nonzero(a);assert len(y);return a[y.min():y.max()+1,x.min():x.max()+1]
def fingerprint(m):
 m=tight(m);h,w=m.shape;assert max(h,w)<S-6
 # Center true native-size boxes on a common canvas; bit shifts translate with large empty guards.
 a=np.zeros((S,S),bool);i=(S-h)//2;j=(S-w)//2;a[i:i+h,j:j+w]=m
 return (int.from_bytes(np.packbits(a,bitorder='little').tobytes(),'little'),int(np.sum(m)))
@lru_cache(600000)
def sim(a,b):
 x,na=a;y,nb=b
 if x==y:return 1.
 q=0
 for dy in range(-2,3):
  for dx in range(-2,3):
   d=dy*S+dx
   if d>=0:v=((x<<d)&y).bit_count()
   else:v=((y<<(-d))&x).bit_count()
   q=max(q,v)
 return q/(na+nb-q)
def feat(m):
 h,w=m.shape;holes=ndimage.binary_fill_holes(m)&~m
 i=fingerprint(m)
 return dict(h=h,w=w,hole=ndimage.label(holes)[1],flip_x=round(sim(i,fingerprint(m[:,::-1])),6),flip_y=round(sim(i,fingerprint(m[::-1])),6))
def pct(r):return round(float(r),6)
def read(D,geo):
 cells=json.loads(Path(geo).read_text());photos={p:np.asarray(Image.open(D/(str(p+17)+'.jpg')).convert('L')) for p in [49,50,51]}
 out=[];rows={}
 for c in cells:
  p=c['page'];a=photos[p]
  for j,b in enumerate(c['glyph_bboxes']):
   x,y,X,Y=b;g=a[y-4:Y+4,x-4:X+4].copy();raw=g<128
   lab,n=ndimage.label(raw,structure=np.ones((3,3),bool));ids=[]
   for z in range(1,n+1):
    us,vs=np.nonzero(lab==z)
    if us.min()>=4 and us.max()<Y-y+4 and vs.min()>=4 and vs.max()<X-x+4:ids.append(z)
   primary=np.isin(lab,ids);m=tight(primary)
   assert hashlib.sha256(m.astype(np.uint8).tobytes()).hexdigest()==c['glyphs'][j]['mask_sha256']
   g[~ndimage.binary_dilation(primary,iterations=3)]=255
   # Consistent native content independent of neighbor overlap. Make sheet white margins integral at each scale.
   can=np.full((112,112),255,np.uint8);hh,ww=g.shape;i=(112-hh)//2;k=(112-ww)//2;can[i:i+hh,k:k+ww]=g
   out.append(dict(page=p,row=c['row'],col=c['col'],side=j+1,box=b,m=m,im=Image.fromarray(can)))
 return out
def main(D,geo,out):
 a=read(D,geo);assert len(a)==512
 key0=[fingerprint(g['m']) for g in a];uni=[];kcid={};bag=[]
 for i,key in enumerate(key0):
  if key not in kcid:
   # Deterministic complete link: admit only if each distinct previous mask of the class clears 0.92.
   eligible=[j for j,ks in enumerate(uni) if all(min(kk[1],key[1])/max(kk[1],key[1])>=.92 and sim(kk,key)>=.92 for kk in ks)]
   assert len(eligible)<=1
   if eligible:j=eligible[0];uni[j].append(key)
   else:j=len(uni);uni.append([key]);bag.append([])
   kcid[key]=j
  j=kcid[key];a[i]['cid']=j;bag[j].append(i)
 rows=defaultdict(list)
 for g in a:
  g['feat']=feat(g['m'])
  if g['side']==1:rows[g['page'],g['row']].append(g['feat']['h'])
 baseline={q:np.median([g['box'][3] for g in a if (g['page'],g['row'])==q and g['side']==1]) for q in rows}
 desc=[]
 for j,inds in enumerate(bag):
  gs=[a[i] for i in inds];types=[]
  for g in gs:
   f=g['feat'];m=float(np.median(rows[g['page'],g['row']]))
   types.append((f['w']/f['h']<=.45 and f['h']>=.85*m,f['hole']==1 and min(f['flip_x'],f['flip_y'])>=.81))
  cms=[min(sim(x,y) for x in uni[j] for y in uni[j])]
  near,other=max((max(sim(x,y) for x in uni[j] for y in by),k) for k,by in enumerate(uni) if j!=k)
  attr=lambda k:[min(g['feat'][k] for g in gs),max(g['feat'][k] for g in gs)]
  edges=[(g['box'][1]-baseline[g['page'],g['row']],g['box'][3]-baseline[g['page'],g['row']]) for g in gs]
  desc.append(dict(id=j,occ=len(gs),distinct_native_masks=len(uni[j]),per_page=[sum(g['page']==p for g in gs) for p in (49,50,51)],per_side=[sum(g['side']==s for g in gs) for s in (1,2)],first=[gs[0][f] for f in ('page','row','col','side')],tall=sum(i for i,_ in types),ring=sum(i for _,i in types),height=attr('h'),width=attr('w'),holes=attr('hole'),mirror_x=attr('flip_x'),mirror_y=attr('flip_y'),baseline_top_bottom=[[float(u),float(v),k] for (u,v),k in sorted(Counter(edges).items())],min_within=pct(cms[0]),nearest_other=other,max_between=pct(near)))
 family={r['id'] for r in desc if r['tall'] or r['ring']};summ={}
 for scale in (1,2,4):
  refs={}
  def fpg(i,t):
   im=a[i]['im'];im=im if scale==1 else im.resize((S//scale,S//scale),Image.Resampling.BOX)
   return fingerprint(np.asarray(im)<t)
  for p in (49,50,51):
   refs[p]=defaultdict(set)
   for i,g in enumerate(a):
    if g['page']!=p:refs[p][g['cid']].add(fpg(i,128))
  for threshold in (64,96,128,160,196):
   saved={};conf=Counter();den=0;nost=[];gaps=[];familyconf=Counter();fd=0
   for i,g in enumerate(a):
    tar=g['cid'];p=g['page']
    if tar not in refs[p]:nost.append(tar);continue
    fp=fpg(i,threshold);k=(p,fp)
    if k not in saved:
     vals=sorted([(max(sim(x,fp) for x in by),j) for j,by in refs[p].items()],reverse=True)
     saved[k]=vals
    vals=saved[k];top=vals[0][0];win=[cl for v,cl in vals if v==top];den+=1
    if len(win)!=1 or win[0]!=tar:conf[tar,tuple(win)]+=1
    if tar in family:
     fd+=1
     vv=next(v for v,j in vals if j==tar)-max(v for v,j in vals if j!=tar);gaps.append(vv)
     if len(win)!=1 or win[0]!=tar:familyconf[tar,tuple(win)]+=1
   aslist=lambda d:[[t,list(win),v] for (t,win),v in sorted(d.items())]
   summ[f'1/{scale}@{threshold}']=dict(eligible=den,no_other_page=dict(sorted(Counter(nost).items())),confusion=aslist(conf),family_eligible=fd,family_confusion=aslist(familyconf),worst_family_gap=pct(min(gaps)))
 pos=[g['cid'] for g in a]
 data=dict(plan='Native overlap >= .92 to every member of each admitted class; comparative margins are own best minus any other class; neutral class IDs follow first appearance, zero based.',glyphs=len(a),classes=desc,class_sequence=pos,stress=summ)
 out.mkdir(parents=True,exist_ok=True);(out/'shapes_249_results.json.gz').write_bytes(gzip.compress(json.dumps(data,separators=(',',':')).encode(),mtime=0))
 # Equal scale sample chart, native heights and widths preserved; visual labels intentionally neutral.
 show=sorted(family,key=lambda j:(not desc[j]['tall'],desc[j]['width'][0],desc[j]['height'][0]))
 atlas=Image.new('RGB',(165*min(5,len(show)),(len(show)+4)//5*153+45),'white');pen=ImageDraw.Draw(atlas);pen.text((9,12),'Native-size examples: stroke and ring screens',fill='black',font=ImageFont.truetype('DejaVuSans.ttf',18))
 for n,c in enumerate(show):
  x=n%5*165;y=45+n//5*153;g=a[bag[c][0]];m=g['m'];h,w=m.shape
  atlas.paste(Image.fromarray(np.where(m,38,251).astype(np.uint8)),(x+(165-w)//2,y+(90-h)//2));r=desc[c]
  pen.text((x+8,y+93),f"C{c:02}   {r['occ']} occurrences",fill='black',font=ImageFont.truetype('DejaVuSans.ttf',14))
  pen.text((x+8,y+115),f"{w} × {h} px   {'stroke' if r['tall'] else 'ring'}",fill='#3f4e50',font=ImageFont.truetype('DejaVuSans.ttf',13))
 atlas.save(out/'shapes_249_atlas.png');print('classes',len(desc),'candidates',show,'native masks',len(kcid),'atlas size',atlas.size,flush=True)
 for i in show:print(desc[i],flush=True)
 print('stress',summ,flush=True)
if __name__=='__main__':main(Path(sys.argv[1]),Path(sys.argv[2]),Path(sys.argv[3]))
