"""Compare 32-pixel grid prompts against frozen R38 synthetic scene references."""
import json,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
import r38_synthetic_crossings as base
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r40'

def main():
 p=json.loads((OUT/'protocol.json').read_text());original=json.loads((base.OUT/'results.json').read_text());r38=json.loads((base.OUT/'protocol.json').read_text());baseline=json.loads((ROOT/'results/l31/results.json').read_text())
 for path,key in [(base.OUT/'protocol.json','r38_protocol_sha256'),(base.OUT/'results.json','r38_results_sha256'),(ROOT/'results/l31/results.json','l31_results_sha256'),(base.SAM,'sam_sha256'),(Path(__file__),'script_sha256')]:
  if base.sha(path)!=p[key]:raise ValueError('Frozen input changed: '+key)
 source=json.loads(base.SELECTION.read_text())['selection'];objects=[base.extract(e,i) for i,e in enumerate(source,1)]
 if [x[2] for x in objects]!=r38['source_objects'] or base.sha(base.BACKGROUND)!=r38['background_sha256']:raise ValueError('R38 source changed')
 if (OUT/'results.json').exists():raise FileExistsError('Existing results')
 OUT.mkdir(parents=True,exist_ok=True);background=np.asarray(Image.open(base.BACKGROUND).convert('RGB').crop((128,128,640,640))).copy();torch.set_num_threads(4);records=[]
 for scene in original['records']:
  start=time.monotonic();pair=scene['pair']-1;condition=scene['condition'];a,am,_=objects[2*pair];b,bm,_=objects[2*pair+1];canvas=background.copy();f1=np.zeros((512,512),bool);f2=np.zeros((512,512),bool);centers=((141,256),(371,256)) if condition=='separated' else ((256,256),(256,256));base.paste(canvas,f1,a,am,*centers[0]);base.paste(canvas,f2,b,bm,*centers[1]);refs=[f1&~f2,f2]
  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(cv2.cvtColor(canvas,cv2.COLOR_RGB2BGR));points=[(x,y) for y in range(16,512,32) for x in range(16,512,32)];raw=[]
  for start_index in range(0,len(points),12):
   batch=points[start_index:start_index+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 point batch output')
   for point,mask,score in zip(batch,pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
    mask=mask.astype(bool);area=int(mask.sum())
    if 300<=area<=50000 and float(score)>=.6:raw.append({'point':point,'mask':mask,'score':float(score)})
  kept=[]
  for c in sorted(raw,key=lambda x:-x['score']):
   if all(base.iou(c['mask'],k['mask'])<.8 for k in kept):kept.append(c)
  budgets={}
  for n in (5,10,20,40,len(kept)):
   masks=[x['mask'] for x in kept[:n]];budgets[str(n)]={'considered':len(masks),'at_05':base.assign(refs,masks,.5),'at_075':base.assign(refs,masks,.75)}
  old=next(r for r in baseline['records'] if r['pair']==pair+1 and r['condition']==condition)
  rec={'pair':pair+1,'condition':condition,'grid_points':len(points),'before_nms':len(raw),'retained':len(kept),'budgets':budgets,'baseline_64px':old['budgets']['quality'],'seconds':time.monotonic()-start};records.append(rec)
  print(f"pair {pair+1} {condition}: {len(kept)} masks; dense top-20 {budgets['20']['at_05']['matched']}/2; 64px top-20 {old['budgets']['quality']['20']['matched']}/2",flush=True)
 result={'format':'r40-dense-grid-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,'warning':'Same six synthetic development scenes previously inspected; dense 32-pixel grid vs 64-pixel grid, reference matching only for scoring. This is not real-slide performance.'};(OUT/'results.json').write_text(json.dumps(result,indent=2)+'\n')
 table=''.join(f"<tr><td>{r['pair']} · {r['condition']}</td><td>{r['baseline_64px']['20']['matched']}/2</td><td>{r['budgets']['20']['at_05']['matched']}/2</td><td>{r['budgets'][str(r['retained'])]['at_05']['matched']}/2</td><td>{r['retained']}</td></tr>" for r in records)
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Denser grid segmentation</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1050px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:14px}td,th{padding:8px;border-bottom:1px solid #cad9cf;text-align:left}</style><main><nav><a href="/results/r38/">Scene silhouettes</a> · <a href="/research/R40.md">Research note</a></nav><h1>Denser grid prompts</h1><p class="notice">Same six synthetic development scenes. Models are not judged on actual field accuracy; score matching uses known synthetic masks after prediction.</p><p>Dense 32-pixel spacing uses 256 points per scene, compared to 64 points with the prior 64-pixel grid. Masks are quality-ranked and suppressed at mask IoU 0.8; high overlap suppression may erase valid instances. Full results include IoU 0.75 and timings.</p><table><tr><th>Scene</th><th>64px top 20</th><th>32px top 20</th><th>32px all</th><th>32px masks retained</th></tr>{ROWS}</table><p><a href="results.json">Raw results and timings</a></p></main></html>'''.replace('{ROWS}',table);(OUT/'index.html').write_text(page)
 lines=['# R40 · Denser grid prompting on controlled crossings','','Compare a 32-pixel positive-point grid (256 prompts) to the existing 64-pixel grid (64 prompts) on the same six R38 synthetic scenes. Both use score ≥0.6, area 300–50,000 and mask NMS IoU 0.8. Rank by SAM predicted quality and match masks one-to-one after prediction against visible references. The NMS can suppress valid overlapping masks.','', '| Pair | Scene | 64px top 20 | 32px top 20 | 32px all | 32px retained |','|---|---|---:|---:|---:|---:|']
 for r in records:lines.append(f"| {r['pair']} | {r['condition']} | {r['baseline_64px']['20']['matched']}/2 | {r['budgets']['20']['at_05']['matched']}/2 | {r['budgets'][str(r['retained'])]['at_05']['matched']}/2 | {r['retained']} |")
 lines+=['','[Results and timing](/results/r40/) · [data](/results/r40/results.json). The images, thresholds and layouts were previously inspected; synthetic opaque crossings and a single unverified background are not independent real-world data. More candidates or matching after using the references does not mean a deployable system can choose them. False positives and review time are unknown. Preserve fresh real fields and sample-separated data for independent evaluation.']
 (ROOT/'research/R40.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']=='R40':t.update(status='review',summary='Compared dense and sparse grid masks on six synthetic scenes; see candidate budgets and limitations.',note='R40.md',result='/results/r40/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed dense-grid comparison.',flush=True)
if __name__=='__main__':main()
