"""Evaluate fixed candidate policies on structurally separable public masks."""
import hashlib,json,sys,time,xml.etree.ElementTree as ET
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
import r44_score_fields as matchlib
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r48';TEMP=Path('/tmp/diatom-r47-public');XMLS=Path('/tmp/diatom-r46-public/xmls');sys.path.insert(0,str(ROOT/'diatom_pilot'))
from adaptive_grid import select_extra
from mask_component_guard import candidates_from_binary

def overlay(image,refs,methods):
 panel=Image.new('RGB',(1152,322),'#f3f6ef');draw=ImageDraw.Draw(panel)
 for col,(label,masks) in enumerate([('Source component candidates',refs),('Sparse combined top 10',[x['mask'] for x in methods['64'][:10]]),('160-point combined top 10',[x['mask'] for x in methods['uniform'][:10]])]):
  img=image.convert('RGBA');layer=Image.new('RGBA',image.size,(0,0,0,0))
  for i,m in enumerate(masks):
   c=Image.new('RGBA',image.size,['#00cc99','#ed8860','#9275ea','#e8c042'][i%4]);c.putalpha(Image.fromarray(m.astype('uint8')*100));layer=Image.alpha_composite(layer,c)
  panel.paste(Image.alpha_composite(img,layer).convert('RGB').resize((360,270)),(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());selection=json.loads((OUT/'selection.json').read_text());download=json.loads((OUT/'image-download.json').read_text())
 for path,key in [(OUT/'selection.json','selection_sha256'),(ROOT/'results/r47/results.json','source_audit_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(ROOT/'diatom_pilot/adaptive_grid.py','point_policy_sha256'),(ROOT/'diatom_pilot/mask_component_guard.py','component_guard_sha256'),(Path(matchlib.__file__),'matching_code_sha256'),(Path(ranker.__file__),'ranking_code_sha256'),(Path(__file__),'script_sha256')]:
  if base.sha(path)!=p[key]:raise ValueError('Frozen input changed: '+key)
 if download['selection_sha256']!=p['selection_sha256']:raise ValueError('Image selection mismatch')
 if (OUT/'results.json').exists():raise FileExistsError('Existing scoring result')
 imgs={x['id']:x for x in download['images']};torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 for i,row in enumerate(selection['selection'],1):
  start=time.monotonic();ident=row['id'];imgpath=TEMP/'images'/f'{ident}.png';maskpath=TEMP/f'{ident}.png';xmlpath=XMLS/f'{ident}.xml'
  if base.sha(imgpath)!=imgs[ident]['sha256'] or base.sha(maskpath)!=row['mask_sha256'] or base.sha(xmlpath)!=row['xml_sha256']:raise ValueError('Image or annotation hash mismatch')
  image=Image.open(imgpath).convert('RGB');rgb=np.asarray(Image.open(maskpath).convert('RGB'));h,w=rgb.shape[:2]
  if image.size!=(w,h) or not (((rgb==0).all(axis=2))|((rgb==255).all(axis=2))).all():raise ValueError('Mask/image format mismatch')
  xml=ET.fromstring(xmlpath.read_bytes());boxes=[[int(o.findtext('./bbox/'+k)) for k in ('xmin','ymin','xmax','ymax')] for o in xml.findall('./objects/object')]
  source=(rgb!=0).any(axis=2);structural=candidates_from_binary(source,boxes,minimum_area=20,containment=.98)
  if structural['status']!='structural_match':raise ValueError('Previously selected structural case no longer passes')
  _,labels,_,_=cv2.connectedComponentsWithStats(source.astype('uint8'),connectivity=8)
  refs=[cv2.resize((labels==entry['component_label']).astype('uint8'),(768,576),interpolation=cv2.INTER_NEAREST)>0 for entry in structural['instances']]
  if any(not x.any() for x in refs):raise ValueError('Reference vanished under resize')
  image=image.resize((768,576),Image.Resampling.LANCZOS);array=cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR);pred=detector.predict(array,imgsz=768,conf=.05,device='cpu',verbose=False)[0];dets=pred.boxes.xyxy.cpu().numpy().tolist() if pred.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(array)
  if dets:
   pred=predictor(bboxes=dets,verbose=False)[0];det=[] if pred.masks is None else [{'id':f'det-{j}','mask':m.astype(bool)} for j,m in enumerate(pred.masks.data.cpu().numpy())]
  else:det=[]
  def points(spacing):return [(x,y) for y in range(spacing//2,576,spacing) for x in range(spacing//2,768,spacing)]
  def infer(points):
   result={}
   for j in range(0,len(points),12):
    batch=points[j:j+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 prompt batch')
    for pt,m,score in zip(batch,out.masks.data.cpu().numpy(),out.boxes.conf.cpu().numpy()):
     mask=m.astype(bool);area=int(mask.sum())
     if 300<=area<=50000 and float(score)>=.6:result[pt]={'id':f'pt-{pt[0]}-{pt[1]}','mask':mask,'quality':float(score)}
   return result
  coarsepts=points(64);densepts=points(32);coarse=infer(coarsepts)
  # Point choices use model predictions only; references never enter selection.
  padded=[np.pad(c['mask'],((0,192),(0,0))) for c in coarse.values()];extra=select_extra(densepts,dets,padded,size=768,extra_count=162,guided_cap=81);dense=infer(densepts)
  pointsets={'64':coarsepts,'32':densepts,'uniform':coarsepts+extra['uniform'],'adaptive':coarsepts+extra['adaptive']};variants={};rankings={}
  for name,pts in pointsets.items():
   available={**coarse,**dense};raw=[available[x] for x in pts if x in available];kept=[]
   for c in sorted(raw,key=lambda z:-z['quality']):
    if all(base.iou(c['mask'],q['mask'])<.8 for q in kept):kept.append(c)
   for c in kept:c['support']=max((base.iou(c['mask'],d['mask']) for d in det),default=0.)
   supported=sorted(kept,key=lambda c:(-(c['support']>=.25),-c['quality']));grid=ranker.interleave(supported,kept);combined=ranker.interleave(det,grid);rankings[name]=combined
   variants[name]={'prompts':len(pts),'reference_with_interior_point':sum(any(ref[y,x] for x,y in pts) for ref in refs),'grid_candidates':len(kept),
      'all_candidates':matchlib.match(refs,combined,.5),'budgets':{str(n):{'iou05':matchlib.match(refs,combined[:n],.5),'iou075':matchlib.match(refs,combined[:n],.75)} for n in (5,10,20)}}
  records.append({'id':ident,'reference_count':len(refs),'source_image_sha256':base.sha(imgpath),'source_mask_sha256':row['mask_sha256'],'guided_count':extra['guided_count'],'variants':variants,'seconds_all_540_prompt_replay':time.monotonic()-start})
  overlay(image,refs,rankings).save(OUT/f'field-{i:02d}.jpg',quality=87)
  print(f"{i}/{len(selection['selection'])} case {ident}, references {len(refs)}: sparse top10 {variants['64']['budgets']['10']['iou05']['matched']}, uniform {variants['uniform']['budgets']['10']['iou05']['matched']}, dense {variants['32']['budgets']['10']['iou05']['matched']}",flush=True)
 result={'format':'r48-structural-mask-results-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,
  'warning':'Source binary connected components were structurally associated to nonintersecting boxes, not independently verified biological instance masks. Reference masks were inspected before images. Sample relationships, annotation completeness, training overlap and real overlaps remain unknown.'};(OUT/'results.json').write_text(json.dumps(result,indent=2)+'\n')
 cards=[]
 for i,r in enumerate(records,1):
  v=r['variants'];cards.append(f"<article><h3>Case {i:02d}</h3><img src=\"field-{i:02d}.jpg\" alt=\"Source mask components and predicted candidate overlays\"><p>Structural reference components: {r['reference_count']} · sparse top-10 matches: {v['64']['budgets']['10']['iou05']['matched']} · 160-point unconditioned: {v['uniform']['budgets']['10']['iou05']['matched']} · dense: {v['32']['budgets']['10']['iou05']['matched']}.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Structural-mask proposal comparison</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/r47/">Structural mask audit</a> · <a href="/research/R48.md">Research note</a> · <a href="/results/performance/">Performance monitor</a></nav><h1>Structural-mask proposal comparison</h1><p class="notice">Twenty-four public cases passed a strict component/box rule; the source masks were inspected before image retrieval. Most cases have one source box. The rule rejects intersecting boxes, so this is not an overlap benchmark or proof of correct biological instances. Biological sample independence and annotation completeness are unknown.</p><p>Panels show derived source components, sparse-grid predictions and unconditioned 160-point predictions. Candidate selection does not use reference masks; one-to-one matching uses them afterward. All 540 possible points were computed to replay policies; latency reduction is not measured. <a href="results.json">Scores</a> · <a href="protocol.json">Frozen protocol</a></p><p>Source: Hüseyin Gündüz, <a href="https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset">Diatom Dataset</a>, <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a>. Images resized and overlaid; derivatives shared noncommercially under the same license.</p>{CARDS}</main></html>'''.replace('{CARDS}',''.join(cards));(OUT/'index.html').write_text(page)
 lines=['# R48 · Structural-mask proposal comparison','','Twenty-four public cases selected before source image pixels were downloaded, after their binary masks passed the strict R47 component-to-box structural rule. Twenty-one had a single box; three had two or three. Intersecting-box cases are rejected by construction, so this is not an overlap test. Biological sample independence, image-label completeness and detector training overlap remain unknown.','', '| Policy | Prompts per field | Reference components | Top 10 IoU ≥0.5 matches | Top 10 IoU ≥0.75 matches | Total retained grid masks |','|---|---:|---:|---:|---:|---:|']
 for name,title in [('64','sparse'),('uniform','unconditioned'),('adaptive','adaptive'),('32','dense')]:
  vals=[r['variants'][name] for r in records];lines.append(f"| {title} | {vals[0]['prompts']} | {sum(r['reference_count'] for r in records)} | {sum(v['budgets']['10']['iou05']['matched'] for v in vals)} | {sum(v['budgets']['10']['iou075']['matched'] for v in vals)} | {sum(v['grid_candidates'] for v in vals)} |")
 lines+=['','[Field overlays](/results/r48/) · [full data](/results/r48/results.json) · [selection](/results/r48/selection.json). One-to-one matches use derived source component masks after inference. The structural rule does not prove source outlines or labels are correct, and unannotated objects cannot be treated as false positives. All 540 point prompts were precomputed for policy replay, so no latency reduction is established. The results do not establish Academy or human-level segmentation and do not evaluate true overlaps.','', 'Source: Hüseyin Gündüz, [Diatom Dataset](https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset), CC BY-NC-SA 4.0; resized and overlaid images shared noncommercially under the same license.']
 (ROOT/'research/R48.md').write_text('\n'.join(lines)+'\n');board=ROOT/'research/board.json';d=json.loads(board.read_text())
 for task in d['tasks']:
  if task['id']=='R48':task.update(status='review',summary='Compared fixed prompt budgets on 24 source cases with structurally separable binary components; not an overlap or independent biological-sample test.',note='R48.md',result='/results/r48/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed structural-mask proposal comparison.',flush=True)
if __name__=='__main__':main()
