"""Test point-jitter stability as a grid-candidate ranker on R38 synthetic scenes."""
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/l31'

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())
 for path,key in [(base.OUT/'protocol.json','r38_protocol_sha256'),(base.OUT/'results.json','r38_results_sha256'),(base.SAM,'sam_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')
 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')
 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(32,512,64) for x in range(32,512,64)];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)
  nms_count=len(kept);kept=kept[:20]
  for start_index in range(0,len(kept),12):
   batch=kept[start_index:start_index+12];jittered=[(min(511,c['point'][0]+4),min(511,c['point'][1]+4)) for c in batch]
   pred=predictor(points=[[[x,y]] for x,y in jittered],labels=[[1] for _ in batch],verbose=False)[0]
   if pred.masks is None or len(pred.masks.data)!=len(batch):raise ValueError('Unexpected jitter batch output')
   for candidate,mask in zip(batch,pred.masks.data.cpu().numpy()):candidate['stability']=base.iou(candidate['mask'],mask.astype(bool))
  ranking={'quality':kept,'stability':sorted(kept,key=lambda c:(-c['stability'],-c['score']))};budgets={}
  for method,candidates in ranking.items():
   budgets[method]={}
   for n in (5,10,20):
    chosen=candidates[:n];budgets[method][str(n)]={'considered':len(chosen),**base.assign(refs,[x['mask'] for x in chosen],.5)}
  rec={'pair':pair+1,'condition':condition,'candidates_before_cap':len(raw),'nms_kept_before_cap':nms_count,'budgets':budgets,
       'candidate_scores':[{'point':list(c['point']),'quality':c['score'],'stability':c['stability']} for c in kept],'elapsed_seconds':time.monotonic()-start};records.append(rec)
  print(f"pair {pair+1} {condition}: {len(kept)} candidates, top-5 quality {budgets['quality']['5']['matched']}/2, stability {budgets['stability']['5']['matched']}/2",flush=True)
 payload={'format':'l31-grid-stability-v1','protocol_sha256':base.sha(OUT/'protocol.json'),'records':records,'warning':'Same six previously examined synthetic scenes; fixed positive-point perturbation and posthoc reference scoring. Stability is not accuracy.'};(OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n')
 table=''.join(f"<tr><td>{r['pair']} · {r['condition']}</td><td>{r['budgets']['quality']['5']['matched']}/2</td><td>{r['budgets']['stability']['5']['matched']}/2</td><td>{r['budgets']['quality']['10']['matched']}/2</td><td>{r['budgets']['stability']['10']['matched']}/2</td><td>{r['budgets']['quality']['20']['matched']}/2</td></tr>" for r in records)
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Prompt stability ranking</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/L31.md">Research note</a></nav><h1>Can prompt stability rank useful masks?</h1><p class="notice">Six previously examined synthetic scenes, not a real slide benchmark. Each reference can be assigned to one candidate at visible-mask IoU ≥ 0.5; references are used only for scoring. Stability tests one +4 pixel perturbation, not biological correctness.</p><p>Start with the same 20 quality-ranked candidates; rerank them by mask IoU after shifting their prompt four pixels diagonally. More candidate evaluations are needed to compute stability.</p><table><tr><th>Scene</th><th>Quality top 5</th><th>Stability top 5</th><th>Quality top 10</th><th>Stability top 10</th><th>All ≤20</th></tr>{ROWS}</table><p><a href="results.json">Raw scores, timings and full budgets</a></p></main></html>'''.replace('{ROWS}',table);(OUT/'index.html').write_text(page)
 lines=['# L31 · Grid-mask ranking by prompt stability','','The six previously inspected R38 synthetic scenes use six public polygons over one Academy background. Generate fixed 64-pixel grid prompts and retain area 300–50,000, score ≥0.6, mask NMS IoU 0.8. Take at most 20 quality-ranked candidates, perturb each prompt by +4 pixels in X and Y, and rerank by IoU between original and perturbed masks. Match selected masks posthoc to visible references at IoU 0.5. This does not use references to rank candidates, but reference-based matching is evaluation only.','', '| Pair | Condition | Quality top 5 | Stability top 5 | Quality top 10 | Stability top 10 | All ≤20 |','|---|---|---:|---:|---:|---:|---:|']
 for r in records:
  b=r['budgets'];lines.append(f"| {r['pair']} | {r['condition']} | {b['quality']['5']['matched']}/2 | {b['stability']['5']['matched']}/2 | {b['quality']['10']['matched']}/2 | {b['stability']['10']['matched']}/2 | {b['quality']['20']['matched']}/2 |")
 lines+=['','[Results](/results/l31/) · [data](/results/l31/results.json). Re-ranking requires an extra SAM prompt for each candidate, and a stable mask can be debris, merged specimens, or the wrong object. The six opaque scenes, preselection, small budget, single jitter, previously inspected examples, unknown image-source training overlap, and one background prevent generalization. Test fresh scenes and real fields without assuming stable candidates are correct.']
 (ROOT/'research/L31.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']=='L31':t.update(status='review',summary='Compared model quality versus prompt-jitter stability ranking on six synthetic scenes; see matches and limitations.',note='L31.md',result='/results/l31/')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(d,indent=2)+'\n');tmp.replace(board);print('Completed prompt stability comparison.',flush=True)
if __name__=='__main__':main()
