"""Compare positive-only and neighbor-negative oracle prompts on R38 scenes."""
import hashlib,json
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/l30'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()

def main():
 protocol=json.loads((base.OUT/'protocol.json').read_text());baseline=json.loads((base.OUT/'results.json').read_text())
 if baseline['protocol_sha256']!=sha(base.OUT/'protocol.json') or sha(base.SAM)!=protocol['sam_sha256'] or sha(base.BACKGROUND)!=protocol['background_sha256'] or sha(base.SELECTION)!=protocol['selection_sha256']:raise ValueError('R38 provenance mismatch')
 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]!=protocol['source_objects']:raise ValueError('R38 source changed')
 if OUT.exists() and (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 item in baseline['records']:
  pair=item['pair']-1;condition=item['condition'];crop1,mask1,_=objects[2*pair];crop2,mask2,_=objects[2*pair+1];canvas=background.copy();full1=np.zeros((512,512),bool);full2=np.zeros((512,512),bool)
  centers=((141,256),(371,256)) if condition=='separated' else ((256,256),(256,256));base.paste(canvas,full1,crop1,mask1,*centers[0]);base.paste(canvas,full2,crop2,mask2,*centers[1]);visible=[full1&~full2,full2];full=[full1,full2];points=[base.point(x) for x in visible]
  if points!=item['oracle_points']:raise ValueError('Oracle prompt changed')
  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))
  result=predictor(points=[[points[0],points[1]],[points[1],points[0]]],labels=[[1,0],[1,0]],verbose=False)[0]
  masks=[] if result.masks is None else [x.astype(bool) for x in result.masks.data.cpu().numpy()]
  if len(masks)!=2 or any(m.shape!=(512,512) for m in masks):raise ValueError('Unexpected prompt output')
  method={'visible_at_05':base.assign(visible,masks,.5),'visible_at_075':base.assign(visible,masks,.75),'full_at_05':base.assign(full,masks,.5),'predicted_shared_pixels':int((masks[0]&masks[1]).sum())}
  original=item['methods']['oracle_points'];records.append({'pair':pair+1,'condition':condition,'baseline':original,'negative':method})
  print(f"Pair {pair+1}, {condition}: positive {original['visible_at_05']['matched']}/2; with negative {method['visible_at_05']['matched']}/2",flush=True)
 result={'format':'l30-negative-crossings-v1','r38_protocol_sha256':sha(base.OUT/'protocol.json'),'r38_results_sha256':sha(base.OUT/'results.json'),'records':records,'warning':'Oracle points derived from known visible masks; synthetic development scenes only. Not a real overlap or automatic detection result.'}
 (OUT/'results.json').write_text(json.dumps(result,indent=2)+'\n')
 lines=['# L30 · Neighbor-negative prompts on controlled crossings','','R38 uses six synthetic development scenes. For each known visible specimen, compare its reference-derived positive point alone with the same point plus the other known specimen point as negative. Matching is one-to-one against the same inserted visible masks. This oracle-assisted check tests a mechanism; it does not measure an automatic or human workflow.','', '| Pair | Condition | Positive @0.5 | Positive plus negative @0.5 | Negative @0.75 |','|---|---|---:|---:|---:|']
 for r in records:lines.append(f"| {r['pair']} | {r['condition']} | {r['baseline']['visible_at_05']['matched']}/2 | {r['negative']['visible_at_05']['matched']}/2 | {r['negative']['visible_at_075']['matched']}/2 |")
 lines+=['','[Results and visualization](/results/l30/) · [numeric data](/results/l30/results.json). Scenes share one background and previously inspected source polygons; opaque compositing, ground-truth prompts, and a permissive IoU threshold limit inference. Disjoint masks are not proof of correct real separation. Both full-object and visible-mask scores are retained. Review fresh real or synthetic cases, count prompt effort and duplicate masks, and avoid tuning on the same examples used for claims.']
 (ROOT/'research/L30.md').write_text('\n'.join(lines)+'\n')
 rows=''.join(f"<tr><td>{r['pair']} · {r['condition']}</td><td>{r['baseline']['visible_at_05']['matched']}/2</td><td>{r['negative']['visible_at_05']['matched']}/2</td><td>{r['negative']['visible_at_075']['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>Neighbor-negative prompts</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:950px;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/L30.md">Research note</a></nav><h1>Neighbor-negative prompts</h1><p class="notice">Same six synthetic development scenes as R38. Both the positive and negative points are derived from the known reference masks; this is not automatic segmentation or real-overlap accuracy.</p><table><tr><th>Scene</th><th>Positive: visible IoU ≥ 0.5</th><th>With negative: visible IoU ≥ 0.5</th><th>With negative: visible IoU ≥ 0.75</th></tr>{ROWS}</table><p>One prediction can match at most one reference. <a href="results.json">Full data</a> includes full-extent scores and predicted overlap; source scene images are not redistributed.</p></main></html>'''.replace('{ROWS}',rows)
 (OUT/'index.html').write_text(page)
 board=ROOT/'research/board.json';d=json.loads(board.read_text())
 for t in d['tasks']:
  if t['id']=='L30':t.update(status='review',summary='Compared oracle positive-only and neighbor-negative point prompts on the six synthetic R38 scenes; results are not real-overlap accuracy.',result='/results/l30/')
 board.write_text(json.dumps(d,indent=2)+'\n');print('Completed neighbor-negative prompt comparison.',flush=True)
if __name__=='__main__':main()
