"""Compare fixed candidate rankings against selected Menne COCO regions."""
import collections,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
import r38_synthetic_crossings as base
import r41_consensus_fresh_sources as ranker
from r41_consensus_fresh_sources import interleave
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r44';COCO=Path('/tmp/diatom-r44-menne/test.all.coco.json');IMAGES=Path('/tmp/diatom-r44-menne/images')

def match(refs,candidates,threshold):
 if not refs or not candidates:return {'matched':0,'reference_count':len(refs),'candidate_count':len(candidates),'ious':[]}
 if len(refs)>12:raise ValueError('Too many references for exact subset matching')
 # State is a bitset of matched references. Each prediction is visited once;
 # within a state retain the assignment with the highest total IoU.
 states={0:(0.0,[])}
 for candidate in candidates:
  scores=[base.iou(ref,candidate['mask']) for ref in refs];next_states=dict(states)
  for bits,(total,values) in states.items():
   for idx,value in enumerate(scores):
    if bits&(1<<idx) or value<threshold:continue
    new=bits|(1<<idx);proposed=(total+value,values+[value]);old=next_states.get(new)
    if old is None or proposed[0]>old[0]:next_states[new]=proposed
  states=next_states
 _,(_,ious)=max(states.items(),key=lambda item:(item[0].bit_count(),item[1][0]))
 return {'matched':len(ious),'reference_count':len(refs),'candidate_count':len(candidates),'ious':ious}

def overlay(image,refs,candidates):
 panel=Image.new('RGB',(1152,410),'#f3f6ef');draw=ImageDraw.Draw(panel)
 for col,(label,masks) in enumerate([('COCO target regions',refs),('Grid alternating top 10',[c['mask'] for c in candidates['grid'][:10]]),('Combined top 10',[c['mask'] for c in candidates['combined'][:10]])]):
  im=image.convert('RGBA');layer=Image.new('RGBA',image.size,(0,0,0,0))
  for k,mask in enumerate(masks):
   color=['#00cc99','#ed8860','#9275ea','#e8c042'][k%4];c=Image.new('RGBA',image.size,color);c.putalpha(Image.fromarray(mask.astype('uint8')*100));layer=Image.alpha_composite(layer,c)
  im=Image.alpha_composite(im,layer).convert('RGB').resize((360,360));panel.paste(im,(col*384+10,40));draw.text((col*384+10,8),label,fill='#203a38')
 return panel

