"""Toy focal mixtures on real stacks: compare oracle focus cues and automatic proposals."""
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,r56_synthetic_compare as objects,l43_proposals as render
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l46';SRC=Path('/tmp/diatom-r56-public');sys.path.insert(0,str(ROOT/'diatom_pilot'))
from focal_profiles import focus_profiles
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def object_residual(row,hashes):
 ident=row['id'];crop,mask=objects.crop_source(row,hashes);raw=np.asarray(Image.open(SRC/(ident+'-image.png')).convert('L'));median=float(np.median(raw));gray=cv2.cvtColor(crop,cv2.COLOR_RGB2GRAY).astype('float32');return np.clip(gray-median,-100,100)*mask,mask

def place(delta,mask,cx,cy):
 h,w=mask.shape;l=int(cx-w//2);t=int(cy-h//2)
 if l<0 or t<0 or l+w>512 or t+h>512:raise ValueError('Object outside canvas')
 layer=np.zeros((512,512),'float32');full=np.zeros((512,512),bool);layer[t:t+h,l:l+w]=delta;full[t:t+h,l:l+w]=mask;return layer,full

def graph(draw,box,profiles,background):
 l,t,r,b=box;draw.rectangle(box,outline='#b3c7be',width=2);colors=['#00836a','#bc4c45']
 for j,v in enumerate(profiles):
  lo=min(v);hi=max(v);norm=[(x-lo)/max(hi-lo,1e-9) for x in v];pts=[(l+10+k*(r-l-20)/4,b-10-y*(b-t-20)) for k,y in enumerate(norm)];draw.line(pts,fill=colors[j],width=3)
  for x,y in pts:draw.ellipse((x-3,y-3,x+3,y+3),fill=colors[j])
 draw.text((l+5,b+4),'0        1        2        3        4   plane index',fill='#203a38')

def main():
 p=json.loads((OUT/'protocol.json').read_text());s=json.loads((OUT/'selection.json').read_text());sel=json.loads((ROOT/'results/r56/usable-selection.json').read_text());dl=json.loads((ROOT/'results/r56/download.json').read_text());bginfo=json.loads((OUT/'backgrounds.json').read_text())
 for path,key in [(OUT/'selection.json','selection_sha256'),(OUT/'backgrounds.npz','backgrounds_sha256'),(OUT/'backgrounds.json','background_metadata_sha256'),(ROOT/'results/r56/usable-selection.json','sources_sha256'),(ROOT/'results/r56/download.json','source_download_sha256'),(base.SAM,'sam_sha256'),(base.DETECTOR,'detector_sha256'),(ROOT/'diatom_pilot/focal_profiles.py','focus_code_sha256'),(Path(objects.__file__),'source_code_sha256'),(Path(__file__),'script_sha256')]:
  if sha(path)!=p[key]:raise ValueError('Frozen input mismatch '+key)
 if (OUT/'results.json').exists():raise FileExistsError('Preserve previous result')
 if [r['id'] for r in sel['sources'][:6]]!=s['source_ids']:raise ValueError('Source selection changed')
 hashes={r['id']:r['sha256'] for r in dl['images']};foreground=[object_residual(r,hashes) for r in sel['sources'][:6]];torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));records=[]
 with np.load(OUT/'backgrounds.npz',allow_pickle=False) as saved:
  for pair in range(3):
   original=saved[f'field_{pair+1}']
   for z in range(5):
    if hashlib.sha256(original[z].tobytes()).hexdigest()!=bginfo['fields'][pair]['plane_sha256'][z]:raise ValueError('Background plane changed')
   backs=np.stack([cv2.resize(a,(512,512),interpolation=cv2.INTER_AREA) for a in original])
   for kind in ('separated','crossing'):
    start=time.monotonic();positions=([(160,256),(352,256)] if kind=='separated' else [(256,256),(266,256)]);layers=[];full=[]
    for (delta,mask),(x,y) in zip(foreground[2*pair:2*pair+2],positions):
     a,b=place(delta,mask,x,y);layers.append(a);full.append(b)
    exclusive=[full[0]&~full[1],full[1]&~full[0]]
    if any(int(x.sum())<30 for x in exclusive):raise ValueError('Insufficient exclusive reference area')
    composite=[]
    for z in range(5):
     result=backs[z].astype('float32')
     for layer,peak in zip(layers,(1,3)):result=result+.65*cv2.GaussianBlur(layer,(0,0),.5+1.5*abs(z-peak))
     composite.append(np.clip(result,0,255).astype('uint8'))
    planes=np.stack(composite);profiles=focus_profiles(planes,full);exclusive_profiles=focus_profiles(planes,exclusive);background_profiles=focus_profiles(backs,full);peaks=[int(np.argmax(x)) for x in profiles];exclusive_peaks=[int(np.argmax(x)) for x in exclusive_profiles];background_peaks=[int(np.argmax(x)) for x in background_profiles];boxes=[]
    for mask in full:
     ys,xs=np.nonzero(mask);boxes.append([int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)])
    oracleious=[[],[]];perplane=[];candidate_records=[]
    for z in range(5):
     bgr=cv2.cvtColor(planes[z],cv2.COLOR_GRAY2BGR);yp=detector.predict(bgr,imgsz=512,conf=.05,device='cpu',verbose=False)[0];detboxes=yp.boxes.xyxy.cpu().numpy().tolist() if yp.boxes is not None else [];pred=Predictor(overrides={'model':str(base.SAM),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});pred.set_image(bgr)
     op=pred(bboxes=boxes,verbose=False)[0]
     if op.masks is None or len(op.masks.data)!=2:raise ValueError('Unexpected oracle masks')
     for j,m in enumerate(op.masks.data.cpu().numpy()):oracleious[j].append(base.iou(full[j],m.astype(bool)))
     if detboxes:
      out=pred(bboxes=detboxes,verbose=False)[0];auto=[] if out.masks is None else [{'id':f'z{z}-{j}','z':z,'mask':m.astype(bool)} for j,m in enumerate(out.masks.data.cpu().numpy())]
     else:auto=[]
     perplane.append(auto);candidate_records.append({'z':z,'boxes':detboxes,'candidate_count':len(auto)})
    order=(2,1,3,0,4);pool=[]
    for j in range(max((len(x) for x in perplane),default=0)):
     for z in order:
      if j<len(perplane[z]):pool.append(perplane[z][j])
    dedup=[];aliases=[]
    for c in pool:
     duplicate=next((q for q in dedup if base.iou(c['mask'],q['mask'])>=.8),None)
     if duplicate is None:dedup.append(c)
     else:aliases.append({'candidate':c['id'],'kept':duplicate['id']})
    methods={'single_middle':perplane[2],'multi_plane':dedup};scores={}
    for name,candidates in methods.items():
     scores[name]={'candidate_count':len(candidates)}
     for cut in (10,20):scores[name][f'top{cut}']=base.assign(full,[c['mask'] for c in candidates[:cut]],.5)
     scores[name]['all']=base.assign(full,[c['mask'] for c in candidates],.5)
    n=len(records)+1
    # All raw masks are saved, including cross-plane suppressed alternatives.
    packed=np.packbits(np.stack([c['mask'] for c in pool],axis=0),axis=None) if pool else np.array([],dtype='uint8')
    np.savez_compressed(OUT/f'scene-{n:02d}.npz',planes=planes,full_masks=np.stack(full),exclusive_masks=np.stack(exclusive),candidate_bits=packed,candidate_shape=np.array([len(pool),512,512],dtype='int32'),candidate_ids=np.array([c['id'] for c in pool]),candidate_z=np.array([c['z'] for c in pool],dtype='int8'))
    records.append({'pair':pair+1,'kind':kind,'source_ids':s['source_ids'][2*pair:2*pair+2],'background_slide':bginfo['fields'][pair]['slide'],'origin_xy':bginfo['fields'][pair]['origin_xy'],'plane_indices':s['backgrounds'][pair]['plane_indices'],'synthetic_peak_indices':[1,3],'overlap_pixels':int((full[0]&full[1]).sum()),'full_areas':[int(x.sum()) for x in full],'exclusive_areas':[int(x.sum()) for x in exclusive],'profiles':profiles,'exclusive_profiles':exclusive_profiles,'background_only_profiles':background_profiles,'profile_peaks':peaks,'exclusive_profile_peaks':exclusive_peaks,'background_only_peaks':background_peaks,'oracle_box_iou_by_plane':oracleious,'automatic_per_plane':candidate_records,'automatic_scores':scores,'suppression_aliases':aliases,'archive':f'scene-{n:02d}.npz','seconds':time.monotonic()-start})
    panel=Image.new('RGB',(1450,735),'#f3f6ef');draw=ImageDraw.Draw(panel)
    for z in range(5):
     im=Image.fromarray(planes[z]).convert('RGB');im.thumbnail((270,270));panel.paste(im,(z*290+10,32));draw.text((z*290+10,8),f'Simulated plane {z}',fill='#203a38')
    for col,(label,masks) in enumerate([('Amodal source masks',full),('Automatic middle plane',[c['mask'] for c in perplane[2]]),('Automatic multi-plane top 20',[c['mask'] for c in dedup[:20]])]):
     im=render.overlay(Image.fromarray(planes[2]).convert('RGB'),masks);im.thumbnail((260,260));panel.paste(im,(col*290+10,350));draw.text((col*290+10,325),label,fill='#203a38')
    draw.text((895,325),'Oracle mask contrast profiles',fill='#203a38');graph(draw,(895,350,1375,610),profiles,background_profiles);draw.text((895,645),'Green peak intended: 1; red peak intended: 3',fill='#203a38');panel.save(OUT/f'scene-{n:02d}.jpg',quality=88)
    print(f"{n}/6 {kind} peaks {peaks} auto middle {scores['single_middle']['top20']['matched']} multi {scores['multi_plane']['top20']['matched']}",flush=True)
 (OUT/'results.json').write_text(json.dumps({'format':'l46-toy-focal-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Toy additive Gaussian-blur mixtures on real previously inspected backgrounds. True underlying optical depth and per-object real focus are not known. Source masks are structural; focus scores use oracle source masks and oracle boxes. Automatic proposal results are synthetic only, not real-overlap or Academy accuracy.'},indent=2)+'\n');print('Toy focal comparison complete.',flush=True)
if __name__=='__main__':main()
