"""Controlled synthetic instance segmentation on real microscopy backgrounds.

Six postselected public polygons create three pairs, each separated or overlapping.
The inserted masks give known visible and full object extents; no claims about
real crossings, whole-field false positives, or independently verified biology.
"""
import hashlib,itertools,json,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image,ImageDraw
from ultralytics import YOLO
from ultralytics.models.sam import Predictor

ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r38';TEMP=Path('/tmp/diatom-r38-crossings');SELECTION=ROOT/'results/r16/selection.json';BACKGROUND=ROOT/'results/pilot/field-01/field.png'
DETECTOR=Path('/tmp/diatom-detector.pt');SAM=Path('/tmp/mobile_sam.pt')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def iou(a,b):
 union=int((a|b).sum());return float((a&b).sum()/union) if union else 0.
def point(mask):
 distance=cv2.distanceTransform(mask.astype('uint8'),cv2.DIST_L2,5);y,x=np.unravel_index(int(distance.argmax()),distance.shape)
 if not distance[y,x]:raise ValueError('Empty visible target')
 return [int(x),int(y)]
def assign(refs,masks,threshold):
 scores=[[iou(ref,m) for m in masks] for ref in refs];choices=[None]+list(range(len(masks)))
 valid=[p for p in itertools.product(choices,repeat=2) if (p[0] is None or p[1] is None or p[0]!=p[1]) and all(j is None or scores[i][j]>=threshold for i,j in enumerate(p))]
 best=max(valid,key=lambda p:(sum(x is not None for x in p),sum(scores[i][j] for i,j in enumerate(p) if j is not None)))
 return {'matched':sum(x is not None for x in best),'matched_ious':[None if j is None else scores[i][j] for i,j in enumerate(best)]}
def extract(entry,index):
 annotation=json.loads((Path('/tmp/diatom-mask-coco')/entry['annotation_file']).read_text());anns=[a for a in annotation['annotations'] if a['image_id']==entry['image']['id']]
 if len(anns)!=1:raise ValueError('Expected one source target')
 path=Path('/tmp/diatom-mask-images')/f'{index:02d}.jpg';image=np.asarray(Image.open(path).convert('RGB'));h,w=image.shape[:2];mask=np.zeros((h,w),'uint8')
 for poly in anns[0]['segmentation']:cv2.fillPoly(mask,[np.rint(np.asarray(poly).reshape(-1,2)).astype('int32')],1)
 ys,xs=np.where(mask)
 if not len(xs):raise ValueError('Empty source mask')
 x0,x1,y0,y1=xs.min(),xs.max()+1,ys.min(),ys.max()+1;crop=image[y0:y1,x0:x1];mask=mask[y0:y1,x0:x1];factor=150/max(mask.shape);size=(max(1,round(mask.shape[1]*factor)),max(1,round(mask.shape[0]*factor)))
 crop=cv2.resize(crop,size,interpolation=cv2.INTER_AREA);mask=cv2.resize(mask,size,interpolation=cv2.INTER_NEAREST)>0
 return crop,mask,{'annotation_id':anns[0]['id'],'image_sha256':sha(path),'annotation_sha256':sha(Path('/tmp/diatom-mask-coco')/entry['annotation_file'])}
