"""Compare fixed context-preserving detector tiles on R44 development fields."""
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
import r44_score_fields as r44
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l36'

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]));intersection=x*y;u=(a[2]-a[0])*(a[3]-a[1])+(b[2]-b[0])*(b[3]-b[1])-intersection
 return intersection/u if u>0 else 0.

def panel(image,refs,base_candidates,tiled_candidates):
 canvas=Image.new('RGB',(1152,410),'#f3f6ef');draw=ImageDraw.Draw(canvas)
 for col,(title,masks) in enumerate([('Source target regions',refs),('Baseline top 10',[x['mask'] for x in base_candidates[:10]]),('Full + tiles top 10',[x['mask'] for x in tiled_candidates[: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)
  canvas.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 canvas

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((r44.OUT/'results.json').read_text())
 for path,key in [(r44.OUT/'selection.json','selection_sha256'),(r44.COCO,'annotation_sha256'),(r44.OUT/'results.json','baseline_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(Path(r44.__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 (OUT/'results.json').exists():raise FileExistsError('Existing results')
 coco=json.loads(r44.COCO.read_text());annotations=collections.defaultdict(list)
 for a in coco['annotations']:annotations[a['image_id']].append(a)
 manifest={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));rows=[]
 fields=[x for x in selection['selection'] if x['split']=='development']
 if len(fields)!=9:raise ValueError('Unexpected development set')
 for index,row in enumerate(fields,1):
  started=time.monotonic();path=r44.IMAGES/row['local_file']
  if base.sha(path)!=manifest[row['id']]['sha256']:raise ValueError('Source image mismatch')
  image=Image.open(path).convert('RGB');array=cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR);refs=[]
  for ann in annotations[row['id']]:
   m=np.zeros((512,512),'uint8')
   for poly in ann['segmentation']:cv2.fillPoly(m,[np.rint(np.asarray(poly).reshape(-1,2)).astype('int32')],1)
   refs.append(m.astype(bool))
  if len(refs)!=row['annotation_count']:raise ValueError('Reference mismatch')
  pred=detector.predict(array,imgsz=512,conf=.05,device='cpu',verbose=False)[0];full_boxes=pred.boxes.xyxy.cpu().numpy().tolist() if pred.boxes is not None else []
  tiled=[]
  for y in (0,128):
   for x in (0,128):
    pred=detector.predict(array[y:y+384,x:x+384],imgsz=640,conf=.05,device='cpu',verbose=False)[0]
    if pred.boxes is None:continue
    for box,conf in zip(pred.boxes.xyxy.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
     a,b,c,d=map(float,box);edge=a<=2 or b<=2 or c>=382 or d>=382;tiled.append({'box':[a+x,b+y,c+x,d+y],'confidence':float(conf),'edge':edge,'tile':[x,y]})
  retained=[]
  for item in sorted(tiled,key=lambda c:-c['confidence']):
   if all(box_iou(item['box'],other['box'])<.5 for other in retained):retained.append(item)
  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(array)
  def prompt(boxes,prefix):
   if not boxes:return []
   out=predictor(bboxes=boxes,verbose=False)[0]
   if out.masks is None:return []
   masks=[m.astype(bool) for m in out.masks.data.cpu().numpy()]
   if len(masks)!=len(boxes):raise ValueError('Unexpected box-prompt mask count')
   return [{'id':prefix+str(i),'mask':m} for i,m in enumerate(masks)]
  full=prompt(full_boxes,'full-');tile=prompt([x['box'] for x in retained],'tile-')
  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 grid masks')
   for m,score in zip(pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
    m=m.astype(bool);area=int(m.sum())
    if 300<=area<=50000 and float(score)>=.6:raw.append({'id':len(raw),'mask':m,'quality':float(score)})
  grid=[]
  for c in sorted(raw,key=lambda x:-x['quality']):
   if all(base.iou(c['mask'],k['mask'])<.8 for k in grid):grid.append(c)
  def combined(det):
   local=[dict(c) for c in grid]
   for c in local:c['support']=max((base.iou(c['mask'],q['mask']) for q in det),default=0.)
   supported=sorted(local,key=lambda c:(-(c['support']>=.25),-c['quality']));return ranker.interleave(det,ranker.interleave(supported,local))
  variants={'baseline':combined(full),'tiles_only':combined(tile),'full_plus_tiles':combined(full+tile)}
  scores={name:{str(n):{'iou05':r44.match(refs,candidates[:n],.5),'iou075':r44.match(refs,candidates[:n],.75)} for n in (5,10,20)} for name,candidates in variants.items()}
  for n in (5,10,20):
   for key in ('iou05','iou075'):
    if scores['baseline'][str(n)][key]['matched']!=baseline[row['id']]['scores']['combined'][str(n)][key]['matched']:raise ValueError('Reproduced baseline counts differ')
  rec={'id':row['id'],'slide':row['slide'],'category':row['category'],'reference_count':len(refs),'full_boxes':len(full),'tile_boxes_before_nms':len(tiled),'tile_boxes_retained':len(tile),'tile_edge_boxes':sum(x['edge'] for x in retained),'grid_masks':len(grid),'scores':scores,'seconds':time.monotonic()-started};rows.append(rec)
  panel(image,refs,variants['baseline'],variants['full_plus_tiles']).save(OUT/f'field-{index:02d}.jpg',quality=88)
  print(f"{index}/9 {row['slide']} refs {len(refs)} baseline10 {scores['baseline']['10']['iou05']['matched']} tiles10 {scores['tiles_only']['10']['iou05']['matched']} full+tiles10 {scores['full_plus_tiles']['10']['iou05']['matched']} ({len(tile)} tiled boxes)",flush=True)
 result={'format':'l36-context-tiles-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':rows,'warning':'Nine previously inspected development tiles; source excludes fragments and dense aggregates. NMS can suppress real overlaps; counts are not real-slide recall.'};(OUT/'results.json').write_text(json.dumps(result,indent=2)+'\n')
 cards=[]
 for i,r in enumerate(rows,1):
  q=r['scores'];cards.append(f"<article><h3>{r['slide']} · {r['category']}</h3><img src=\"field-{i:02d}.jpg\" alt=\"Reference and two candidate overlays\"><p>Annotated regions: {r['reference_count']}; baseline top 10: {q['baseline']['10']['iou05']['matched']}; full+tiles top 10: {q['full_plus_tiles']['10']['iou05']['matched']}. Tiled boxes retained: {r['tile_boxes_retained']} ({r['tile_edge_boxes']} touch a tile edge).</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Context-aware tile prompts</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/r44/">Prior field test</a> · <a href="/research/L36.md">Research note</a> · <a href="/results/performance/">Performance monitor</a></nav><h1>Context-aware tile prompts</h1><p class="notice">Nine previously inspected public development tiles from three slide groups. Source annotations exclude small fragments and dense aggregates, so unmatched proposals are not necessarily false positives. This is not Academy accuracy or an independent test.</p><p>Detect on overlapping 384-pixel tiles; translate boxes to full-field coordinates and prompt the segmenter on the full 512-pixel field. The tiled-only and full-plus-tiled variants preserve grid proposals; tiled boxes are suppressed against other tiled boxes at box IoU 0.5, which can remove true overlaps. Colors are candidates, not identities. <a href="results.json">Full scores</a> · <a href="protocol.json">Frozen protocol</a></p><p>Source 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; masks overlaid and images resized.</p>{CARDS}</main></html>'''.replace('{CARDS}',''.join(cards));(OUT/'index.html').write_text(page)
 lines=['# L36 · Context-aware tiling on development fields','','Nine previously inspected R44 development tiles from three public slide groups. Detect with 384×384 crops at four offsets and 640-pixel detector input; translate boxes to full field, perform tile-only box NMS at 0.5, and prompt MobileSAM on the full field. Compare baseline, tiled-only and full-plus-tiled detector/grid proposals at equal candidate budgets. Full-field and tiled box candidates are retained separately; NMS across tiled boxes can still remove real overlaps.','', '| Slide / category | Regions | Baseline top 10 | Tiled only top 10 | Full + tile top 10 | Tile masks |','|---|---:|---:|---:|---:|---:|']
 for r in rows:
  q=r['scores'];lines.append(f"| {r['slide']} · {r['category']} | {r['reference_count']} | {q['baseline']['10']['iou05']['matched']} | {q['tiles_only']['10']['iou05']['matched']} | {q['full_plus_tiles']['10']['iou05']['matched']} | {r['tile_boxes_retained']} |")
 lines+=['','[Field overlays](/results/l36/) · [scores](/results/l36/results.json). These fields and reference annotations were inspected previously; matching uses reference regions after inference. Source labels exclude fragments and dense aggregates; annotation-empty does not mean no specimen, and its units may merge touching cells. Cropping and box NMS may lose edge or overlapping instances. Counts, unmatched proposals and IoU do not establish precision, species identification, or human-level Academy performance. No additional public holdout fields were opened during this development run.']
 (ROOT/'research/L36.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']=='L36':t.update(status='review',summary='Compared context-preserving detector tiles with full-field prompts on nine prior public development tiles; see field and budget results.',note='L36.md',result='/results/l36/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed context-aware tile development comparison.',flush=True)
if __name__=='__main__':main()
