"""Verify GrabCut candidate files and proxy IoUs without asserting anatomy."""
import collections
import json
from pathlib import Path

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/r112/grabcut-source-pilot'
U = R / 'results/r112/species-breadth-extension'


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')
    for f, h in p['inputs_sha256'].items():
        assert sha256(R / f) == h
    source = {r['annotation_id']: r for r in json.loads((U / 'assets.json').read_text())['records']}
    proxy = {}
    for group, folder in [('khanom', R / 'results/r112/source-mask-polygon-proxy'), ('gunduz', R / 'results/r115')]:
        proxy[group] = (folder, {x['id']: x for x in json.loads((folder / 'results.json').read_text())['records'] if group == 'khanom' or x['status'] == 'evaluated'})
    grouped = collections.defaultdict(collections.Counter)
    seen = collections.defaultdict(list)
    for row in result['records']:
        group, ident = row['group'], row['id']
        seen[group].append(ident)
        mask_path = O / row['mask']
        assert mask_path.resolve() == (O / 'masks' / f'{group}-{ident}.png').resolve()
        assert sha256(mask_path) == row['mask_sha256'] and sha256(O / row['comparison']) == row['comparison_sha256']
        raw = np.asarray(Image.open(mask_path).convert('L'))
        assert set(np.unique(raw)).issubset({0, 255})
        candidate = raw > 0
        assert list(candidate.shape[::-1]) == row['source_dimensions_px'] and int(candidate.sum()) == row['candidate_area_px']
        if group == 'ude':
            meta = source[ident]
            old = json.loads((U / 'mask-hypotheses/records' / (ident + '.json')).read_text())
            assert sha256(U / meta['source_crop']) == meta['source_sha256']
            path = U / 'mask-hypotheses' / old['masks']['center']['file']
            assert sha256(path) == old['masks']['center']['sha256']
            base = np.asarray(Image.open(path).convert('L')) > 0
            assert row['source_name'] == meta['source_species']
            ref = None
        else:
            folder, records = proxy[group]
            old = records[ident]
            for key in ('crop', 'center', 'reference'):
                assert sha256(folder / old['images'][key]['file']) == old['images'][key]['sha256']
            base = np.asarray(Image.open(folder / old['images']['center']['file']).convert('L')) > 0
            ref = np.asarray(Image.open(folder / old['images']['reference']['file']).convert('L')) > 0
        assert candidate.shape == base.shape and int(base.sum()) == row['center_area_px']
        stat = grouped[group]
        stat['cases'] += 1
        stat['candidate_smaller'] += bool(candidate.sum() < base.sum())
        stat['candidate_area_le_1pct_crop'] += bool(candidate.mean() <= .01)
        stat['candidate_area_gt_75pct_crop'] += bool(candidate.mean() > .75)
        if ref is not None:
            for name, mask in [('center', base), ('grabcut', candidate)]:
                union = int((mask | ref).sum())
                iou = int((mask & ref).sum()) / union if union else None
                assert row[name + '_reference_iou'] == iou
                stat[name + '_iou_ge_05'] += bool(iou is not None and iou >= .5)
                stat[name + '_iou_ge_075'] += bool(iou is not None and iou >= .75)
    assert dict(seen) == p['cases']
    check = {'format': 'r112-grabcut-source-verify-v1',
             'protocol_sha256': sha256(O / 'protocol.json'), 'results_sha256': sha256(O / 'results.json'),
             'summary': {k: dict(v) for k, v in grouped.items()},
             'checks': 'Checked source and mask hashes, binary masks, dimensions, areas and reference IoUs. Does not replay GrabCut or establish source reference correctness.'}
    (O / 'verify.json').write_text(json.dumps(check, indent=2) + '\n')
    print(json.dumps(check, indent=2))


if __name__ == '__main__':
    main()
