"""Freeze a small, source-annotation-assisted negative-point experiment."""
import hashlib
import json
from pathlib import Path

import cv2
import numpy as np

from diatom_pilot.ude_scaleup_dataset import sha256

R = Path(__file__).resolve().parents[1]
D = R / 'results/r112/species-breadth-extension'
O = R / 'results/r112/outside-box-prompt-pilot'


def negatives(row):
    """Choose up to four image points outside the rough rotated rectangle."""
    w, h = row['source_dimensions_px']
    x0, y0, *_ = row['source_bbox_global']
    poly = np.asarray(row['source_annotation_points_global'], dtype=np.float32).reshape(-1, 2)
    poly -= np.array([x0, y0], dtype=np.float32)
    center = poly.mean(axis=0)
    bins = {}
    for y in range(0, h, max(1, h // 32)):
        for x in range(0, w, max(1, w // 32)):
            distance = -cv2.pointPolygonTest(poly, (float(x), float(y)), True)
            if distance < 4:
                continue
            quadrant = (x >= center[0], y >= center[1])
            value = (distance, -y, -x)
            if quadrant not in bins or value > bins[quadrant][0]:
                bins[quadrant] = (value, [x, y])
    return [bins[k][1] for k in sorted(bins)]


def main():
    O.mkdir(exist_ok=True)
    assert not (O / 'protocol.json').exists()
    assets = json.loads((D / 'assets.json').read_text())
    q = json.loads((D / 'mask-hypotheses/results.json').read_text())
    verify = json.loads((D / 'mask-hypotheses/verify.json').read_text())
    assert verify['verified_records'] == len(assets['records']) == len(q['records'])
    source = {r['annotation_id']: r for r in assets['records']}
    eligible = []
    for p in q['records']:
        row = source[p['annotation_id']]
        if row['source_annotation_shape'] != 'Rectangle':
            continue
        pts = negatives(row)
        if len(pts) < 2:
            continue
        c = p['center_mask_crop_fraction']
        group = 'high_coverage' if c > .75 else 'reference' if .15 <= c <= .55 else None
        if group:
            eligible.append({'annotation_id': row['annotation_id'], 'group': group,
                             'center_coverage': c, 'negative_points_xy': pts})
    known = ('14048082', '12929072')
    chosen = [next(x for x in eligible if x['annotation_id'] == ident and x['group'] == 'high_coverage') for ident in known]
    key = lambda x: hashlib.sha256(('outside-box-v1:' + x['annotation_id']).encode()).hexdigest()
    chosen += sorted((x for x in eligible if x['group'] == 'high_coverage' and x['annotation_id'] not in known), key=key)[:22]
    chosen += sorted((x for x in eligible if x['group'] == 'reference'), key=key)[:12]
    assert len(chosen) == 36 and len({x['annotation_id'] for x in chosen}) == 36
    files = ['results/r112/species-breadth-extension/assets.json',
             'results/r112/species-breadth-extension/verify.json',
             'results/r112/species-breadth-extension/mask-hypotheses/results.json',
             'results/r112/species-breadth-extension/mask-hypotheses/verify.json',
             'research/r112_outside_box_prompt_select.py',
             'research/r112_outside_box_prompt_run.py']
    protocol = {'format': 'r112-outside-box-prompt-pilot-v1',
                'inputs_sha256': {f: sha256(R / f) for f in files},
                'model_sha256': sha256(Path('/tmp/mobile_sam.pt')),
                'selection': 'Two visually problematic source masks observed in scene 0006 plus 22 hash-selected other center-coverage >75% rectangles and 12 hash-selected 15–55% coverage rectangles. Only rectangles with at least two eligible negative points were selected. This is a deliberately biased, previously examined development sample.',
                'method': 'Reuse MobileSAM and its original grayscale preprocessing and center point; add at most four negative points at least four native pixels outside the rough source rectangle, selecting the farthest grid point in each quadrant. Points outside the source box may still be on diatoms. Evaluate no taxonomic or biological accuracy and retain both original and experimental masks.',
                'warning': 'Source rectangles are rough, target point may be wrong, negative points may hit other organisms, all outputs are unverified shared-model candidates, and lack of expert truth precludes a quality claim.',
                'records': chosen}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    print('frozen', len(chosen), 'cases; eligible high/reference', sum(x['group'] == 'high_coverage' for x in eligible), sum(x['group'] == 'reference' for x in eligible))


if __name__ == '__main__':
    main()
