"""Reconstruct all uncalibrated diagnostic fields and omission measurements."""
import collections
import json
from pathlib import Path

import numpy as np
from PIL import Image

from diatom_pilot.ude_scaleup_dataset import sha256
from r112_gunduz_native_scenes import pools, render

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/gunduz-uncalibrated-scenes'


def main():
    p = json.loads((O / 'protocol.json').read_text())
    m = json.loads((O / 'manifest.json').read_text())
    assert m['protocol_sha256'] == sha256(O / 'protocol.json')
    for f, h in p['inputs_sha256'].items():
        assert sha256(R / f) == h
    datasets = pools()
    expected = {(pool, i) for pool, ds in datasets.items() for i in range(len(ds))}
    used, names = set(), set()
    counts = collections.Counter()
    assert len(p['scenes']) == len(m['records']) == 9
    for scene, row in zip(p['scenes'], m['records']):
        assert scene['id'] == row['id'] and scene['background'] == row['background']
        assert sha256(O / row['image']) == row['image_sha256'] and sha256(O / row['mask_archive']) == row['mask_archive_sha256']
        im = np.asarray(Image.open(O / row['image']))
        assert im.shape == (768, 768) and im.dtype == np.uint8
        with np.load(O / row['mask_archive'], allow_pickle=False) as z:
            shape = tuple(z['support_shape'])
            assert shape == (len(row['instances']), 768, 768)
            assert str(z['background_label_status']) == 'unknown' and str(z['visible_support_status']) == 'undefined'
            masks = np.unpackbits(z['support_bits'], count=int(np.prod(shape))).reshape(shape).astype(bool)
        regenerated, supports, details, bg = render(scene, datasets)
        assert np.array_equal(im, regenerated) and np.array_equal(masks, supports) and details == row['instances']
        assert int((im != bg).sum()) == row['changed_pixels_vs_background'] and not np.any((im != bg) & ~masks.any(0))
        pairs = sum(bool((masks[a] & masks[b]).any()) for a in range(len(masks)) for b in range(a + 1, len(masks)))
        assert pairs == row['support_overlap_pairs']
        counts['overlap_pairs'] += pairs
        counts['scenes_with_overlap'] += pairs > 0
        for i, (item, mask, contribution) in enumerate(zip(details, masks, row['omission_contributions'])):
            key = (item['pool'], item['index'])
            assert key not in used and key in expected
            used.add(key)
            names.add(item['source_name'])
            assert item['source_scale_um_per_pixel_xy'] is None and item['visible_support_status'] == 'undefined'
            assert int(mask.sum()) == item['in_frame_support_px']
            counts['partial_supports'] += bool(item['in_frame_fraction'] is not None and item['in_frame_fraction'] < 1)
            counts['empty_supports'] += not mask.any()
            without, _, _, _ = render(scene, datasets, omit=i)
            diff = np.abs(im.astype(np.int16) - without.astype(np.int16))
            assert not np.any(diff[~mask])
            assert contribution['changed_pixels'] == int((diff > 0).sum())
            assert contribution['mean_absolute_change_in_support'] == (float(diff[mask].mean()) if mask.any() else None)
            counts['zero_changed_instances'] += contribution['changed_pixels'] == 0
    assert used == expected and len(names) == 29
    counts.update({'scenes': len(m['records']), 'instances': len(used), 'source_name_strings': len(names)})
    result = {'format': 'r112-gunduz-uncalibrated-scenes-verify-v1',
              'manifest_sha256': sha256(O / 'manifest.json'), 'protocol_sha256': sha256(O / 'protocol.json'),
              'counts': dict(counts), 'replayed_scenes': 9, 'replayed_omissions': len(used),
              'checks': 'Rebuilt all images, supports and individual omission differences using shared rendering code. Validates file geometry and provenance, not specimen correctness, optics, species accuracy or real-world visibility.'}
    (O / 'verify.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()
