"""Compare detector-box and grid-prompt masks on 12 existing local fields.

No reference labels are used; overlap measures prediction agreement, not accuracy.
"""
import hashlib,json,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image,ImageDraw,ImageOps
from ultralytics.models.sam import Predictor
ROOT=Path(__file__).resolve().parents[1];SURVEY=ROOT/'results/r3/scan-survey';OUT=ROOT/'results/r39';SAM=Path('/tmp/mobile_sam.pt')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def iou(a,b):
 u=int((a|b).sum());return float((a&b).sum()/u) if u else 0.
def overlay(image,candidates):
 canvas=image.convert('RGBA');d=Image.new('RGBA',image.size,(0,0,0,0));colors=[(0,196,155,100),(238,126,62,100),(161,96,230,100),(253,201,64,100)]
 for i,c in enumerate(candidates):
  layer=Image.new('RGBA',image.size,colors[i%len(colors)]);layer.putalpha(Image.fromarray(c['mask'].astype('uint8')*85));d=Image.alpha_composite(d,layer)
 return Image.alpha_composite(canvas,d).convert('RGB')
def main():
 protocol=json.loads((OUT/'protocol.json').read_text());survey=json.loads((SURVEY/'survey.json').read_text())
 for path,key in [(SURVEY/'survey.json','survey_sha256'),(SAM,'segmenter_sha256'),(Path(__file__),'script_sha256')]:
  if sha(path)!=protocol[key]:raise ValueError('Frozen input changed: '+key)
 if (OUT/'results.json').exists():raise FileExistsError('Experiment already complete')
 torch.set_num_threads(4);rows=[];OUT.mkdir(parents=True,exist_ok=True)
 for index,f in enumerate(survey['fields'],1):
  started=time.monotonic();path=SURVEY/f['image']
  if sha(path)!=protocol['field_sha256'][index-1]:raise ValueError('Field image changed')
  source=Image.open(path).convert('RGB');array=cv2.cvtColor(np.asarray(source),cv2.COLOR_RGB2BGR);predictor=Predictor(overrides={'model':str(SAM),'task':'segment','mode':'predict','imgsz':768,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});predictor.set_image(array)
  def box_masks(entries):
   if not entries:return []
   pred=predictor(bboxes=[x['xyxy'] for x in entries],verbose=False)[0]
   if pred.masks is None:return []
   masks=[m.astype(bool) for m in pred.masks.data.cpu().numpy()]
   if len(masks)!=len(entries):raise ValueError('Box-mask count mismatch')
   return [{'mask':m,'score':e['confidence'],'area':int(m.sum())} for m,e in zip(masks,entries)]
  full=box_masks(f['full_field']);tile=box_masks(f['tile_kept']);points=[(x,y) for y in range(64,768,128) for x in range(64,768,128)];grid=[]
  for n in range(0,len(points),12):
   batch=points[n:n+12];pred=predictor(points=[[[x,y]] for x,y in batch],labels=[[1] for _ in batch],verbose=False)[0]
   if pred.masks is None:continue
   for mask,score in zip(pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
    mask=mask.astype(bool);area=int(mask.sum())
    if 300<=area<=50000 and float(score)>=.6:grid.append({'mask':mask,'score':float(score),'area':area})
  kept=[]
  for c in sorted(grid,key=lambda c:-c['score']):
   if all(iou(c['mask'],x['mask'])<.8 for x in kept):kept.append(c)
  def overlap(a,b):return sum(any(iou(x['mask'],y['mask'])>=.5 for y in b) for x in a)
  def within(c):return sum(iou(c[i]['mask'],c[j]['mask'])>=.5 for i in range(len(c)) for j in range(i+1,len(c)))
  rec={'field':index,'slide':f['slide'],'origin_xy':f['origin_xy'],'z':f['z'],'source_sha256':sha(path),
       'full_count':len(full),'tile_count':len(tile),'grid_count':len(kept),'grid_before_nms':len(grid),
       'full_grid_agreement_at_05':overlap(full,kept),'tile_grid_agreement_at_05':overlap(tile,kept),
       'grid_within_pairs_at_05':within(kept),'seconds':time.monotonic()-started}
  rows.append(rec)
  # All colored masks are model proposals, not ground-truth annotations.
  canvas=Image.new('RGB',(1152,430),'#f7f8f3');draw=ImageDraw.Draw(canvas)
  for col,(title,masks) in enumerate([('Full-field detector',full),('Tiled detector',tile),('Grid proposals',kept[:20])]):
   im=overlay(ImageOps.autocontrast(source,cutoff=.25),masks);im.thumbnail((360,360));canvas.paste(im,(col*384+8,44));draw.text((col*384+8,8),title+' · '+str(len(masks))+' shown',fill='#203a38')
  canvas.save(OUT/f'field-{index:02d}.jpg',quality=88);print(f"{index}/12 fields: full {len(full)}, tile {len(tile)}, grid {len(kept)}, grid overlapping pairs {rec['grid_within_pairs_at_05']}",flush=True)
 result={'format':'r39-candidate-audit-v1','protocol_sha256':sha(OUT/'protocol.json'),'fields':rows,'warning':'Unreviewed predictions on preselected, previously examined fields; mask agreement is not accuracy and no method has ground-truth recall or precision.'}
 (OUT/'results.json').write_text(json.dumps(result,indent=2)+'\n')
 cards=[]
 for r in rows:cards.append(f"<article><h3>Field {r['field']:02d}</h3><img src=\"field-{r['field']:02d}.jpg\" alt=\"Three candidate mask overlays\"><p>Full {r['full_count']} · tiled {r['tile_count']} · grid {r['grid_count']} masks; {r['grid_within_pairs_at_05']} grid-mask pairs overlap at IoU ≥ 0.5. Grid panel shows at most 20.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Candidate masks on real slide fields</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1180px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:14px}article{background:white;padding:12px;margin:12px 0}img{width:100%}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/R39.md">Research note</a></nav><h1>Candidate masks on real slide fields</h1><p class="notice">Colored shapes are unreviewed model candidates, not ground truth. These 12 fields were previously inspected and sampled one per scan file; they are not verified independent samples. Candidate counts and overlap are not accuracy or recall.</p><p>Each row shows full-field detector prompts, tiled detector prompts, and up to 20 quality-ranked grid prompts. Grid scores and detector confidence are different quantities; panels do not represent a matched review budget. <a href="results.json">Measurements</a> · <a href="protocol.json">Frozen settings</a></p>{CARDS}</main></html>'''.replace('{CARDS}',''.join(cards))
 (OUT/'index.html').write_text(page)
 totals={k:sum(r[k] for r in rows) for k in ('full_count','tile_count','grid_count','grid_within_pairs_at_05','full_grid_agreement_at_05','tile_grid_agreement_at_05')}
 note=f'''# R39 · Candidate masks on 12 local slide fields\n\nUse the 12 previously sampled and viewed Academy development fields from R3. Reuse the recorded full-field and tiled detector boxes and prompt MobileSAM; compare with a fixed 128-pixel grid of positive points with score ≥ 0.6, area 300–50,000 pixels, and duplicate suppression at mask IoU 0.8. These settings were fixed before this run. Grid and detector scores are not comparable.\n\nAcross 12 fields the model produced {totals['full_count']} full-field box masks, {totals['tile_count']} tiled box masks, and {totals['grid_count']} retained grid masks. Among grid masks, {totals['grid_within_pairs_at_05']} within-field pairs overlap at IoU ≥ 0.5; {totals['full_grid_agreement_at_05']} full-field and {totals['tile_grid_agreement_at_05']} tiled masks each have at least one grid mask at IoU ≥ 0.5. [View all field overlays](/results/r39/) and [measurements](/results/r39/results.json).\n\nThese are unreviewed predictions, not reference labels. Counts or agreement do not establish recall, accuracy, distinct specimens, or false-positive rates; true instances may overlap substantially. Grid panels show at most 20 candidates, so recorded totals can exceed displayed counts. Fields are one per previously selected scan, but biological sample independence and completeness are unknown. Preservation of small/partial valves and the value of grids require review against references; the experiment does not establish human-level performance.\n\n**Follow-up:** use self-supervised consistency and controlled object insertion to rank candidates, then compare against real provisional marks after available automated experiments; retain overlap rather than suppressing solely on IoU. Compare runtime and candidate burden, and preserve classification crops.\n'''
 (ROOT/'research/R39.md').write_text(note)
 board=ROOT/'research/board.json';d=json.loads(board.read_text())
 for t in d['tasks']:
  if t['id']=='R39':t.update(status='review',summary=f"On 12 previously viewed fields: {totals['full_count']} full, {totals['tile_count']} tile, {totals['grid_count']} grid masks; agreement is not accuracy.",note='R39.md',result='/results/r39/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed 12-field candidate audit.',flush=True)
if __name__=='__main__':main()
