"""Frozen L44 box proposal policies on new-source synthetic crossings."""
import hashlib,json,sys,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,r41_consensus_fresh_sources as ranker,l42_synthetic_transfer as render
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r56';TMP=Path('/tmp/diatom-r56-public');BG=ROOT/'results/r3/scan-survey';sys.path.insert(0,str(ROOT/'diatom_pilot'))
from contrast_boxes import contrast_boxes
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def crop_source(row,images):
 ident=row['id'];ip=TMP/(ident+'-image.png');mp=TMP/(ident+'-mask.png')
 if sha(ip)!=images[ident] or sha(mp)!=row['mask_sha256']:raise ValueError('Source hash mismatch')
 rgb=np.asarray(Image.open(ip).convert('RGB'));mask=np.asarray(Image.open(mp).convert('L'))>0;_,labels,_,_=cv2.connectedComponentsWithStats(mask.astype('uint8'),connectivity=8);m=labels==row['result']['instances'][0]['component_label'];ys,xs=np.nonzero(m)
 if not len(xs):raise ValueError('Empty component')
 crop=rgb[ys.min():ys.max()+1,xs.min():xs.max()+1];m=m[ys.min():ys.max()+1,xs.min():xs.max()+1];scale=150/max(m.shape);size=(max(1,round(m.shape[1]*scale)),max(1,round(m.shape[0]*scale)));return cv2.resize(crop,size,interpolation=cv2.INTER_AREA),cv2.resize(m.astype('uint8'),size,interpolation=cv2.INTER_NEAREST)>0
def main():
 p=json.loads((OUT/'synthetic-protocol.json').read_text());sel=json.loads((OUT/'usable-selection.json').read_text());download=json.loads((OUT/'download.json').read_text());rule=json.loads((OUT/'synthetic-source-rule.json').read_text())
 for path,key in [(OUT/'usable-selection.json','selection_sha256'),(OUT/'download.json','download_sha256'),(OUT/'synthetic-source-rule.json','source_rule_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(ROOT/'diatom_pilot/contrast_boxes.py','box_code_sha256'),(Path(__file__),'script_sha256')]:
  if sha(path)!=p[key]:raise ValueError('Frozen input mismatch '+key)
 if (OUT/'synthetic-results.json').exists():raise FileExistsError('Preserve results')
 images={x['id']:x['sha256'] for x in download['images']};objects=[crop_source(r,images) for r in sel['sources'][:6]];torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 for pair in range(3):
  path=BG/f'field-{pair+10:02d}.png'
  if sha(path)!=rule['background_sha256'][pair]:raise ValueError('Background changed')
  bg=Image.open(path).convert('RGB').resize((512,512),Image.Resampling.LANCZOS)
  for kind in ('separated','crossing'):
   start=time.monotonic();canvas=np.asarray(bg).copy();full=[np.zeros((512,512),bool),np.zeros((512,512),bool)];pos=([(160,256),(352,256)] if kind=='separated' else [(256,256),(266,256)])
   for i,(crop,mask) in enumerate(objects[pair*2:pair*2+2]):base.paste(canvas,full[i],crop,mask,*pos[i])
   visible=[full[0]&~full[1],full[1]]
   if any(not x.any() for x in visible):raise ValueError('Fully hidden source object')
   image=Image.fromarray(canvas);bgr=cv2.cvtColor(canvas,cv2.COLOR_RGB2BGR);out=detector.predict(bgr,imgsz=512,conf=.05,device='cpu',verbose=False)[0];boxes=out.boxes.xyxy.cpu().numpy().tolist() if out.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(bgr)
   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=[]
   proposals=contrast_boxes(cv2.cvtColor(bgr,cv2.COLOR_BGR2GRAY),limit=80);raw=[]
   for j in range(0,len(proposals),12):
    batch=proposals[j:j+12];out=predictor(bboxes=[x['box'] for x in batch],verbose=False)[0]
    if out.masks is None or len(out.masks.data)!=len(batch):raise ValueError('Unexpected box output')
    for k,(m,q) in enumerate(zip(out.masks.data.cpu().numpy(),out.boxes.conf.cpu().numpy())):
     mask=m.astype(bool);area=int(mask.sum())
     if 300<=area<=50000 and float(q)>=.6:raw.append({'id':f'box-{j+k}','mask':mask})
   kept=[]
   for c in raw:
    if all(base.iou(c['mask'],x['mask'])<.8 for x in kept):kept.append(c)
   methods={'detector':det,'combined':ranker.interleave(det,kept)};scores={}
   for name,cs in methods.items():
    scores[name]={'candidates':len(cs)}
    for cut in (10,20):
     masks=[x['mask'] for x in cs[:cut]];scores[name][f'top{cut}']={'visible':base.assign(visible,masks,.5),'full':base.assign(full,masks,.5)}
    masks=[x['mask'] for x in cs];scores[name]['all']={'visible':base.assign(visible,masks,.5),'full':base.assign(full,masks,.5)}
   n=len(records)+1;records.append({'pair':pair+1,'condition':kind,'source_ids':[sel['sources'][pair*2]['id'],sel['sources'][pair*2+1]['id']],'shared_pixels':int((full[0]&full[1]).sum()),'box_prompts':len(proposals),'scores':scores,'seconds':time.monotonic()-start});panel=Image.new('RGB',(1080,410),'#f3f6ef');draw=ImageDraw.Draw(panel)
   for col,(label,masks) in enumerate([('Visible source masks',visible),('Detector masks',[c['mask'] for c in det]),('Combined top 20',[c['mask'] for c in methods['combined'][:20]])]):
    im=render.overlay(image,masks);im.thumbnail((344,344));panel.paste(im,(col*360+8,45));draw.text((col*360+8,8),label,fill='#203a38')
   panel.save(OUT/f'synthetic-{n:02d}.jpg',quality=88);print(f"{n}/6 {kind} shared {records[-1]['shared_pixels']} baseline {scores['detector']['top20']['visible']['matched']} combined {scores['combined']['top20']['visible']['matched']}",flush=True)
 (OUT/'synthetic-results.json').write_text(json.dumps({'format':'r56-synthetic-v1','protocol_sha256':sha(OUT/'synthetic-protocol.json'),'records':records,'warning':'Three new source pairs placed opaquely on previously inspected Academy backgrounds. Same new IDs as R56 field experiment; sample independence, source annotation accuracy and real optics unknown.'},indent=2)+'\n');print('Fresh-source synthetic comparison complete.',flush=True)
if __name__=='__main__':main()
