"""Rank SAM grid masks with detector consensus on controlled synthetic scenes."""
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
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r41';ALT=ROOT/'results/r3/scan-survey/field-05.png';SOURCE=ROOT/'results/r21/training-selection.json';BACKGROUND=ROOT/'results/r3/scan-survey/field-03.png';INDICES=(1,9,3,10,4,11)

def extract21(entry,index):
 path=Path('/tmp/diatom-adaptation')/f'{index:02d}.jpg';annotations=Path('/tmp/diatom-mask-coco')/entry['annotation_file'];data=json.loads(annotations.read_text());ann=next(x for x in data['annotations'] if x['id']==entry['annotation_id'] and x['image_id']==entry['image']['id']);image=np.asarray(Image.open(path).convert('RGB'));h,w=image.shape[:2];mask=np.zeros((h,w),'uint8')
 for poly in ann['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 annotation')
 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];scale=150/max(mask.shape);size=(max(1,round(mask.shape[1]*scale)),max(1,round(mask.shape[0]*scale)));crop=cv2.resize(crop,size,interpolation=cv2.INTER_AREA);mask=cv2.resize(mask,size,interpolation=cv2.INTER_NEAREST)>0
 return crop,mask,{'annotation_id':ann['id'],'image_sha256':base.sha(path),'annotation_sha256':base.sha(annotations)}

def interleave(supported,quality):
 out=[];seen=set()
 for i in range(max(len(supported),len(quality))):
  for ranking in (supported,quality):
   if i<len(ranking) and ranking[i]['id'] not in seen:out.append(ranking[i]);seen.add(ranking[i]['id'])
 return out

