"""Compare fixed point-grid densities on preexisting public development tiles."""
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/r45'

def draw_panel(image,refs,methods):
 panel=Image.new('RGB',(1152,410),'#f3f6ef');draw=ImageDraw.Draw(panel)
 for col,(title,masks) in enumerate([('Source target regions',refs),('64px combined top 10',[x['mask'] for x in methods['64'][:10]]),('32px combined top 10',[x['mask'] for x in methods['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)
  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((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 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)
   if not mask.any():raise ValueError('Empty reference')
   refs.append(mask.astype(bool))
  if len(refs)!=row['annotation_count']:raise ValueError('Reference count changed')
  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=[]
  variants={};methods={}
  for spacing in (64,32):
   t=time.monotonic();points=[(x,y) for y in range(spacing//2,512,spacing) for x in range(spacing//2,512,spacing)];raw=[]
   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 result')
    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:raw.append({'id':len(raw),'mask':mask,'quality':float(score)})
   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[str(spacing)]=combined
   coverage=sum(any(ref[y,x] for x,y in points) for ref in refs)
   variants[str(spacing)]={'points':len(points),'reference_with_interior_point':coverage,'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)},'seconds':time.monotonic()-t}
  for n in (5,10,20):
   for key in ('iou05','iou075'):
    if variants['64']['budgets'][str(n)][key]['matched']!=baseline[row['id']]['scores']['combined'][str(n)][key]['matched']:raise ValueError('R44 baseline replay differs')
  records.append({'id':row['id'],'slide':row['slide'],'category':row['category'],'reference_count':len(refs),'reference_areas':[int(x.sum()) for x in refs],'detector_masks':len(det),'variants':variants,'seconds':time.monotonic()-started})
  draw_panel(image,refs,methods).save(OUT/f'field-{i:02d}.jpg',quality=88)
  print(f"{i}/9 {row['slide']} refs {len(refs)}: 64px {variants['64']['budgets']['10']['iou05']['matched']} / {len(refs)} with {variants['64']['after_nms']} grid masks; 32px {variants['32']['budgets']['10']['iou05']['matched']} / {len(refs)} with {variants['32']['after_nms']} grid masks",flush=True)
 result={'format':'r45-grid-density-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,'warning':'Previously inspected public development fields, nonrandom selection and incomplete annotations. Point coverage and candidate matches are not human-level Academy 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>{r['slide']} · {r['category']}</h3><img src=\"field-{i:02d}.jpg\" alt=\"Source reference and candidate masks for both grids\"><p>Source regions: {r['reference_count']}; 64px interior-point coverage {v['64']['reference_with_interior_point']}, top-10 matches {v['64']['budgets']['10']['iou05']['matched']}, grid candidates {v['64']['after_nms']}; 32px coverage {v['32']['reference_with_interior_point']}, top-10 matches {v['32']['budgets']['10']['iou05']['matched']}, grid candidates {v['32']['after_nms']}.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Grid density and small annotated regions</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/R45.md">Research note</a> · <a href="/results/performance/">Performance monitor</a></nav><h1>Grid density and annotated regions</h1><p class="notice">Nine previously viewed public development fields. References are source-defined regions and omit many partials and dense aggregates. Model overlays are not ground truth; these are not real-overlap or Academy performance results.</p><p>64-pixel spacing uses 64 prompts; 32-pixel spacing uses 256. Both use the same quality, area, grid suppression and detector/grid ranking. Reference masks are used after prediction only. <a href="results.json">Full scores</a> · <a href="protocol.json">Frozen 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=['# R45 · Prompt density and annotated object scale','','Compare frozen 64-pixel and 32-pixel grid point spacing on the nine previously viewed R44 development fields. Each prediction uses the same model, 0.6 score minimum, 300–50,000 pixel area, 0.8 grid-mask suppression, detector-support ranking and full-field detector candidates. References are used only after prediction for measuring grid-point coverage and one-to-one matching; the 64-pixel baseline is checked against R44.','', '| Slide / category | Regions | 64px point coverage | 32px point coverage | 64px top 10 | 32px top 10 | 64px / 32px grid masks |','|---|---:|---:|---:|---:|---:|---:|']
 for r in records:
  v=r['variants'];lines.append(f"| {r['slide']} · {r['category']} | {r['reference_count']} | {v['64']['reference_with_interior_point']} | {v['32']['reference_with_interior_point']} | {v['64']['budgets']['10']['iou05']['matched']} | {v['32']['budgets']['10']['iou05']['matched']} | {v['64']['after_nms']} / {v['32']['after_nms']} |")
 lines+=['','[Overlays](/results/r45/) · [full data](/results/r45/results.json). These are nonrandom, previously seen development fields; source regions exclude many fragments and dense aggregates, may combine touching objects, and cannot establish false-positive rates or human-level Academy performance. More point coverage is not equivalent to correct masks, and more candidates or an oracle-selected best match do not automatically improve deployable output. R44 public held-out results have already been observed and are not used as unseen validation here.']
 (ROOT/'research/R45.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']=='R45':t.update(status='review',summary='Compared fixed 64px and 32px prompt grids on nine previously viewed public development fields; see coverage, match counts and candidate burden.',note='R45.md',result='/results/r45/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed grid-density development comparison.',flush=True)
if __name__=='__main__':main()
