"""Controlled geometry examples illustrating instance-matching limits."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.overlap_evidence import two_target_evidence
from diatom_pilot.fast_mask_nms import greedy_mask_nms
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r71'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def rect(x0,y0,x1,y1):
 m=np.zeros((128,128),bool);m[y0:y1,x0:x1]=True;return m
def scene(label,refs,preds,description,expected):return {'id':label,'refs':refs,'preds':[{'id':f'p{i+1}','mask':m} for i,m in enumerate(preds)],'description':description,'expected':expected}
def build():
 a=rect(20,20,100,100);shift=rect(35,20,115,100);near=rect(25,20,105,100);sep=rect(102,20,126,100);contained=rect(40,40,80,80);opaque=rect(40,20,120,100)
 return [scene('separated_perfect',[a,sep],[a,sep],'Two separated targets and perfect masks.',(2,2)),scene('crossing_perfect',[a,shift],[a,shift],'Overlapping targets and their exact full shapes.',(2,2)),scene('near_coincident_perfect',[a,near],[a,near],'Two distinct exact shapes overlap above the suppression threshold.',(2,1)),scene('identical_targets',[a,a],[a,a],'Two coincident targets and two coincident predictions have no exclusive geometry.',(2,1)),scene('contained_perfect',[a,contained],[a,contained],'One exact target is completely contained by another.',(2,2)),scene('duplicate_union',[a,shift],[a|shift,a|shift],'Two duplicate union masks can both match overlapping targets.',(2,1)),scene('visible_only',[a,opaque],[a&~opaque,opaque],'Opaque top layer hides part of the bottom target; predictions are exact visible regions, references are full shapes.',(1,1)),scene('missing_instance',[a,shift],[a],'Only one of two targets has a candidate.',(1,1))]
def render(masks):
 im=Image.new('RGBA',(128,128),'white');layer=Image.new('RGBA',(128,128),(0,0,0,0))
 for j,mask in enumerate(masks):
  col=Image.new('RGBA',(128,128),['#00b886','#e85956'][j%2]);col.putalpha(Image.fromarray(mask.astype('uint8')*140));layer=Image.alpha_composite(layer,col)
 return Image.alpha_composite(im,layer).convert('RGB').resize((256,256),Image.Resampling.NEAREST)
def main():
 p=json.loads((OUT/'protocol.json').read_text())
 for f in p['inputs']:
  if sha(f['path'])!=f['sha256']:raise ValueError('Input changed '+f['path'])
 if (OUT/'results.json').exists():raise FileExistsError('Preserve result')
 records=[];archive={}
 for i,s in enumerate(build(),1):
  refs=s['refs'];preds=s['preds'];pre=two_target_evidence(refs,preds,.5);keep,aliases=greedy_mask_nms(preds,.8);post=two_target_evidence(refs,keep,.5);assert (pre['matched'],post['matched'])==s['expected'];exclusive=[refs[0]&~refs[1],refs[1]&~refs[0]];archive[f'{s["id"]}_refs']=np.stack(refs);archive[f'{s["id"]}_preds']=np.stack([q['mask'] for q in preds]);panel=Image.new('RGB',(1024,290),'white');draw=ImageDraw.Draw(panel)
  for col,(name,masks) in enumerate([('Full target shapes',refs),('Target-exclusive regions',exclusive),('Candidate masks',[q['mask'] for q in preds]),('Kept after IoU NMS',[q['mask'] for q in keep])]):panel.paste(render(masks),(col*256,32));draw.text((col*256+4,7),name,fill='#203a38')
  image=f'case-{i:02d}.png';panel.save(OUT/image);records.append({'id':s['id'],'description':s['description'],'before_nms':pre,'after_nms':post,'aliases':aliases,'image':image,'image_sha256':sha(OUT/image)});print(s['id'],pre['matched'],'→',post['matched'],'exclusive',pre['exclusive_areas'],flush=True)
 np.savez_compressed(OUT/'masks.npz',**archive);(OUT/'results.json').write_text(json.dumps({'format':'r71-mask-geometry-controls-v1','protocol_sha256':sha(OUT/'protocol.json'),'archive_sha256':sha(OUT/'masks.npz'),'records':records,'warning':'Hand-constructed geometry, no microscope images or trained model. Full vs visible mask conventions differ; geometric margins and NMS thresholds are not biological labels.'},indent=2)+'\n')
if __name__=='__main__':main()
