"""Evaluate frozen proposals and conditional prompts on two overlap candidates.

Input images and source masks remain in /tmp; result JSON contains scores only.
The two cases were selected using reference polygons and are development data.
"""
import hashlib
import itertools
import json
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
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 r5_link_planes import iou

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()
sam = SAM('/tmp/mobile_sam.pt')
rows = json.loads((ROOT / 'results/l24/overlap-audit.json').read_text())['overlap_pairs']
records = []
for source_index in (3, 4):
    row = rows[source_index-1]
    path = Path(f'/tmp/diatom-l24-overlap/{source_index:02}.jpg')
    image = np.array(Image.open(path).convert('RGB').resize((768, 576), Image.Resampling.LANCZOS))
    source = json.loads((Path('/tmp/diatom-mask-coco') / row['variants'][0]).read_text())
    annotations = [next(a for a in source['annotations'] if a['id'] == ann_id)
                   for ann_id in row['annotation_ids_first_variant']]
    refs = []
    for ann in annotations:
        mask = np.zeros((row['height'], row['width']), dtype=np.uint8)
        for polygon in ann['segmentation']:
            cv2.fillPoly(mask, [np.rint(np.asarray(polygon).reshape(-1, 2)).astype('int32')], 1)
        refs.append(cv2.resize(mask, (768, 576), interpolation=cv2.INTER_NEAREST).astype(bool))
    bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    refboxes, points = [], []
    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)])
        dist = cv2.distanceTransform(ref.astype('uint8'), cv2.DIST_L2, 5)
        py, px = np.unravel_index(dist.argmax(), dist.shape)
        points.append([int(px), int(py)])
    pred = detector.predict(bgr, imgsz=768, conf=.05, device='cpu', verbose=False)[0]
    boxes, confidence = pred.boxes.xyxy.cpu().tolist(), pred.boxes.conf.cpu().tolist()
    scores = [[iou(refbox, box) for box in boxes] for refbox in refboxes]
    choices = [None] + list(range(len(boxes)))
    eligible = [a for a in itertools.product(choices, repeat=2)
                if len([x for x in a if x is not None]) == len(set(x for x in a if x is not None))
                and all(j is None or scores[k][j] >= .5 for k,j in enumerate(a))]
    match = max(eligible, 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)))
    def mask_for(**kwargs):
        result = sam.predict(bgr, imgsz=768, device='cpu', retina_masks=True, verbose=False, **kwargs)[0]
        if result.masks is None or len(result.masks.data) != 1:
            raise ValueError('Expected exactly one prompted mask')
        mask = result.masks.data[0].cpu().numpy().astype(bool)
        if mask.shape != refs[0].shape:
            raise ValueError('Unexpected mask shape')
        return mask
    def mask_iou(mask, ref):
        return float((mask & ref).sum() / (mask | ref).sum())
    variants = {}
    for name, use_negative in [('positive_only', False), ('neighbor_negative', True)]:
        masks = []
        for j in range(2):
            p = [points[j]] + ([points[1-j]] if use_negative else [])
            labels = [1] + ([0] if use_negative else [])
            masks.append(mask_for(points=[p], labels=[labels]))
        variants[name] = {'mask_iou': [mask_iou(mask, ref) for mask,ref in zip(masks,refs)],
                          'mask_intersection_pixels': int((masks[0] & masks[1]).sum())}
    detected_masks = []
    for k, j in enumerate(match):
        detected_masks.append(None if j is None else mask_iou(mask_for(bboxes=boxes[j]), refs[k]))
    records.append({'filename': row['filename'], 'image_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
                    'annotation_file': row['variants'][0], 'annotation_ids': row['annotation_ids_first_variant'],
                    'reference_overlap_pixels_resized': int((refs[0] & refs[1]).sum()),
                    'reference_boxes': refboxes, 'reference_derived_points': points,
                    'detector_predictions': [{'xyxy': b, 'confidence': c} for b,c in zip(boxes,confidence)],
                    'box_iou_by_target': scores, 'matched_prediction_indices': list(match),
                    'detector_box_mask_iou': detected_masks, 'oracle_point_variants': variants})
    print(row['filename'], 'predictions', len(boxes), 'assignment', match,
          'prompt IoUs', {k: [round(v, 3) for v in x['mask_iou']] for k,x in variants.items()}, flush=True)
out = ROOT / 'results/r25'
out.mkdir(parents=True, exist_ok=True)
(out / 'candidate-results.json').write_text(json.dumps({'image_size': [768,576],
    'detector_confidence': .05, 'matching_box_iou': .5, 'records': records}, indent=2) + '\n')
