"""Compare fixed prompt budgets on inspected multi-object public fields.

Box matches assess proposed extent only; source binary masks do not establish
instance masks for overlapping specimens. References are scoring-only.
"""
import json,math,sys,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
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l38';SRC=ROOT/'results/r46';TEMP=Path('/tmp/diatom-r46-public');sys.path.insert(0,str(ROOT/'diatom_pilot'))
from adaptive_grid import select_extra

def box_iou(a,b):
 x=max(0,min(a[2],b[2])-max(a[0],b[0]));y=max(0,min(a[3],b[3])-max(a[1],b[1]));inter=x*y;union=(a[2]-a[0])*(a[3]-a[1])+(b[2]-b[0])*(b[3]-b[1])-inter
 return inter/union if union>0 else 0.
def mask_box(m):
 y,x=np.where(m)
 return [int(x.min()),int(y.min()),int(x.max()+1),int(y.max()+1)] if len(x) else None

def match_boxes(refs,candidates,threshold=.5):
 if len(refs)>12:raise ValueError('Too many box references for exact matching')
 states={0:(0.,[])}
 for c in candidates:
  box=mask_box(c['mask'])
  if box is None:continue
  next_states=dict(states)
  for bits,(total,ious) in states.items():
   for i,r in enumerate(refs):
    if bits&(1<<i):continue
    value=box_iou(r,box)
    if value<threshold:continue
    new=bits|(1<<i);proposal=(total+value,ious+[value]);old=next_states.get(new)
    if old is None or proposal[0]>old[0]:next_states[new]=proposal
  states=next_states
 _,(_,ious)=max(states.items(),key=lambda t:(t[0].bit_count(),t[1][0]))
 return {'matched':len(ious),'reference_boxes':len(refs),'candidate_count':len(candidates),'matched_box_ious':ious}

def semantic_agreement(source,candidates):
 union=np.zeros(source.shape,bool)
 for c in candidates:union|=c['mask']
 return base.iou(source,union)

def panel(image,source,refs,variants):
 canvas=Image.new('RGB',(1152,322),'#f3f6ef');draw=ImageDraw.Draw(canvas)
 for col,(label,masks) in enumerate([('Source foreground + boxes',[source]),('64px candidates · top 10',[x['mask'] for x in variants['64'][:10]]),('32px candidates · top 10',[x['mask'] for x in variants['32'][:10]])]):
  im=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)
  im=Image.alpha_composite(im,layer).convert('RGB')
  if col==0:
   d=ImageDraw.Draw(im)
   for r in refs:d.rectangle(tuple(r),outline='#f3ac29',width=2)
  im=im.resize((360,270));canvas.paste(im,(col*384+10,40));draw.text((col*384+10,8),label,fill='#203a38')
 return canvas

