"""Apply L19's fixed grid and confidence-ranked budgets to R25 cases."""
import hashlib
import itertools
import json
import time
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
from ultralytics.models.sam import Predictor

ROOT = Path(__file__).resolve().parent.parent
rows = json.loads((ROOT / 'results/l24/overlap-audit.json').read_text())['overlap_pairs']
torch.set_num_threads(4)
records = []


def matching(scores, limit):
    choices = [None] + list(range(limit))
    feasible = [pair for pair in itertools.product(choices, repeat=2)
                if (pair[0] is None or pair[1] is None or pair[0] != pair[1])
                and all(j is None or scores[k][j] >= .5 for k, j in enumerate(pair))]
    return max(feasible, key=lambda pair: (sum(j is not None for j in pair),
               sum(scores[k][j] for k, j in enumerate(pair) if j is not None)))


for source_index in (3, 4):
    row = rows[source_index - 1]
    path = Path(f'/tmp/diatom-l24-overlap/{source_index:02}.jpg')
    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())
    annotations = [next(a for a in source['annotations'] if a['id'] == ident)
                   for ident in row['annotation_ids_first_variant']]
    refs = []
    for annotation in annotations:
        original = np.zeros((row['height'], row['width']), np.uint8)
        for polygon in annotation['segmentation']:
            cv2.fillPoly(original, [np.rint(np.asarray(polygon).reshape(-1, 2)).astype('int32')], 1)
        refs.append(cv2.resize(original, (768, 576), interpolation=cv2.INTER_NEAREST).astype(bool))
    predictor = Predictor(overrides={'model': '/tmp/mobile_sam.pt', 'task': 'segment', 'mode': 'predict',
        'imgsz': 768, 'device': 'cpu', 'retina_masks': True, 'verbose': False, 'save': False, 'conf': 0.0})
    started = time.monotonic()
    predictor.set_image(cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
    points = [(x, y) for y in range(32, 576, 64) for x in range(32, 768, 64)]
    candidates = []
    for n in range(0, len(points), 12):
        batch = points[n:n + 12]
        prediction = predictor(points=[[[x, y]] for x, y in batch], labels=[[1] for _ in batch], verbose=False)[0]
        if prediction.masks is None:
            continue
        for raw, confidence in zip(prediction.masks.data.cpu().numpy(), prediction.boxes.conf.cpu().numpy()):
            mask = raw.astype(bool)
            if mask.shape != (576, 768):
                raise ValueError('Unexpected mask shape')
            area = int(mask.sum())
            if 300 <= area <= 50000 and float(confidence) >= .6:
                candidates.append({'mask': mask, 'score': float(confidence), 'area': area})
    kept = []
    for candidate in sorted(candidates, key=lambda x: -x['score']):
        duplicate = False
        for previous in kept:
            common = int((candidate['mask'] & previous['mask']).sum())
            union = candidate['area'] + previous['area'] - common
            if union and common / union >= .8:
                duplicate = True
                break
        if not duplicate:
            kept.append(candidate)
    scores = [[float((ref & c['mask']).sum() / (ref | c['mask']).sum()) for c in kept] for ref in refs]
    budgets = {}
    for budget in (5, 10, 20, len(kept)):
        actual = min(budget, len(kept))
        match = matching(scores, actual)
        budgets[str(budget)] = {'candidates_considered': actual, 'matched_indices': list(match),
            'matched_ious': [None if j is None else scores[k][j] for k, j in enumerate(match)]}
    record = {'filename': row['filename'], 'image_sha256': hashlib.sha256(path.read_bytes()).hexdigest(), 'grid_points': len(points),
              'after_filter': len(candidates), 'after_suppression': len(kept),
              'candidates': [{'score': x['score'], 'area_pixels': x['area']} for x in kept],
              'target_mask_ious': scores, 'budgets': budgets, 'elapsed_seconds': time.monotonic() - started}
    records.append(record)
    print(row['filename'], 'retained', len(kept), 'budgets', budgets, flush=True)
out = ROOT / 'results/l25'
out.mkdir(parents=True, exist_ok=True)
(out / 'grid-results.json').write_text(json.dumps({'spacing': 64, 'offset': 32, 'score_min': .6,
    'area_range': [300, 50000], 'suppression_iou': .8, 'match_iou': .5, 'records': records}, indent=2) + '\n')
