"""Score detector-prompted and grid-prompted masks with a common mask rule.

Uses frozen R25 detector boxes and L25 grid scores. Reference assignments are
posthoc evaluation only. Source image pixels and candidate masks stay in /tmp.
"""
import hashlib
import itertools
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
from ultralytics import SAM

ROOT = Path(__file__).resolve().parent.parent
source_rows = json.loads((ROOT / 'results/l24/overlap-audit.json').read_text())['overlap_pairs']
detector_rows = json.loads((ROOT / 'results/r25/candidate-results.json').read_text())['records']
grid_rows = json.loads((ROOT / 'results/l25/grid-results.json').read_text())['records']
torch.set_num_threads(4)
segmenter = SAM('/tmp/mobile_sam.pt')


def assign(scores, budget, threshold):
    n = min(budget, len(scores[0]))
    options = [None] + list(range(n))
    feasible = [a for a in itertools.product(options, repeat=2)
                if (a[0] is None or a[1] is None or a[0] != a[1])
                and all(j is None or scores[k][j] >= threshold for k, j in enumerate(a))]
    return max(feasible, 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)))


records = []
for source_index, detector, grid in zip((3, 4), detector_rows, grid_rows):
    row = source_rows[source_index - 1]
    assert row['filename'] == detector['filename'] == grid['filename']
    path = Path(f'/tmp/diatom-l24-overlap/{source_index:02}.jpg')
    digest = hashlib.sha256(path.read_bytes()).hexdigest()
    if digest != detector['image_sha256'] or digest != grid['image_sha256']:
        raise ValueError('Image differs from an earlier experiment input')
    image = np.asarray(Image.open(path).convert('RGB').resize((768, 576), Image.Resampling.LANCZOS))
    source = json.loads((Path('/tmp/diatom-mask-coco') / row['variants'][0]).read_text())
    refs = []
    for ident in row['annotation_ids_first_variant']:
        annotation = next(a for a in source['annotations'] if a['id'] == ident)
        raw = np.zeros((row['height'], row['width']), np.uint8)
        for polygon in annotation['segmentation']:
            cv2.fillPoly(raw, [np.rint(np.asarray(polygon).reshape(-1, 2)).astype('int32')], 1)
        refs.append(cv2.resize(raw, (768, 576), interpolation=cv2.INTER_NEAREST).astype(bool))
    predictions = sorted(detector['detector_predictions'], key=lambda p: -p['confidence'])
    scores = [[], []]
    for prediction in predictions:
        result = segmenter.predict(cv2.cvtColor(image, cv2.COLOR_RGB2BGR), bboxes=prediction['xyxy'],
                imgsz=768, device='cpu', retina_masks=True, verbose=False)[0]
        if result.masks is None or len(result.masks.data) != 1:
            raise ValueError('Expected one mask for each detector proposal')
        mask = result.masks.data[0].cpu().numpy().astype(bool)
        if mask.shape != refs[0].shape:
            raise ValueError('Unexpected mask shape')
        for k, ref in enumerate(refs):
            scores[k].append(float((mask & ref).sum() / (mask | ref).sum()))
    methods = {'detector_box_prompts': {'ranking': 'YOLO confidence', 'scores': scores,
                                       'candidates': len(predictions)},
               'regular_grid_prompts': {'ranking': 'MobileSAM mask quality', 'scores': grid['target_mask_ious'],
                                        'candidates': grid['after_suppression']}}
    for method in methods.values():
        method['budgets'] = {}
        for threshold in (.5, .75):
            method['budgets'][str(threshold)] = {}
            for budget in (5, 10, 20):
                pair = assign(method['scores'], budget, threshold)
                method['budgets'][str(threshold)][str(budget)] = {
                    'considered': min(budget, method['candidates']),
                    'matched_indices': list(pair),
                    'matched_ious': [None if j is None else method['scores'][k][j] for k, j in enumerate(pair)]}
    records.append({'filename': row['filename'], 'methods': methods})
    print(row['filename'], {name: {b: v['matched_ious'] for b, v in method['budgets']['0.5'].items()}
                            for name, method in methods.items()}, flush=True)
out = ROOT / 'results/r26'
out.mkdir(parents=True, exist_ok=True)
(out / 'common-budget.json').write_text(json.dumps({'mask_iou_thresholds': [.5, .75],
    'budgets': [5, 10, 20], 'records': records}, indent=2) + '\n')