def main():
 p=json.loads((OUT/'protocol.json').read_text());sel=json.loads((SRC/'case-selection.json').read_text());box=json.loads((SRC/'box-audit.json').read_text());download=json.loads((SRC/'case-download.json').read_text())
 for path,key in [(SRC/'case-selection.json','selection_sha256'),(SRC/'box-audit.json','boxes_sha256'),(SRC/'case-download.json','downloads_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(ROOT/'diatom_pilot/adaptive_grid.py','selection_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 (OUT/'results.json').exists():raise FileExistsError('Existing result')
 meta={x['id']:x for x in box['records']};files={x['id']:x for x in download['records']};torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 for i,row in enumerate(sel['selection'],1):
  start=time.monotonic();ident=row['id'];info=meta[ident];imgs=TEMP/'images'/f'{ident}.png';masks=TEMP/'annotations'/f'{ident}.png'
  if base.sha(imgs)!=files[ident]['files']['images']['sha256'] or base.sha(masks)!=files[ident]['files']['annotations']['sha256']:raise ValueError('Input hash mismatch')
  image=Image.open(imgs).convert('RGB');source=np.asarray(Image.open(masks).convert('RGB'));w,h=image.size
  if (w,h)!=tuple(info['size']) or source.shape[:2]!=(h,w):raise ValueError('Input dimensions mismatch')
  image=image.resize((768,576),Image.Resampling.LANCZOS);source=cv2.resize(((source!=0).any(axis=2)).astype('uint8'),(768,576),interpolation=cv2.INTER_NEAREST)>0
  refs=[[r['box'][0]*768/w,r['box'][1]*576/h,r['box'][2]*768/w,r['box'][3]*576/h] for r in info['objects']]
  arr=cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR);pred=detector.predict(arr,imgsz=768,conf=.05,device='cpu',verbose=False)[0];boxes=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(arr)
  if boxes:
   out=predictor(bboxes=boxes,verbose=False)[0];det=[] if out.masks is None else [{'id':f'det-{j}','mask':m.astype(bool)} for j,m in enumerate(out.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(pts):
   result={}
   for k in range(0,len(pts),12):
    batch=pts[k:k+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 output')
    for pt,m,score in zip(batch,out.masks.data.cpu().numpy(),out.boxes.conf.cpu().numpy()):
     m=m.astype(bool);area=int(m.sum())
     if 300<=area<=50000 and float(score)>=.6:result[pt]={'id':f'pt-{pt[0]}-{pt[1]}','mask':m,'quality':float(score)}
   return result
  coarsepts=points(64);densepts=points(32);coarse=infer(coarsepts)
  # Reference boxes and source foreground never enter this selection call.
  padded=[np.pad(c['mask'],((0,192),(0,0))) for c in coarse.values()];choice=select_extra(densepts,boxes,padded,size=768,extra_count=162,guided_cap=81);dense=infer(densepts)
  pointsets={'64':coarsepts,'32':densepts,'uniform':coarsepts+choice['uniform'],'adaptive':coarsepts+choice['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'],x['mask'])<.8 for x 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),'grid_candidates':len(kept),'box_matches':{str(n):match_boxes(refs,combined[:n]) for n in (5,10,20)},
     'all_box_matches':match_boxes(refs,combined),'selected_foreground_union_iou_top10':semantic_agreement(source,combined[:10])}
  rec={'id':ident,'stratum':row['stratum'],'source_boxes':len(refs),'detector_masks':len(det),'guided_count':choice['guided_count'],
       'variants':variants,'seconds_full_540_prompt_replay':time.monotonic()-start};records.append(rec)
  panel(image,source,refs,rankings).save(OUT/f'field-{i:02d}.jpg',quality=88)
  print(f"{i}/8 {row['stratum']} boxes {len(refs)}: 64px top10 {variants['64']['box_matches']['10']['matched']}; 32px top10 {variants['32']['box_matches']['10']['matched']}; uniform/adaptive {variants['uniform']['box_matches']['10']['matched']}/{variants['adaptive']['box_matches']['10']['matched']}",flush=True)
 result={'format':'l38-real-multiobject-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,'warning':'Inspected nonrandom fields with partial semantic annotations; box matches do not prove instance masks. Mask union IoU is not whole-field accuracy.'};(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} · {r['stratum'].replace('_',' ')}</h3><img src=\"field-{i:02d}.jpg\" alt=\"Source foreground and candidate overlays\"><p>Source boxes: {r['source_boxes']} · box matches in top 10: sparse {v['64']['box_matches']['10']['matched']}, dense {v['32']['box_matches']['10']['matched']}, unconditioned {v['uniform']['box_matches']['10']['matched']}, adaptive {v['adaptive']['box_matches']['10']['matched']}.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Real multi-object proposal diagnostic</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/r46/">Source mask/box audit</a> · <a href="/research/L38.md">Research note</a> · <a href="/results/performance/">Performance monitor</a></nav><h1>Real multi-object proposal diagnostic</h1><p class="notice">Eight previously inspected public fields; source annotations are binary foreground unions plus per-object boxes. A predicted mask's bounding box can match a source box while its outline is wrong. Neither box matching nor similarity to selected foreground proves instance-mask accuracy or real overlap recovery.</p><p>Left: source foreground and boxes. Middle: first ten sparse-grid combined candidates. Right: first ten dense-grid combined candidates. Uniform/adaptive policies use 270 prompts each; all 540 potential points were computed for replay. Unlabeled image content is not a verified negative. <a href="results.json">Full data</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=['# L38 · Real multi-object box and selected-foreground diagnostic','','Eight previously inspected Gündüz fields, four with intersecting annotated boxes and four multi-object controls. Compare 108 coarse points, 432 dense points, and two 270-point policies (108 coarse + 162 deterministic unconditioned or model-guided points). Point selection uses model outputs only. Reference boxes are used only after inference for one-to-one matching at box IoU ≥0.5; the source semantic mask is a binary union and not individual overlapping-object truth.','', '| Case | Stratum | Source boxes | Sparse top 10 | Dense top 10 | Uniform top 10 | Adaptive top 10 |','|---|---|---:|---:|---:|---:|---:|']
 for i,r in enumerate(records,1):
  v=r['variants'];lines.append(f"| {i} | {r['stratum']} | {r['source_boxes']} | {v['64']['box_matches']['10']['matched']} | {v['32']['box_matches']['10']['matched']} | {v['uniform']['box_matches']['10']['matched']} | {v['adaptive']['box_matches']['10']['matched']} |")
 lines+=['','[Overlays and data](/results/l38/). Matching the bounding box of a proposed mask is not evidence of a correct instance boundary. The binary annotation does not distinguish overlapping specimens and apparently omits some diatom-like structures; unassigned candidates and mask-union disagreement are not necessarily false positives. Sample independence, image acquisition groups and detector training overlap remain unknown. All 540 possible grid points were precomputed, so timings do not measure actual 270-point policy latency. These are previously viewed, metadata-selected images and not a held-out evaluation.','', 'Dataset attribution: Hüseyin Gündüz, [Diatom Dataset](https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset), CC BY-NC-SA 4.0; modified overlay images share the same noncommercial license.']
 (ROOT/'research/L38.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']=='L38':t.update(status='review',summary='Compared four fixed prompt budgets on eight previously inspected real multi-object public fields; box matching does not establish instance mask accuracy.',note='L38.md',result='/results/l38/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed real multi-object proposal diagnostic.',flush=True)
if __name__=='__main__':main()