def paste(canvas,full,crop,mask,cx,cy):
 h,w=mask.shape;left=int(cx-w//2);top=int(cy-h//2)
 if left<0 or top<0 or left+w>512 or top+h>512:raise ValueError('Object outside scene')
 region=canvas[top:top+h,left:left+w];region[mask]=crop[mask];full[top:top+h,left:left+w]=mask

def main():
 OUT.mkdir(parents=True,exist_ok=True);TEMP.mkdir(parents=True,exist_ok=True)
 if (OUT/'results.json').exists():raise FileExistsError('Results exist; preserve experiment')
 protocol=json.loads((OUT/'protocol.json').read_text());
 for path,key in [(SELECTION,'selection_sha256'),(BACKGROUND,'background_sha256'),(DETECTOR,'detector_sha256'),(SAM,'sam_sha256'),(Path(__file__),'script_sha256')]:
  if sha(path)!=protocol[key]:raise ValueError('Frozen input changed: '+key)
 source=json.loads(SELECTION.read_text())['selection'];objects=[extract(row,i) for i,row in enumerate(source,1)]
 if [x[2] for x in objects]!=protocol['source_objects']:raise ValueError('Frozen source image or annotation changed')
 background=np.asarray(Image.open(BACKGROUND).convert('RGB').crop((128,128,640,640))).copy()
 torch.set_num_threads(4);detector=YOLO(str(DETECTOR));records=[]
 for pair in range(3):
  for condition in ('separated','crossing'):
   crop1,mask1,meta1=objects[2*pair];crop2,mask2,meta2=objects[2*pair+1];canvas=background.copy();full1=np.zeros((512,512),bool);full2=np.zeros((512,512),bool)
   centers=((141,256),(371,256)) if condition=='separated' else ((256,256),(256,256))
   paste(canvas,full1,crop1,mask1,*centers[0]);paste(canvas,full2,crop2,mask2,*centers[1]);visible=[full1&~full2,full2];full=[full1,full2];overlap=int((full1&full2).sum())
   if min(int(x.sum()) for x in visible)<50:raise ValueError('An inserted object is almost fully hidden')
   imgpath=TEMP/f'pair-{pair+1}-{condition}.png';Image.fromarray(canvas).save(imgpath)
   bgr=cv2.cvtColor(canvas,cv2.COLOR_RGB2BGR);pred=detector.predict(bgr,imgsz=512,conf=.05,device='cpu',verbose=False)[0];boxes=pred.boxes.xyxy.cpu().numpy().tolist() if pred.boxes is not None else []
   predictor=Predictor(overrides={'model':str(SAM),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});predictor.set_image(bgr)
   def masks_for(**args):
    result=predictor(verbose=False,**args)[0]
    if result.masks is None:return []
    return [x.astype(bool) for x in result.masks.data.cpu().numpy()]
   points=[point(x) for x in visible];point_masks=masks_for(points=[[p] for p in points],labels=[[1],[1]])
   box_masks=masks_for(bboxes=boxes) if boxes else []
   if len(point_masks)!=2 or any(x.shape!=(512,512) for x in point_masks+box_masks):raise ValueError('Unexpected predicted masks')
   methods={}
   for name,masks in [('oracle_points',point_masks),('detector_boxes',box_masks)]:
    methods[name]={'candidates':len(masks),'visible_at_05':assign(visible,masks,.5),'visible_at_075':assign(visible,masks,.75),
      'full_at_05':assign(full,masks,.5)}
   rec={'pair':pair+1,'condition':condition,'sources':[meta1,meta2],'visible_pixels':[int(x.sum()) for x in visible],
        'full_pixels':[int(x.sum()) for x in full],'overlap_pixels':overlap,'oracle_points':points,'methods':methods};records.append(rec)
   # Silhouette-only diagnostic: source image pixels are not redistributed.
   thumb=Image.new('RGB',(1024,512),'#eef2ed');draw=ImageDraw.Draw(thumb)
   for col,maskset in enumerate((visible,point_masks)):
    for mask,color in zip(maskset,('#198f76','#c05b36')):
     overlay=Image.new('RGBA',(512,512),color);overlay.putalpha(Image.fromarray(mask.astype('uint8')*150));base=thumb.crop((col*512,0,(col+1)*512,512)).convert('RGBA');base=Image.alpha_composite(base,overlay);thumb.paste(base.convert('RGB'),(col*512,0))
   thumb.thumbnail((768,384));thumb.save(OUT/f'pair-{pair+1}-{condition}-silhouettes.png')
   print(f'Pair {pair+1}, {condition}: detector masks {len(box_masks)}, overlap {overlap} px, point visible matches {methods["oracle_points"]["visible_at_05"]["matched"]}/2, detector matches {methods["detector_boxes"]["visible_at_05"]["matched"]}/2',flush=True)
 payload={'format':'r38-synthetic-crossings-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,
    'warning':'Six synthetic scenes from six selected polygons and one real but not verified empty Academy background; image copies are opaque. Oracle point prompts use known visible masks. Other background objects are unannotated; no false-positive rate, real-overlap or Academy recall claim is possible.'}
 (OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n')
 cards=[]
 for r in records:
  m=r['methods'];cards.append(f"<article><h3>Pair {r['pair']} · {r['condition']}</h3><img src=\"pair-{r['pair']}-{r['condition']}-silhouettes.png\" alt=\"Reference and point-prompted mask silhouettes\"><p>Left: visible reference masks; right: point-prompted masks. Source-image pixels are not shown.</p><p>Visible matches at IoU ≥ 0.5: oracle points {m['oracle_points']['visible_at_05']['matched']}/2; detector-box masks {m['detector_boxes']['visible_at_05']['matched']}/2 from {m['detector_boxes']['candidates']} candidates. Reference overlap: {r['overlap_pixels']} pixels.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Controlled overlap segmentation</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1100px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:14px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(340px,1fr));gap:12px}article{background:white;padding:12px}img{width:100%}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/R38.md">Research note</a></nav><h1>Controlled overlap segmentation</h1><p class="notice">Six synthetic scenes from six selected public annotations on one real but not verified empty Academy background. Opaque paste is not a microscope simulation. Oracle points use the known visible masks. Results are not real-overlap or whole-slide accuracy.</p><p>Each reference can match at most one prediction. The page shows visible-mask results at 0.5 IoU; full-extent and stricter 0.75 IoU scores are in <a href="results.json">the recorded data</a>. Other objects in the background are unannotated.</p><div class="grid">{CARDS}</div></main></html>'''.replace('{CARDS}',''.join(cards));(OUT/'index.html').write_text(page)
 note=['# R38 · Controlled overlap segmentation','', 'Six synthetic scenes: three pairs of public annotated cutouts, one Academy background, separated and opaque-overlap placements. This is a controlled development diagnostic, not evidence of human-level segmentation or real-overlap accuracy. Model training-data overlap and background annotation completeness are unknown. The source record does not specify license text; source image pixels are retained locally in /tmp, and only derived silhouettes are displayed.', '', '| Pair | Condition | Overlap pixels | Oracle points: visible @0.5 | Detector boxes: visible @0.5 | Detector candidates |','|---|---|---:|---:|---:|---:|']
 for r in records:
  m=r['methods'];note.append(f"| {r['pair']} | {r['condition']} | {r['overlap_pixels']} | {m['oracle_points']['visible_at_05']['matched']}/2 | {m['detector_boxes']['visible_at_05']['matched']}/2 | {m['detector_boxes']['candidates']} |")
 note.extend(['','Full-object and visible-object masks differ where the back specimen is occluded; both are scored in the JSON. Point prompts are derived from reference masks and cannot demonstrate automatic detection. Mask matching is posthoc one-to-one, not candidate selection. Unmatched background proposals are not necessarily false positives. The six cases share a background and selected source images, and opaque compositing may be unrealistic. [View silhouettes and data](/results/r38/).','','**Follow-up:** Test multiple backgrounds and realistic blending, compare visible vs inferred extent explicitly, and assess non-oracle candidate ranking; evaluate on real crossings before generalizing.'])
 (ROOT/'research/R38.md').write_text('\n'.join(note)+'\n')
 board=ROOT/'research/board.json';d=json.loads(board.read_text())
 for task in d['tasks']:
  if task['id']=='R38':task.update(status='review',summary='Six controlled synthetic scenes scored with detector-box and oracle-point MobileSAM masks; see visible/full outcomes and limitations.',note='R38.md',result='/results/r38/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board)
 print('Completed six controlled synthetic scenes.',flush=True)

if __name__=='__main__':main()