def main():
 protocol=json.loads((OUT/'protocol.json').read_text())
 for path,key in [(SOURCE,'selection_sha256'),(BACKGROUND,'background_sha256'),(ALT,'alternate_background_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(Path(__file__),'script_sha256')]:
  if base.sha(path)!=protocol[key]:raise ValueError('Frozen input changed: '+key)
 source=json.loads(SOURCE.read_text())['selection'];objects=[extract21(source[i-1],i) for i in INDICES]
 if [x[2] for x in objects]!=protocol['source_objects']:raise ValueError('Frozen source objects changed')
 if (OUT/'results.json').exists():raise FileExistsError('Existing experiment')
 backgrounds=[np.asarray(Image.open(p).convert('RGB').crop((128,128,640,640))).copy() for p in (BACKGROUND,ALT)]
 torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 for variant in ('original','alternate'):
  for pair in range(3):
   for condition in ('separated','crossing'):
    start=time.monotonic();a,am,_=objects[2*pair];b,bm,_=objects[2*pair+1]
    if variant=='alternate':b=np.rot90(b).copy();bm=np.rot90(bm).copy()
    canvas=backgrounds[0 if variant=='original' else 1].copy();f1=np.zeros((512,512),bool);f2=np.zeros((512,512),bool)
    centers=((141,256),(371,256)) if condition=='separated' else ((256,256),(256,256));base.paste(canvas,f1,a,am,*centers[0]);base.paste(canvas,f2,b,bm,*centers[1]);refs=[f1&~f2,f2]
    if min(int(x.sum()) for x in refs)<50:raise ValueError('Almost fully hidden reference')
    bgr=cv2.cvtColor(canvas,cv2.COLOR_RGB2BGR);prediction=detector.predict(bgr,imgsz=512,conf=.05,device='cpu',verbose=False)[0];boxes=prediction.boxes.xyxy.cpu().numpy().tolist() if prediction.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:
     out=predictor(bboxes=boxes,verbose=False)[0];det=[] if out.masks is None else [x.astype(bool) for x in out.masks.data.cpu().numpy()]
    else:det=[]
    points=[(x,y) for y in range(16,512,32) for x in range(16,512,32)];raw=[]
    for start_index in range(0,len(points),12):
     batch=points[start_index:start_index+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 grid result')
     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 x:-x['quality']):
     if all(base.iou(c['mask'],k['mask'])<.8 for k in kept):kept.append(c)
    for c in kept:c['support']=max((base.iou(c['mask'],m) for m in det),default=0.)
    supported=sorted(kept,key=lambda c:(-(c['support']>=.25),-c['quality']))
    # Alternating the two orders retains high-quality unsupported proposals.
    combined=interleave(supported,kept);methods={'quality':kept,'consensus':supported,'alternating':combined};budgets={}
    for method,candidates in methods.items():budgets[method]={str(n):base.assign(refs,[c['mask'] for c in candidates[:n]],.5) for n in (5,10,20)}
    records.append({'variant':variant,'pair':pair+1,'condition':condition,'overlap_pixels':int((f1&f2).sum()),'detector_boxes':len(boxes),'grid_candidates':len(kept),'detector_supported':sum(c['support']>=.25 for c in kept),
       'budgets':budgets,'seconds':time.monotonic()-start})
    print(f"{variant} pair {pair+1} {condition}: grid {len(kept)}, detector-supported {records[-1]['detector_supported']}; top 10 quality {budgets['quality']['10']['matched']}/2, consensus {budgets['consensus']['10']['matched']}/2, alternating {budgets['alternating']['10']['matched']}/2",flush=True)
 data={'format':'r41-consensus-ranking-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,'warning':'Different previously inspected public source polygons; two previously viewed backgrounds and synthetic opaque overlaps. Detector overlap is not proof of a diatom; references used only for scoring.'};(OUT/'results.json').write_text(json.dumps(data,indent=2)+'\n')
 rows=''.join(f"<tr><td>{r['variant']} · {r['pair']} · {r['condition']}</td><td>{r['budgets']['quality']['10']['matched']}/2</td><td>{r['budgets']['consensus']['10']['matched']}/2</td><td>{r['budgets']['alternating']['10']['matched']}/2</td><td>{r['detector_supported']}/{r['grid_candidates']}</td></tr>" for r in records)
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Detector and grid agreement</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}td,th{padding:8px;border-bottom:1px solid #cad9cf;text-align:left}</style><main><nav><a href="/results/r38/">Earlier R38 scenes (different cutouts)</a> · <a href="/research/R41.md">Research note</a> · <a href="/results/performance/">Performance monitor</a></nav><h1>Detector and grid agreement</h1><p class="notice">Twelve synthetic scenes use six previously examined annotated cutouts not used in L32, and two real but unverified backgrounds. Alternative layouts are not independent biological samples or proof of real-slide accuracy.</p><p>Quality ranks SAM grid masks by its predicted score. Consensus prioritizes grid masks overlapping a detector-prompted mask at IoU ≥ 0.25. Alternating interleaves both rankings, retaining unsupported grid proposals. Results are scored after prediction using known visible synthetic masks at IoU ≥ 0.5. Each reference matches at most one candidate; detector agreement is not proof of correctness.</p><table><tr><th>Scene</th><th>Quality top 10</th><th>Consensus top 10</th><th>Alternating top 10</th><th>Detector-supported / all</th></tr>{ROWS}</table><p><a href="results.json">Raw results, budgets and runtime</a> · <a href="protocol.json">Frozen settings</a></p></main></html>'''.replace('{ROWS}',rows);(OUT/'index.html').write_text(page)
 lines=['# R41 · Consensus ranking on different source objects','','Generate dense grid candidates with fixed SAM quality and NMS settings; compare quality ranking with detector-mask consensus at IoU ≥0.25 and an alternating ranking that retains unsupported grid masks. All three use identical candidate pools; references are used only for posthoc matching at visible IoU 0.5. Six original and six alternate-layout scenes use six selected public source cutouts distinct from L32; the alternate uses another previously viewed Academy field background and a 90-degree rotation of the second object. Neither set is independent.','', '| Variant | Pair | Condition | Quality top 10 | Consensus top 10 | Alternating top 10 | Detector-supported / all |','|---|---:|---|---:|---:|---:|---:|']
 for r in records:
  b=r['budgets'];lines.append(f"| {r['variant']} | {r['pair']} | {r['condition']} | {b['quality']['10']['matched']}/2 | {b['consensus']['10']['matched']}/2 | {b['alternating']['10']['matched']}/2 | {r['detector_supported']}/{r['grid_candidates']} |")
 lines+=['','[Visual result table](/results/r41/) · [raw data and timings](/results/r41/results.json). The selected cutouts were used in earlier decoder-adaptation work, but the base MobileSAM checkpoint is used here. The detector may miss specimens or detect background; consensus can prioritize false positives and demote valid detector-unsupported objects. Images are opaque synthetic composites on only two backgrounds; source images, classes, prompt settings, and NMS are not independent of earlier exploration. Unknown background specimens preclude false-positive counts. These numbers are not evidence of real-slide recall, biological sample independence, or human-level segmentation.','','**Next:** If a rule appears promising, freeze it and test on genuinely new synthetic specimens and more backgrounds, then assess provisional real-field instances after automated experiments; keep unsupported hypotheses and evaluate partial and overlapping cases.']
 (ROOT/'research/R41.md').write_text('\n'.join(lines)+'\n');board=ROOT/'research/board.json';d=json.loads(board.read_text())
 for t in d['tasks']:
  if t['id']=='R41':t.update(status='review',summary='Compared quality, detector-consensus, and alternating grid ranking on 12 related synthetic scenes; not real-slide accuracy.',note='R41.md',result='/results/r41/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed fresh-source consensus comparison.',flush=True)
if __name__=='__main__':main()