def main():
 p=json.loads((OUT/'protocol.json').read_text());s=json.loads((OUT/'selection.json').read_text());d=json.loads((OUT/'download-report.json').read_text())
 for path,key in [(OUT/'selection.json','selection_sha256'),(COCO,'annotation_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(Path(base.__file__),'base_script_sha256'),(Path(ranker.__file__),'ranking_script_sha256'),(Path(__file__),'script_sha256')]:
  if base.sha(path)!=p[key]:raise ValueError('Frozen input changed: '+key)
 if d['selection_sha256']!=p['selection_sha256'] or len(d['images'])!=len(s['selection']):raise ValueError('Download mismatch')
 if (OUT/'results.json').exists():raise FileExistsError('Existing result')
 coco=json.loads(COCO.read_text());annotations=collections.defaultdict(list)
 for a in coco['annotations']:annotations[a['image_id']].append(a)
 manifest={r['id']:r for r in d['images']};torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 for n,row in enumerate(s['selection'],1):
  start=time.monotonic();path=IMAGES/row['local_file'];item=manifest.get(row['id'])
  if not item or base.sha(path)!=item['sha256']:raise ValueError('Image hash mismatch')
  image=Image.open(path).convert('RGB')
  if image.size!=(512,512):raise ValueError('Unexpected tile size')
  refs=[]
  for ann in annotations[row['id']]:
   mask=np.zeros((512,512),'uint8')
   for poly in ann['segmentation']:cv2.fillPoly(mask,[np.rint(np.asarray(poly).reshape(-1,2)).astype('int32')],1)
   if not mask.any():raise ValueError('Empty target polygon')
   refs.append(mask.astype(bool))
  if len(refs)!=row['annotation_count']:raise ValueError('Annotation count changed')
  bgr=cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR);result=detector.predict(bgr,imgsz=512,conf=.05,device='cpu',verbose=False)[0];boxes=result.boxes.xyxy.cpu().numpy().tolist() if result.boxes is not None else []
  predictor=Predictor(overrides={'model':str(base.SAM),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});predictor.set_image(bgr)
  if boxes:
   pred=predictor(bboxes=boxes,verbose=False)[0];det=[] if pred.masks is None else [{'id':f'det-{i}','mask':m.astype(bool)} for i,m in enumerate(pred.masks.data.cpu().numpy())]
  else:det=[]
  points=[(x,y) for y in range(32,512,64) for x in range(32,512,64)];raw=[]
  for j in range(0,len(points),12):
   batch=points[j:j+12];pred=predictor(points=[[[x,y]] for x,y in batch],labels=[[1] for _ in batch],verbose=False)[0]
   if pred.masks is None or len(pred.masks.data)!=len(batch):raise ValueError('Unexpected prompt batch')
   for point,m,score in zip(batch,pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
    mask=m.astype(bool);area=int(mask.sum())
    if 300<=area<=50000 and float(score)>=.6:raw.append({'id':len(raw),'mask':mask,'quality':float(score)})
  grid=[]
  for c in sorted(raw,key=lambda c:-c['quality']):
   if all(base.iou(c['mask'],x['mask'])<.8 for x in grid):grid.append(c)
  for c in grid:c['support']=max((base.iou(c['mask'],v['mask']) for v in det),default=0.)
  supported=sorted(grid,key=lambda c:(-(c['support']>=.25),-c['quality']));alternating=interleave(supported,grid);combined=interleave(det,alternating);methods={'grid':alternating,'combined':combined}
  scores={name:{str(b):{'iou05':match(refs,candidates[:b],.5),'iou075':match(refs,candidates[:b],.75)} for b in (5,10,20)} for name,candidates in methods.items()}
  scores['detector_all']={'iou05':match(refs,det,.5),'iou075':match(refs,det,.75)}
  rec={'id':row['id'],'split':row['split'],'slide':row['slide'],'category':row['category'],'source_sha256':base.sha(path),'reference_count':len(refs),'detector_count':len(det),'grid_count':len(grid),'combined_count':len(combined),'scores':scores,'seconds':time.monotonic()-start};records.append(rec)
  overlay(image,refs,methods).save(OUT/f'field-{n:02d}.jpg',quality=88)
  print(f"{n}/{len(s['selection'])} {row['split']} {row['slide']} refs {len(refs)} grid10 {scores['grid']['10']['iou05']['matched']} combined10 {scores['combined']['10']['iou05']['matched']}",flush=True)
 payload={'format':'r44-menne-field-result-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,'warning':'Selected nonrandom test tiles from six slides; missing fragments and dense aggregates are excluded by source labeling. Source-area splits do not guarantee independence, and detector training overlap is unknown. Not Academy or human-level performance.'};(OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n')
 cards=[]
 for n,r in enumerate(records,1):
  q=r['scores'];cards.append(f"<article><h3>{r['slide']} · {r['split']} · {r['category']}</h3><img src=\"field-{n:02d}.jpg\" alt=\"COCO reference, grid and combined candidate overlays\"><p>Annotated regions: {r['reference_count']} · grid top 10 matched: {q['grid']['10']['iou05']['matched']} · combined top 10 matched: {q['combined']['10']['iou05']['matched']}. Candidates can be debris, other unannotated diatoms or duplicates; colors indicate separate masks.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>River Menne crowded-field test</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/R44.md">Research note</a></nav><h1>River Menne public-field segmentation</h1><p class="notice">Eighteen intentionally selected source tiles from six slide names, two annotated multi-object and one annotation-empty per slide. The source excludes many fragments and dense aggregates. Colored areas are predictions or source target regions, not necessarily all diatoms. Results do not establish Academy or human-level accuracy.</p><p>Three panels: source annotations, first ten grid candidates, first ten combined candidates. References are used only for scoring after proposals. Matches at IoU ≥0.5 are one-to-one. Source images and annotations: Kloster, Burfeid-Castellanos and Beszteri, <a href="https://doi.org/10.5281/zenodo.7079005">River Menne dataset</a>, <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>; masks overlaid and images resized. <a href="results.json">Full scores and provenance</a> · <a href="protocol.json">Frozen protocol</a></p>{CARDS}</main></html>'''.replace('{CARDS}',''.join(cards));(OUT/'index.html').write_text(page)
 lines=['# R44 · River Menne public-field validation','','Eighteen preselected CC BY 4.0 source tiles from six slide names: two with at least two labeled regions and one annotation-empty per slide. Three slide names are marked development and three held out for this public diagnostic. Named test tiles come from spatial subsections of the source slides; detector training overlap and sample independence remain unverified. The source excludes many <75% fragments and dense aggregates, so its reference is not complete for this project.','', '| Split | Labeled regions | Grid top 10 matched | Combined top 10 matched | Annotation-empty fields |','|---|---:|---:|---:|---:|']
 for split in ('development','held_out_public'):
  x=[r for r in records if r['split']==split];lines.append(f"| {split} | {sum(r['reference_count'] for r in x)} | {sum(r['scores']['grid']['10']['iou05']['matched'] for r in x)} | {sum(r['scores']['combined']['10']['iou05']['matched'] for r in x)} | {sum(r['reference_count']==0 for r in x)} |")
 lines+=['','[Annotated fields and model overlays](/results/r44/) · [full scoring data](/results/r44/results.json) · [selection](/results/r44/selection.json). Matching uses annotations after prediction at IoU ≥0.5, one-to-one. The selected set is deliberately enriched for multi-object fields and empty-label fields; its aggregate is not population recall. Unmatched candidates or those on empty-label fields cannot be called false positives: excluded partial valves and aggregates may be present. Source labels may merge touching or overlapping cells. The images are not Academy slides and these numbers do not establish human-level segmentation.']
 (ROOT/'research/R44.md').write_text('\n'.join(lines)+'\n');board=ROOT/'research/board.json';bd=json.loads(board.read_text())
 for task in bd['tasks']:
  if task['id']=='R44':task.update(status='review',summary='Fixed grid and combined proposals evaluated on 18 preselected public tiles; source excludes many fragments and aggregates.',note='R44.md',result='/results/r44/')
 temp=board.with_suffix('.json.tmp');temp.write_text(json.dumps(bd,indent=2)+'\n');temp.replace(board);print('Completed River Menne field benchmark.',flush=True)
if __name__=='__main__':main()
