"""Score one-to-one detector proposals and prompted masks on three annotated pairs."""
import itertools
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 r18_pair_data import load_pair
from r5_link_planes import iou

selection=json.loads((ROOT/'results/r18/selection.json').read_text())['selected_pairs']
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)
detector=YOLO('yolov8n.yaml',task='detect');detector.model=ckpt['model'].float();segmenter=SAM('/tmp/mobile_sam.pt')
font=ImageFont.truetype('DejaVuSans.ttf',15);plate=Image.new('RGB',(1320,len(selection)*410),'#f8f8f2');draw=ImageDraw.Draw(plate)
records=[]
for i,row in enumerate(selection,1):
    image,refs,path=load_pair(i,row)
    refboxes=[]
    for ref in refs:
        y,x=np.where(ref);refboxes.append([int(x.min()),int(y.min()),int(x.max()+1),int(y.max()+1)])
    prediction=detector.predict(cv2.cvtColor(image,cv2.COLOR_RGB2BGR),imgsz=768,conf=.05,device='cpu',verbose=False)[0]
    boxes=prediction.boxes.xyxy.cpu().tolist();conf=prediction.boxes.conf.cpu().tolist()
    scores=[[iou(refbox,box) for box in boxes] for refbox in refboxes]
    # Exhaustively select at most one distinct predicted box per reference;
    # maximize match count, then summed IoU. This is scoring, not inference.
    choices=[None]+list(range(len(boxes)))
    valid=[]
    for assignment in itertools.product(choices,repeat=2):
        chosen=[v for v in assignment if v is not None]
        if len(set(chosen))!=len(chosen):continue
        if any(j is not None and scores[k][j]<.5 for k,j in enumerate(assignment)):continue
        valid.append(assignment)
    match=max(valid,key=lambda a:(sum(j is not None for j in a),sum(scores[k][j] for k,j in enumerate(a) if j is not None)))
    masks=[];maskious=[]
    for k,j in enumerate(match):
        if j is None:masks.append(None);maskious.append(None);continue
        pred=segmenter.predict(cv2.cvtColor(image,cv2.COLOR_RGB2BGR),bboxes=boxes[j],imgsz=768,device='cpu',retina_masks=True,verbose=False)[0]
        if pred.masks is None or len(pred.masks.data)!=1:raise ValueError('Expected one mask per prompt')
        m=pred.masks.data[0].cpu().numpy().astype(bool)
        if m.shape!=refs[k].shape:raise ValueError('Wrong mask shape')
        masks.append(m);maskious.append(float(np.logical_and(m,refs[k]).sum()/np.logical_or(m,refs[k]).sum()))
    records.append({'image_file':row['image']['file_name'],'annotation_ids':row['annotation_ids'],'reference_boxes':refboxes,
                    'predictions':[{'xyxy':b,'confidence':c} for b,c in zip(boxes,conf)],'box_iou_by_target':scores,
                    'matched_prediction_indices':list(match),'matched_mask_iou':maskious})
    union=np.logical_or(*refs);ys,xs=np.where(union);left=max(0,int(xs.min())-55);right=min(image.shape[1],int(xs.max())+56);top=max(0,int(ys.min())-55);bottom=min(image.shape[0],int(ys.max())+56)
    views=[('Reference polygons',refs),('All detector boxes',None),('Matched box masks',masks)]
    for col,(title,overlays) in enumerate(views):
        im=Image.fromarray(image).convert('RGBA')
        if overlays is not None:
            for mask,color in zip(overlays,[(0,185,150,100),(238,80,155,100)]):
                if mask is None:continue
                layer=Image.new('RGBA',im.size,color);layer.putalpha(Image.fromarray(mask.astype('uint8')*color[3]));im=Image.alpha_composite(im,layer)
        d=ImageDraw.Draw(im)
        if col==1:
            for box in boxes:d.rectangle(box,outline='#00d6ad',width=2)
        crop=im.convert('RGB').crop((left,top,right,bottom));crop.thumbnail((390,330),Image.Resampling.LANCZOS)
        x=col*440+8;y=(i-1)*410+50;plate.paste(crop,(x,y));draw.text((x,(i-1)*410+5),f'{i}. {title}',font=font,fill='#193b36')
        if col==2:draw.text((x,(i-1)*410+25),'IoUs '+', '.join('miss' if v is None else f'{v:.2f}' for v in maskious),font=font,fill='#193b36')
    print(row['image']['file_name'],'boxes',len(boxes),'assigned',match,'mask IoUs',maskious,flush=True)
OUT=ROOT/'results/r18';plate.save(OUT/'auto-pairs.jpg',quality=90)
(OUT/'auto-pairs.json').write_text(json.dumps({'box_iou_threshold':.5,'confidence_threshold':.05,'records':records},indent=2))
