"""Evaluate detector-proposed boxes and conditional masks against six polygons."""
import json
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont
from ultralytics import SAM,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.insert(0,str(ROOT/'research'))
from r16_data import load_case
from r5_link_planes import iou

OUT=ROOT/'results/r16';selection=json.loads((OUT/'selection.json').read_text())['selection']
oracle=json.loads((OUT/'prompted-masks.json').read_text())['records']
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):checkpoint=torch.load('/tmp/diatom-detector.pt',map_location='cpu',weights_only=True)
detector=YOLO('yolov8n.yaml',task='detect');detector.model=checkpoint['model'].float();segmenter=SAM('/tmp/mobile_sam.pt')
font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1300,len(selection)*360),'#f8f8f2');draw=ImageDraw.Draw(plate)
records=[]
for i,entry in enumerate(selection,1):
    image,ref,path=load_case(i,entry);ys,xs=np.where(ref)
    reference_box=[int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)]
    result=detector.predict(cv2.cvtColor(image,cv2.COLOR_RGB2BGR),imgsz=768,conf=.05,device='cpu',verbose=False)[0]
    boxes=result.boxes.xyxy.cpu().tolist();scores=result.boxes.conf.cpu().tolist()
    overlap=[iou(box,reference_box) for box in boxes]
    matched_index=int(np.argmax(overlap)) if overlap and max(overlap)>=.5 else None
    mask=None;mask_iou=None
    if matched_index is not None:
        p=segmenter.predict(cv2.cvtColor(image,cv2.COLOR_RGB2BGR),bboxes=boxes[matched_index],imgsz=768,device='cpu',retina_masks=True,verbose=False)[0]
        if p.masks is None or len(p.masks.data)!=1:raise ValueError('Expected one prompted mask')
        mask=p.masks.data[0].cpu().numpy().astype(bool)
        if mask.shape!=ref.shape:raise ValueError('Unexpected mask shape')
        mask_iou=float(np.logical_and(mask,ref).sum()/np.logical_or(mask,ref).sum())
    target={'image_file':entry['image']['file_name'],'category':entry['category'],'reference_box_xyxy':reference_box,
            'detection_boxes':[{'xyxy':b,'confidence':s,'bbox_iou_with_reference':v} for b,s,v in zip(boxes,scores,overlap)],
            'match_threshold_iou':.5,'matched_index':matched_index,'matched_mask_iou':mask_iou,
            'oracle_box_mask_iou':next(v['iou'] for v in oracle[i-1]['variants'] if v['prompt']=='box')}
    records.append(target)
    margin=75;left=max(0,reference_box[0]-margin);top=max(0,reference_box[1]-margin)
    right=min(ref.shape[1],reference_box[2]+margin);bottom=min(ref.shape[0],reference_box[3]+margin)
    contours,_=cv2.findContours(ref,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    lines=[[(int(x),int(y)) for x,y in c[:,0,:]] for c in contours]
    for col,title in enumerate(('Reference','Detector proposals','Matched box mask')):
        view=Image.fromarray(image).convert('RGBA')
        if col==2 and mask is not None:
            layer=Image.new('RGBA',view.size,(0,185,150,0));layer.putalpha(Image.fromarray(mask.astype('uint8')*105));view=Image.alpha_composite(view,layer)
        d=ImageDraw.Draw(view)
        for line in lines:
            if len(line)>1:d.line(line+[line[0]],fill='#ffce36',width=2)
        if col==1:
            for b in boxes:d.rectangle(b,outline='#00d6ad',width=2)
        if col==2 and matched_index is not None:d.rectangle(boxes[matched_index],outline='#ed4ab5',width=2)
        crop=view.convert('RGB').crop((left,top,right,bottom));crop.thumbnail((390,300),Image.Resampling.LANCZOS)
        x=col*430+8;y=(i-1)*360+50;plate.paste(crop,(x,y))
        suffix='' if col!=2 else (' · no matched box' if mask_iou is None else f' · mask IoU {mask_iou:.2f}')
        draw.text((x,(i-1)*360+5),f'{i} · {title}{suffix}',font=font,fill='#193b36')
    print(i,entry['image']['file_name'],'detector boxes',len(boxes),'best box IoU',round(max(overlap),3) if overlap else None,'mask IoU',round(mask_iou,3) if mask_iou is not None else None,flush=True)
plate.save(OUT/'automatic-pipeline.jpg',quality=90)
(OUT/'automatic-pipeline.json').write_text(json.dumps({'box_match_iou':.5,'confidence_threshold':.05,'records':records},indent=2))
