"""Compare frozen detection on raw planes and a hard local-contrast focus composite."""
import json
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont,ImageOps
from ultralytics import YOLO
from ultralytics.nn.tasks import DetectionModel
from ultralytics.nn.modules import Conv,C2f,Bottleneck,SPPF,Concat,Detect,DFL
from torch.nn import Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,Identity,MaxPool2d,Upsample

ROOT=Path(__file__).resolve().parent.parent
sys.path[:0]=[str(ROOT/'experiments'),str(ROOT/'research')]
from scan_fields import Stack
from r1_anchor_matching import maximum_matching

torch.set_num_threads(4)
allowed=[DetectionModel,Conv,C2f,Bottleneck,SPPF,Concat,Detect,DFL,Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,Identity,MaxPool2d,Upsample,set]
with torch.serialization.safe_globals(allowed):
    ckpt=torch.load('/tmp/diatom-detector.pt',map_location='cpu',weights_only=True)
model=YOLO('yolov8n.yaml',task='detect');model.model=ckpt['model'].float()
fields=json.loads((ROOT/'results/diatom-practice-round1.json').read_text())['fields']
baseline=json.loads((ROOT/'results/r3/predictions-0.05.json').read_text())
out=ROOT/'results/l16';out.mkdir(exist_ok=True)
font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1320,len(fields)*440),'#f8f8f2');draw=ImageDraw.Draw(plate)
records=[]
for i,field in enumerate(fields):
    base=next(r for r in baseline if r['slide']==field['slide'] and r['field']==field['field'])
    with Stack(ROOT/'scans'/field['slide']) as stack:
        planes=np.stack([np.asarray(stack.field(z,*field['origin_xy'],768)) for z in range(stack.depth)])
    # A local average of squared Laplacian is a rough contrast proxy, not optical depth.
    scores=np.stack([cv2.GaussianBlur(cv2.Laplacian(p.astype(np.float32),cv2.CV_32F,ksize=3)**2,(0,0),5) for p in planes])
    choice=np.argmax(scores,axis=0).astype('uint8')
    composite=np.take_along_axis(planes,choice[None],axis=0)[0]
    Image.fromarray(composite).save(out/f'composite-{i+1}.png')
    Image.fromarray(choice).save(out/f'focus-index-{i+1}.png')
    pred=model.predict(np.repeat(composite[:,:,None],3,axis=2),imgsz=768,conf=.05,device='cpu',verbose=False)[0]
    fused_boxes=pred.boxes.xyxy.cpu().tolist();full_boxes=[b['xyxy'] for b in base['boxes']]
    points=[(m['x'],m['y']) for m in field['marks'] if m['kind']=='Possible diatom']
    counts={}
    for name,boxes in [('recorded_plane',full_boxes),('focus_composite',fused_boxes)]:
        counts[name]={'boxes':len(boxes),'one_to_one_marks':len(maximum_matching(points,boxes)[0])}
    records.append({'slide':field['slide'],'field':field['field'],'origin_xy':field['origin_xy'],'recorded_z':base['z'],
                    'z_planes':len(planes),'counts':counts,'composite_boxes':fused_boxes,
                    'composite_confidences':pred.boxes.conf.cpu().tolist(),'composite_file':f'composite-{i+1}.png',
                    'focus_index_file':f'focus-index-{i+1}.png'})
    depth_rgb=cv2.applyColorMap((choice.astype(np.float32)*255/max(len(planes)-1,1)).astype('uint8'),cv2.COLORMAP_TURBO)[:,:,::-1]
    for j,(source,boxes) in enumerate([(planes[base['z']],full_boxes),(composite,fused_boxes),(depth_rgb,[])]):
        im=Image.fromarray(source)
        if j<2:im=ImageOps.autocontrast(im,cutoff=.25).convert('RGB')
        else:im=im.convert('RGB')
        d=ImageDraw.Draw(im)
        if j<2:
            for b in boxes:d.rectangle(b,outline='#00d8ae',width=3)
            for x,y in points:d.ellipse((x-5,y-5,x+5,y+5),outline='#ffcc33',width=3)
        xoff=j*430+8;yoff=i*440+40;plate.paste(im.resize((360,360)),(xoff,yoff))
        title=['Recorded plane','Contrast composite','Chosen Z index'][j]
        draw.text((xoff,i*440+8),f"{field['slide'][:9]} · {title}",font=font,fill='#193b36')
    print(field['slide'][:9],counts,flush=True)
plate.save(out/'focus-fusion.jpg',quality=90)
(out/'focus-fusion.json').write_text(json.dumps({'algorithm':'per-pixel max Gaussian-smoothed squared Laplacian, sigma=5',
 'warning':'Composite and chosen Z are contrast-derived; not ground truth depth. No registration.', 'fields':records},indent=2))
