"""Compare model-guided and unconditioned extra points on public development tiles."""
import collections,json,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
import r44_score_fields as r44
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l37';sys.path.insert(0,str(ROOT/'diatom_pilot'))
from adaptive_grid import select_extra

def render(image,refs,methods):
 panel=Image.new('RGB',(1152,410),'#f3f6ef');draw=ImageDraw.Draw(panel)
 for col,(title,masks) in enumerate([('Source target regions',refs),('Unconditioned top 10',[x['mask'] for x in methods['uniform'][:10]]),('Adaptive top 10',[x['mask'] for x in methods['adaptive'][: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)
  panel.paste(Image.alpha_composite(im,layer).convert('RGB').resize((360,360)),(col*384+10,40));draw.text((col*384+10,8),title,fill='#203a38')
 return panel

def main():
 p=json.loads((OUT/'protocol.json').read_text());selection=json.loads((r44.OUT/'selection.json').read_text());report=json.loads((r44.OUT/'download-report.json').read_text());prior=json.loads((ROOT/'results/r45/results.json').read_text())
 for path,key in [(r44.OUT/'selection.json','selection_sha256'),(r44.COCO,'annotation_sha256'),(ROOT/'results/r45/results.json','baseline_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(Path(r44.__file__),'matching_code_sha256'),(Path(ranker.__file__),'ranking_code_sha256'),(ROOT/'diatom_pilot/adaptive_grid.py','selection_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')
 coco=json.loads(r44.COCO.read_text());annotations=collections.defaultdict(list)
 for a in coco['annotations']:annotations[a['image_id']].append(a)
 downloaded={x['id']:x for x in report['images']};baseline={x['id']:x for x in prior['records']};torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 fields=[x for x in selection['selection'] if x['split']=='development']
 if len(fields)!=9:raise ValueError('Unexpected development set')
 for i,row in enumerate(fields,1):
  started=time.monotonic();path=r44.IMAGES/row['local_file']
  if base.sha(path)!=downloaded[row['id']]['sha256']:raise ValueError('Source image changed')
  image=Image.open(path).convert('RGB');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)
   refs.append(mask.astype(bool))
  if len(refs)!=row['annotation_count'] or any(not x.any() for x in refs):raise ValueError('Reference mismatch')
  arr=cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR);pred=detector.predict(arr,imgsz=512,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':512,'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 grid_points(spacing):return [(x,y) for y in range(spacing//2,512,spacing) for x in range(spacing//2,512,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 output')
    for point,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[point]={'id':f'pt-{point[0]}-{point[1]}','mask':mask,'quality':float(score)}
   return result
  coarse_points=grid_points(64);dense_points=grid_points(32);coarse=infer(coarse_points)
  # Guidance depends only on coarse predictions and detector boxes; source
  # references never enter select_extra. Dense outputs are precomputed solely
  # to replay the two fixed point subsets under identical numerical inference.
  extra=select_extra(dense_points,boxes,[c['mask'] for c in coarse.values()]);dense=infer(dense_points)
  pointsets={'64':coarse_points,'32':dense_points,'uniform':coarse_points+extra['uniform'],'adaptive':coarse_points+extra['adaptive']};variants={};methods={}
  for name,points in pointsets.items():
   available={**coarse,**dense};raw=[available[x] for x in points if x in available];kept=[]
   for c in sorted(raw,key=lambda z:-z['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'],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);methods[name]=combined
   variants[name]={'prompts':len(points),'reference_with_interior_point':sum(any(ref[y,x] for x,y in points) for ref in refs),'before_nms':len(raw),'after_nms':len(kept),
       'matching_before_nms':r44.match(refs,raw,.5),'matching_after_nms':r44.match(refs,kept,.5),'combined_all':r44.match(refs,combined,.5),
       'budgets':{str(n):{'iou05':r44.match(refs,combined[:n],.5),'iou075':r44.match(refs,combined[:n],.75)} for n in (5,10,20)}}
  for source,variant in [('64','64'),('32','32')]:
   expected=baseline[row['id']]['variants'][source]
   if variants[variant]['after_nms']!=expected['after_nms'] or any(variants[variant]['budgets'][n]['iou05']['matched']!=expected['budgets'][n]['iou05']['matched'] for n in ('5','10','20')):raise ValueError('R45 baseline replay differs')
  records.append({'id':row['id'],'slide':row['slide'],'category':row['category'],'reference_count':len(refs),'detector_boxes':len(boxes),'guided_count':extra['guided_count'],
     'uniform_extra_points':[list(x) for x in extra['uniform']],'adaptive_extra_points':[list(x) for x in extra['adaptive']],
     'variants':variants,'elapsed_seconds_all_320_prompt_replay':time.monotonic()-started})
  render(image,refs,methods).save(OUT/f'field-{i:02d}.jpg',quality=88)
  print(f"{i}/9 {row['slide']} refs {len(refs)}: uniform top10 {variants['uniform']['budgets']['10']['iou05']['matched']}, adaptive top10 {variants['adaptive']['budgets']['10']['iou05']['matched']}, guided {extra['guided_count']}/96",flush=True)
 payload={'format':'l37-adaptive-grid-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,
   'warning':'Development-only replay on previously viewed nonrandom public fields. All 320 prompts were precomputed; measured wall time is not adaptive inference latency. Source labels exclude fragments and dense aggregates.'};(OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n')
 cards=[]
 for i,r in enumerate(records,1):
  v=r['variants'];cards.append(f"<article><h3>{r['slide']} · {r['category']}</h3><img src=\"field-{i:02d}.jpg\" alt=\"Reference, unconditioned and adaptive candidate overlays\"><p>Regions: {r['reference_count']} · unconditioned top-10 {v['uniform']['budgets']['10']['iou05']['matched']} · adaptive top-10 {v['adaptive']['budgets']['10']['iou05']['matched']} · guided extra points {r['guided_count']}/96.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Adaptive grid prompting</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/r45/">Fixed-grid comparison</a> · <a href="/research/L37.md">Research note</a> · <a href="/results/performance/">Performance monitor</a></nav><h1>Adaptive grid prompting</h1><p class="notice">Nine previously viewed public development tiles, not independent validation or Academy accuracy. Source labels exclude many fragments and dense aggregates; unannotated regions are not necessarily negatives.</p><p>Both methods start with 64 prompts and add 96: one uses a fixed deterministic point sample; the other uses up to 48 points near model boxes or coarse-mask boundaries plus at least 48 unconditioned points. Source annotations never choose prompts. All 320 possible prompts were precomputed for replay, so actual adaptive latency has not been measured. <a href="results.json">Full data</a> · <a href="protocol.json">Protocol</a></p><p>Images and annotations: Kloster, Burfeid-Castellanos and Beszteri, <a href="https://doi.org/10.5281/zenodo.7079005">River Menne dataset</a>, CC BY 4.0; overlays and resizing added.</p>{CARDS}</main></html>'''.replace('{CARDS}',''.join(cards));(OUT/'index.html').write_text(page)
 lines=['# L37 · Adaptive grid densification','','On nine previously viewed R44 development tiles, compare the same 64-point coarse grid plus 96 extra points under two predeclared rules: deterministic image-independent point sampling, and up to 48 points near model-predicted coarse-mask boundaries or expanded detector boxes with the remainder unconditioned. Both use exactly 160 points. The dense 256-point grid is a separate reference, not an equal-compute control. No source reference labels enter prompt selection. All 320 possible coarse and dense prompts were precomputed to replay the subsets; no adaptive runtime saving is measured.','', '| Slide / category | Regions | Uniform 160 top 10 | Adaptive 160 top 10 | Dense 256 top 10 | Guided extra points |','|---|---:|---:|---:|---:|---:|']
 for r in records:
  v=r['variants'];lines.append(f"| {r['slide']} · {r['category']} | {r['reference_count']} | {v['uniform']['budgets']['10']['iou05']['matched']} | {v['adaptive']['budgets']['10']['iou05']['matched']} | {v['32']['budgets']['10']['iou05']['matched']} | {r['guided_count']}/96 |")
 lines+=['','[Overlays](/results/l37/) · [full data and point coordinates](/results/l37/results.json). The experiment reuses previously examined, nonrandom fields; source labels exclude fragments and dense aggregates. Prompt count is not runtime. Candidate overlap is not proof of duplication. Source-label matches are not real overlap recovery or human-level Academy performance. R44 held-out public results were already observed and were not rerun here.']
 (ROOT/'research/L37.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']=='L37':t.update(status='review',summary='Compared model-guided and deterministic unconditioned extra prompts at 160-point budget on nine public development tiles.',note='L37.md',result='/results/l37/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed adaptive-grid development comparison.',flush=True)
if __name__=='__main__':main()
