"""Measure output pixels in other published polygons on used Khanom crops."""
import collections
import json
from pathlib import Path

import cv2
import numpy as np
from PIL import Image

from diatom_pilot.ude_scaleup_dataset import sha256

R = Path(__file__).resolve().parents[1]
O = R / 'results/r118'
K = R / 'results/r112/source-mask-polygon-proxy'
D = R / 'datasets/r84-khanom'


def main():
    results = json.loads((O / 'results.json').read_text())
    proxy = {x['id']: x for x in json.loads((K / 'results.json').read_text())['records']}
    rows, totals = [], collections.Counter()
    for row in results['records']:
        if row['group'] != 'khanom':
            continue
        source = proxy[row['id']]
        coco_path = D / source['source_coco']
        assert sha256(coco_path) == source['source_coco_sha256']
        coco = json.loads(coco_path.read_text())
        target_path = R / row['reference']
        assert sha256(target_path) == row['reference_sha256']
        target = np.asarray(Image.open(target_path).convert('L')) > 0
        pred = {}
        for mode in ('original', 'adapted'):
            item = row['outputs'][mode]
            path = O / item['path']
            assert sha256(path) == item['sha256']
            pred[mode] = np.asarray(Image.open(path).convert('L')) > 0
            assert pred[mode].shape == target.shape
        x0, y0, _, _ = source['crop_bounds_xyxy_exclusive']
        others = []
        for ann in coco['annotations']:
            if ann['image_id'] != source['source_image_id'] or ann['id'] == source['annotation_id']:
                continue
            assert ann['iscrowd'] == 0 and len(ann['segmentation']) == 1
            points = np.asarray(ann['segmentation'][0], dtype=np.float64).reshape(-1, 2)
            raw = np.zeros(target.shape, np.uint8)
            cv2.fillPoly(raw, [np.rint(points - [x0, y0]).astype(np.int32)], 1)
            other = (raw > 0) & ~target
            size = int(other.sum())
            if size == 0:
                continue
            entry = {'source_annotation_id': ann['id'], 'other_exclusive_pixels_in_crop': size}
            for mode in ('original', 'adapted'):
                hit = int((pred[mode] & other).sum())
                entry[mode + '_hit_pixels'] = hit
                entry[mode + '_fraction_of_other_in_crop'] = hit / size
            others.append(entry)
            if size >= 50:
                totals['other_polygon_portions_ge_50_pixels'] += 1
                for mode in ('original', 'adapted'):
                    totals[mode + '_other_portions_hit_ge_half'] += entry[mode + '_fraction_of_other_in_crop'] >= .5
        totals['cases'] += 1
        totals['cases_with_other_polygons_in_crop'] += bool(others)
        for mode in ('original', 'adapted'):
            totals[mode + '_cases_touch_other_polygon'] += any(x[mode + '_hit_pixels'] > 0 for x in others)
            totals[mode + '_cases_cover_half_other_portion_ge_50'] += any(x['other_exclusive_pixels_in_crop'] >= 50 and x[mode + '_fraction_of_other_in_crop'] >= .5 for x in others)
        rows.append({'id': row['id'], 'other_polygons': others})
    assert len(rows) == 29
    out = {'format': 'r118-other-polygon-audit-v1', 'results_sha256': sha256(O / 'results.json'),
           'proxy_sha256': sha256(K / 'results.json'), 'summary': dict(totals),
           'method': 'Rasterize every other published polygon from the same source image into each existing crop, subtract target polygon pixels, and measure overlap of each prediction with the remainder. Threshold ≥50 pixels and ≥50% coverage is an arbitrary post-hoc geometry diagnostic.',
           'warning': 'Crops and prompts are reference-derived, annotations are previously viewed and incomplete, boundaries are not established expert truth. An overlapped polygon portion can be truncated and overlap does not prove a biological merge; unannotated neighbors are unknown.', 'records': rows}
    (O / 'other-polygon-audit.json').write_text(json.dumps(out, indent=2) + '\n')
    print(json.dumps(out['summary'], indent=2))


if __name__ == '__main__':
    main()
