"""Specialist and generic detector on fresh-source synthetic crossing composites."""
import hashlib,json,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image,ImageDraw,ImageOps
from ultralytics import YOLO
from ultralytics.models.sam import Predictor
import r38_synthetic_crossings as old
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l42';TMP=Path('/tmp/diatom-l42-sources');BG=ROOT/'results/r3/scan-survey';SPECIAL=Path('/tmp/diatom-r52-pseudo/best.pt')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def make_object(row,download):
 ident=row['id'];ip=TMP/(ident+'-image.png');mp=TMP/(ident+'-mask.png')
 if sha(ip)!=download[ident] or sha(mp)!=row['mask_sha256']:raise ValueError('Source hash mismatch')
 source=np.asarray(Image.open(ip).convert('RGB'));mask=np.asarray(Image.open(mp).convert('L'))>0
 if source.shape[:2]!=mask.shape:raise ValueError('Source dimensions mismatch')
 _,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=source[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)))
 crop=cv2.resize(crop,size,interpolation=cv2.INTER_AREA);m=cv2.resize(m.astype('uint8'),size,interpolation=cv2.INTER_NEAREST)>0
 return crop,m
def overlay(image,masks):
 im=image.convert('RGBA');layer=Image.new('RGBA',im.size,(0,0,0,0))
 for i,m in enumerate(masks):
  color=Image.new('RGBA',im.size,['#00cc99','#ed8860','#9275ea','#e8c042'][i%4]);color.putalpha(Image.fromarray(m.astype('uint8')*105));layer=Image.alpha_composite(layer,color)
 return Image.alpha_composite(im,layer).convert('RGB')
def main():
 p=json.loads((OUT/'protocol.json').read_text());sel=json.loads((OUT/'usable-selection.json').read_text());download=json.loads((OUT/'download.json').read_text())
 for path,key in [(OUT/'usable-selection.json','selection_sha256'),(OUT/'download.json','download_sha256'),(SPECIAL,'specialist_sha256'),(old.SAM,'sam_sha256'),(old.DETECTOR,'detector_sha256'),(Path(old.__file__),'synthetic_helpers_sha256'),(Path(__file__),'script_sha256')]:
  if sha(path)!=p[key]:raise ValueError('Hash mismatch '+key)
 if (OUT/'results.json').exists():raise FileExistsError('Results already exist')
 images={x['id']:x['sha256'] for x in download['images']};objects=[make_object(r,images) for r in sel['sources']];torch.set_num_threads(4);special=YOLO(str(SPECIAL));generic=YOLO(str(old.DETECTOR));records=[]
 for pair in range(3):
  path=BG/f'field-{pair+1:02d}.png'
  if sha(path)!=p['background_sha256'][pair]:raise ValueError('Background changed')
  bg=Image.open(path).convert('RGB').resize((512,512),Image.Resampling.LANCZOS)
  for condition in ('separated','crossing'):
   start=time.monotonic();canvas=np.array(bg);full=[np.zeros((512,512),bool),np.zeros((512,512),bool)];(a,am),(b,bm)=objects[2*pair:2*pair+2];locations=([(160,256),(352,256)] if condition=='separated' else [(256,256),(266,256)])
   for i,(crop,mask) in enumerate(((a,am),(b,bm))):old.paste(canvas,full[i],crop,mask,*locations[i])
   visible=[full[0]&~full[1],full[1]];image=Image.fromarray(canvas);bgr=cv2.cvtColor(canvas,cv2.COLOR_RGB2BGR)
   sp=special.predict(bgr,imgsz=640,conf=.25,iou=.7,device='cpu',retina_masks=True,verbose=False)[0];sm=[] if sp.masks is None else [m.astype(bool) for m in sp.masks.data.cpu().numpy()]
   det=generic.predict(bgr,imgsz=512,conf=.05,device='cpu',verbose=False)[0];boxes=det.boxes.xyxy.cpu().numpy().tolist() if det.boxes is not None else [];gm=[]
   if boxes:
    predictor=Predictor(overrides={'model':str(old.SAM),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});predictor.set_image(bgr);result=predictor(bboxes=boxes,verbose=False)[0];gm=[] if result.masks is None else [m.astype(bool) for m in result.masks.data.cpu().numpy()]
   metrics={}
   for name,masks in [('specialist',sm),('generic_box_sam',gm)]:metrics[name]={'candidates':len(masks),'visible':old.assign(visible,masks,.5),'full':old.assign(full,masks,.5)}
   idx=len(records)+1;records.append({'pair':pair+1,'condition':condition,'background':str(path.relative_to(ROOT)),'source_ids':[sel['sources'][2*pair]['id'],sel['sources'][2*pair+1]['id']],'shared_pixels':int((full[0]&full[1]).sum()),'visible_areas':[int(x.sum()) for x in visible],'full_areas':[int(x.sum()) for x in full],'scores':metrics,'seconds':time.monotonic()-start})
   panel=Image.new('RGB',(1440,410),'#f3f6ef');draw=ImageDraw.Draw(panel)
   for col,(label,masks) in enumerate([('Visible reference masks',visible),('Marine specialist masks',sm),('Generic box-to-SAM masks',gm),('Full source masks',full)]):
    out=overlay(image,masks);out.thumbnail((344,344));panel.paste(out,(col*360+8,45));draw.text((col*360+8,8),label,fill='#203a38')
   panel.save(OUT/f'scene-{idx:02d}.jpg',quality=88);print(f"{idx}/6 {condition} shared {records[-1]['shared_pixels']} specialist {metrics['specialist']['visible']['matched']} generic {metrics['generic_box_sam']['visible']['matched']}",flush=True)
 payload={'format':'l42-synthetic-transfer-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Opaque composites on previously seen real backgrounds; background objects unlabeled, source mask mapping structural, biological sample independence/model training overlap unknown. Not real overlap or slide accuracy.'};(OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n');print('Synthetic transfer experiment complete.',flush=True)
if __name__=='__main__':main()
