"""Check saved cross-source decoder masks and compute development summaries."""
import collections
import json
import math
from pathlib import Path

import numpy as np
from PIL import Image

from diatom_pilot.ude_scaleup_dataset import sha256
from r118_decoder_source_transfer import iou

R = Path(__file__).resolve().parents[1]
O = R / 'results/r118'
K = R / 'results/r112/source-mask-polygon-proxy'
U = R / 'results/r112/species-breadth-extension'
P = R / 'results/r112/outside-box-prompt-pilot'


def main():
    p = json.loads((O / 'protocol.json').read_text())
    result = json.loads((O / 'results.json').read_text())
    assert result['protocol_sha256'] == sha256(O / 'protocol.json') and sha256(Path('/tmp/mobile_sam.pt')) == p['mobile_sam_sha256']
    for f, digest in p['inputs_sha256'].items():
        assert sha256(R / f) == digest
    kh = {x['id']: x for x in json.loads((K / 'results.json').read_text())['records']}
    ude = {x['annotation_id']: x for x in json.loads((U / 'assets.json').read_text())['records']}
    seen = collections.defaultdict(list)
    counts = {g: collections.Counter() for g in ('khanom', 'ude')}
    scores = {mode: [] for mode in ('original', 'adapted')}
    assert len(result['records']) == 65
    for row in result['records']:
        group, ident = row['group'], row['id']
        seen[group].append(ident)
        assert group in ('khanom', 'ude') and sha256(R / row['source_image']) == row['source_image_sha256']
        assert sha256(R / row['prior_center_mask']) == row['prior_center_mask_sha256']
        gray = np.asarray(Image.open(R / row['source_image']).convert('L'))
        previous = np.asarray(Image.open(R / row['prior_center_mask']).convert('L')) > 0
        assert row['source_dimensions_xy'] == [gray.shape[1], gray.shape[0]] and previous.shape == gray.shape
        if group == 'khanom':
            source = kh[ident]
            assert row['source_image'] == str((K / source['images']['crop']['file']).relative_to(R))
            assert row['source_point_xy'] == source['source_points_xy'][0] and row['inference_point_xy'] == source['model_points_xy'][0]
            assert row['prior_center_mask_sha256'] == source['images']['center']['sha256']
            assert row['reference_sha256'] == source['images']['reference']['sha256'] == sha256(R / row['reference'])
            reference = np.asarray(Image.open(R / row['reference']).convert('L')) > 0
        else:
            source = ude[ident]
            meta = json.loads((U / 'mask-hypotheses/records' / (ident + '.json')).read_text())
            assert row['source_name'] == source['source_species'] and row['source_image_sha256'] == source['source_sha256']
            assert row['source_point_xy'] == meta['source_points_xy'][0] and row['inference_point_xy'] == meta['inference_points_xy'][0]
            assert row['prior_center_mask_sha256'] == meta['masks']['center']['sha256']
            assert row['reference'] is None and row['reference_sha256'] is None
            reference = None
        assert sha256(O / row['comparison']) == row['comparison_sha256']
        masks = []
        for mode in ('original', 'adapted'):
            out = row['outputs'][mode]
            path = O / out['path']
            assert path.resolve() == (O / 'masks' / f'{group}-{ident}-{mode}.png').resolve() and sha256(path) == out['sha256']
            raw = np.asarray(Image.open(path).convert('L'))
            assert raw.shape == gray.shape and set(np.unique(raw)).issubset({0, 255})
            mask = raw > 0
            assert out['area_px'] == int(mask.sum()) and out['crop_fraction'] == float(mask.mean())
            assert math.isfinite(out['model_score_not_accuracy'])
            assert out['reference_iou'] == (iou(mask, reference) if reference is not None else None)
            if reference is not None:
                scores[mode].append(out['reference_iou'])
                counts[group][mode + '_iou_ge_05'] += out['reference_iou'] >= .5
                counts[group][mode + '_iou_ge_075'] += out['reference_iou'] >= .75
            counts[group][mode + '_coverage_gt_075'] += out['crop_fraction'] > .75
            counts[group][mode + '_empty'] += not mask.any()
            x = min(gray.shape[1]-1, max(0, round(row['source_point_xy'][0])))
            y = min(gray.shape[0]-1, max(0, round(row['source_point_xy'][1])))
            counts[group][mode + '_contains_prompt_pixel'] += bool(mask[y, x])
            masks.append(mask)
        assert row['rerun_vs_saved_center_iou'] == iou(masks[0], previous)
        assert row['adapted_vs_original_iou'] == iou(masks[1], masks[0])
        a_large = row['outputs']['original']['crop_fraction'] > .75
        b_large = row['outputs']['adapted']['crop_fraction'] > .75
        counts[group]['both_coverage_gt_075'] += a_large and b_large
        counts[group]['original_only_coverage_gt_075'] += a_large and not b_large
        counts[group]['adapted_only_coverage_gt_075'] += b_large and not a_large
        counts[group]['rerun_exact_saved'] += np.array_equal(masks[0], previous)
        counts[group]['cases'] += 1
        if reference is not None:
            a, b = row['outputs']['original']['reference_iou'], row['outputs']['adapted']['reference_iou']
            counts[group]['adapted_higher_iou'] += b > a + 1e-9
            counts[group]['adapted_lower_iou'] += b < a - 1e-9
            counts[group]['adapted_equal_iou'] += abs(a-b) <= 1e-9
    assert seen['khanom'] == p['selection']['khanom_ids'] and seen['ude'] == p['selection']['ude_ids']
    for mode in ('original', 'adapted'):
        counts['khanom'][mode + '_mean_iou'] = float(np.mean(scores[mode]))
        counts['khanom'][mode + '_median_iou'] = float(np.median(scores[mode]))
    other = json.loads((O / 'other-polygon-audit.json').read_text())
    assert other['results_sha256'] == sha256(O / 'results.json') and other['proxy_sha256'] == sha256(K / 'results.json')
    out = {'format': 'r118-decoder-source-transfer-verify-v1', 'protocol_sha256': sha256(O / 'protocol.json'),
           'results_sha256': sha256(O / 'results.json'), 'other_polygon_audit_sha256': sha256(O / 'other-polygon-audit.json'),
           'summary': {k: dict(v) for k, v in counts.items()},
           'checks': 'Recomputed all source and mask hashes, point mappings, areas, prior-mask agreement and source-polygon IoUs using saved masks; no inference replay or biological ground-truth validation.'}
    (O / 'verify.json').write_text(json.dumps(out, indent=2) + '\n')
    print(json.dumps(out['summary'], indent=2))


if __name__ == '__main__':
    main()
