"""Score frozen proposal rankings against individual public polygon targets."""
import json,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics import YOLO
from ultralytics.models.sam import Predictor
import r38_synthetic_crossings as base
from r41_consensus_fresh_sources import interleave
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r43';SRC=Path('/tmp/diatom-mask-coco');IMAGES=Path('/tmp/diatom-r43-public')

def render(ref,ranked,path):
 panel=Image.new('RGB',(960,240),'#eef3ed')
 for col,masks in enumerate(([ref],[c['mask'] for c in ranked[:10]])):
  tile=Image.new('RGBA',(768,576),'#eef3ed')
  for i,m in enumerate(masks):
   color=['#198f76','#c05b36','#8066ae','#b39629'][i%4];layer=Image.new('RGBA',(768,576),color);layer.putalpha(Image.fromarray(m.astype('uint8')*100));tile=Image.alpha_composite(tile,layer)
  panel.paste(tile.convert('RGB').resize((320,240)),(col*320,0))
 panel.crop((0,0,640,240)).save(path)

def main():
 p=json.loads((OUT/'protocol.json').read_text());s=json.loads((OUT/'selection.json').read_text());download=json.loads((OUT/'download-report.json').read_text())
 for path,key in [(OUT/'selection.json','selection_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(Path(__file__),'script_sha256')]:
  if base.sha(path)!=p[key]:raise ValueError('Frozen input changed: '+key)
 for name,h in s['annotation_sha256'].items():
  if base.sha(SRC/name)!=h:raise ValueError('Annotation source changed')
 if download['selection_sha256']!=p['selection_sha256'] or len(download['images'])!=len(s['selection']):raise ValueError('Download report mismatch')
 if (OUT/'results.json').exists():raise FileExistsError('Experiment already completed')
 torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 for i,row in enumerate(s['selection'],1):
  t=time.monotonic();impath=IMAGES/f'{i:02}.jpg'
  if base.sha(impath)!=download['images'][i-1]['sha256']:raise ValueError('Image hash mismatch')
  image=np.asarray(Image.open(impath).convert('RGB'));h,w=image.shape[:2]
  if (w,h)!=(row['image']['width'],row['image']['height']):raise ValueError('Image size mismatch')
  ref=np.zeros((h,w),'uint8');ann=next(a for a in json.loads((SRC/row['annotation_file']).read_text())['annotations'] if a['id']==row['annotation_id'] and a['image_id']==row['image']['id'])
  for poly in ann['segmentation']:cv2.fillPoly(ref,[np.rint(np.asarray(poly).reshape(-1,2)).astype('int32')],1)
  ref=cv2.resize(ref,(768,576),interpolation=cv2.INTER_NEAREST)>0
  if not ref.any():raise ValueError('Empty reference')
  image=cv2.resize(image,(768,576),interpolation=cv2.INTER_AREA);bgr=cv2.cvtColor(image,cv2.COLOR_RGB2BGR);dp=detector.predict(bgr,imgsz=768,conf=.05,device='cpu',verbose=False)[0];boxes=dp.boxes.xyxy.cpu().numpy().tolist() if dp.boxes is not None else []
  predictor=Predictor(overrides={'model':str(base.SAM),'task':'segment','mode':'predict','imgsz':768,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});predictor.set_image(bgr)
  if boxes:
   out=predictor(bboxes=boxes,verbose=False)[0];det=[] if out.masks is None else [m.astype(bool) for m in out.masks.data.cpu().numpy()]
  else:det=[]
  points=[(x,y) for y in range(32,576,64) for x in range(32,768,64)];raw=[]
  for n in range(0,len(points),12):
   batch=points[n:n+12];out=predictor(points=[[[x,y]] for x,y in batch],labels=[[1] for _ in batch],verbose=False)[0]
   if out.masks is None or len(out.masks.data)!=len(batch):raise ValueError('Unexpected mask batch')
   for pt,mask,score in zip(batch,out.masks.data.cpu().numpy(),out.boxes.conf.cpu().numpy()):
    mask=mask.astype(bool);area=int(mask.sum())
    if 300<=area<=50000 and float(score)>=.6:raw.append({'id':len(raw),'point':pt,'mask':mask,'quality':float(score)})
  kept=[]
  for c in sorted(raw,key=lambda c:-c['quality']):
   if all(base.iou(c['mask'],x['mask'])<.8 for x in kept):kept.append(c)
  for c in kept:c['support']=max((base.iou(c['mask'],m) for m in det),default=0.)
  support=sorted(kept,key=lambda c:(-(c['support']>=.25),-c['quality']));ranked={'quality':kept,'alternating':interleave(support,kept)}
  def best(masks):return max((base.iou(ref,m) for m in masks),default=0.)
  metrics={name:{str(n):best([x['mask'] for x in candidates[:n]]) for n in (5,10,20)}|{'all':best([x['mask'] for x in candidates])} for name,candidates in ranked.items()}
  metrics['detector']={'all':best(det)}
  rec={'index':i,'category':row['category'],'family':row['filename_family_heuristic'],'source_image_sha256':base.sha(impath),'annotation_id':ann['id'],
       'detector_masks':len(det),'grid_masks':len(kept),'supported_grid_masks':sum(c['support']>=.25 for c in kept),'best_reference_iou':metrics,'seconds':time.monotonic()-t};records.append(rec)
  render(ref,ranked['alternating'],OUT/f'target-{i:02}-silhouettes.png')
  print(f"{i}/{len(s['selection'])} targets: detector {metrics['detector']['all']:.2f}, quality top10 {metrics['quality']['10']:.2f}, alternating top10 {metrics['alternating']['10']:.2f}",flush=True)
 payload={'format':'r43-public-polygon-benchmark-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,
 'warning':'Preselected public polygon targets, filename family heuristic only; unmatched candidates may be unannotated specimens or debris. Detector training-data overlap unknown; not Academy overlap or whole-field accuracy.'}
 (OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n')
 cards=[]
 for r in records:
  m=r['best_reference_iou'];cards.append(f"<article><h3>Target {r['index']:02d} · {r['category'].split('_')[0]}</h3><img src=\"target-{r['index']:02d}-silhouettes.png\" alt=\"Reference and candidate mask silhouettes\"><p>Left: annotated target; right: first 10 alternating-ranked candidate masks, with colors indicating candidates, not identities. Best target IoU: detector {m['detector']['all']:.2f} · quality top 10 {m['quality']['10']:.2f} · alternating top 10 {m['alternating']['10']:.2f}. {r['grid_masks']} total grid masks.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Public polygon segmentation benchmark</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1150px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:14px}article{background:white;padding:12px;margin:12px 0}img{max-width:100%}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/R43.md">Research note</a></nav><h1>Public polygon segmentation benchmark</h1><p class="notice">Twelve preselected public targets from two taxa, grouped heuristically by filename. These are not independent local overlap tests; there may be unannotated objects, and detector training-data overlap is unknown. Source images are not shown because the public record has no explicit reuse license text.</p><p>Candidate ranking uses predictions only; polygon masks are used afterward for scoring. Best IoU is reference-selected evaluation, not a deployable selection policy. <a href="results.json">Full data</a> · <a href="protocol.json">Frozen protocol</a></p>{CARDS}</main></html>'''.replace('{CARDS}',''.join(cards));(OUT/'index.html').write_text(page)
 totals={name:sum(r['best_reference_iou'][name]['10']>=.5 for r in records) for name in ('quality','alternating')};det_total=sum(r['best_reference_iou']['detector']['all']>=.5 for r in records)
 note=f'''# R43 · Public polygon candidate-rank benchmark\n\nTwelve target images were selected from two public annotated taxa before fetching image pixels, using six filename-family groups and exclusions documented in the [frozen selection](/results/r43/selection.json). Filename families do not prove sample independence, and training-data overlap for the detector is unknown. Source imagery remains in temporary local storage because the record did not specify explicit reuse terms.\n\nApply detector box prompts and a fixed point grid to the resized image, then compare quality and detector-consensus/quality alternating ranks. Each image has one selected polygon; use it only for posthoc scoring. At target mask IoU ≥ 0.5, quality top 10 matched {totals['quality']}/12 targets, alternating top 10 matched {totals['alternating']}/12, and the complete detector-prompt set matched {det_total}/12. [Inspect reference and candidate silhouettes](/results/r43/) and [all scores](/results/r43/results.json).\n\nThe selected targets may omit other scene objects, so unmatched candidates are not automatically false positives; best-IoU selection is not deployable candidate selection. These are two taxa, small and possibly related groups, with no reliable real-crossing annotations or Academy domain; the numbers are not whole-field recall, human-level performance, or a valid taxonomic benchmark. Compare fixed rules on a different, independent and rights-cleared dataset and real partial/overlap examples.\n'''
 (ROOT/'research/R43.md').write_text(note);board=ROOT/'research/board.json';d=json.loads(board.read_text())
 for task in d['tasks']:
  if task['id']=='R43':task.update(status='review',summary=f"Fixed public polygon target test: quality top 10 {totals['quality']}/12, alternating {totals['alternating']}/12 at mask IoU 0.5; not whole-field recall.",note='R43.md',result='/results/r43/')
 temp=board.with_suffix('.json.tmp');temp.write_text(json.dumps(d,indent=2)+'\n');temp.replace(board);print('Completed public polygon benchmark.',flush=True)
if __name__=='__main__':main()
