"""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/l35';SOURCE=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((SOURCE/'selection.json').read_text());download=json.loads((SOURCE/'download-report.json').read_text());previous=json.loads((SOURCE/'results.json').read_text())
 for path,key in [(SOURCE/'selection.json','selection_sha256'),(SOURCE/'results.json','r43_results_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.)
  detector_candidates=[{'id':f'det-{k}','mask':m} for k,m in enumerate(det)];ranked['combined']=interleave(detector_candidates,ranked['alternating'])
  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)}
  old=previous['records'][i-1]['best_reference_iou']
  for name in ('quality','alternating','detector'):
   for key,value in old[name].items():
    if abs(metrics[name][key]-value)>1e-6:raise ValueError('Reproduced baseline differs from frozen R43')
  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),'combined_top10_count':len(ranked['combined'][:10]),'combined_top10_overlap_pairs_08':sum(base.iou(ranked['combined'][i]['mask'],ranked['combined'][j]['mask'])>=.8 for i in range(min(10,len(ranked['combined']))) for j in range(i+1,min(10,len(ranked['combined'])))),'best_reference_iou':metrics,'seconds':time.monotonic()-t};records.append(rec)
  render(ref,ranked['combined'],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}, combined top10 {metrics['combined']['10']:.2f}",flush=True)
 payload={'format':'l35-combined-ranking-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 combined candidates. Colors denote candidates, not identities. Best target IoU: detector {m['detector']['all']:.2f} · grid top 10 {m['alternating']['10']:.2f} · combined top 10 {m['combined']['10']:.2f}.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Combined detector and grid proposals</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/r43/">Previous public benchmark</a> · <a href="/research/L35.md">Research note</a> · <a href="/results/performance/">Performance monitor</a></nav><h1>Combined detector and grid proposals</h1><p class="notice">Same twelve previously evaluated public targets as R43. One polygon per image; unannotated objects may be present, source groups may be related, and detector training data is unknown. Not a fresh real-overlap or Academy benchmark.</p><p>Interleave detector box masks with detector-supported/quality alternating grid masks, preserving all candidates. Reference annotations are used only afterward to measure the best target IoU. <a href="results.json">Full data</a> · <a href="protocol.json">Frozen settings</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','combined')};det_total=sum(r['best_reference_iou']['detector']['all']>=.5 for r in records)
 note=f'''# L35 · Combined detector and grid candidate ranking\n\nOn the same 12 public target images used in R43, interleave detector-prompted masks with alternating detector-supported/quality-ranked grid masks. Each prediction is generated without the reference; one selected polygon is used only for posthoc scoring. No cross-method masks are suppressed, so duplicates and overlap are retained.\n\nAt target IoU ≥0.5 and top-10 budget, grid quality matched {totals['quality']}/12 selected targets, grid alternating matched {totals['alternating']}/12, and combined matched {totals['combined']}/12. All detector-prompted masks matched {det_total}/12. [View silhouettes](/results/l35/) and [scores](/results/l35/results.json).\n\nThese images and the complementarity of methods were inspected before this follow-up, so this is a development result, not independent validation. Matches use the reference to choose a best candidate after prediction, not a deployable choice. Other objects may be unlabeled, model training overlap is unknown, and only two taxa are represented. Compare frozen rules at the same budgets on new independent public fields and real partials/overlaps; measure candidate burden and avoid IoU suppression that erases true overlaps.\n'''
 (ROOT/'research/L35.md').write_text(note);board=ROOT/'research/board.json';d=json.loads(board.read_text())
 for task in d['tasks']:
  if task['id']=='L35':task.update(status='review',summary=f"On 12 previously assessed public targets, combined top-10 masks matched {totals['combined']}/12; development only.",note='L35.md',result='/results/l35/')
 temp=board.with_suffix('.json.tmp');temp.write_text(json.dumps(d,indent=2)+'\n');temp.replace(board);print('Completed combined proposal comparison.',flush=True)
if __name__=='__main__':main()
