"""Recheck every extension asset against its archive member and partition."""
import collections
import csv
import json
from pathlib import Path

from PIL import Image, ImageChops
from diatom_pilot.ude_development_archive import UDEDevelopmentArchive, sha256

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


def main():
    select = json.loads((O / 'selection.json').read_text())
    assets = json.loads((O / 'assets.json').read_text())
    old = json.loads((R / 'results/r112/species-breadth/selection.json').read_text())
    partition = json.loads((R / 'results/r112/species-scaleup/location-partitions.json').read_text())['group_partition']
    assert assets['selection_sha256'] == sha256(O / 'selection.json')
    for path, digest in select['inputs_sha256'].items():
        assert sha256(R / path) == digest
    assert sha256(Path('/tmp/ude-metadata.csv')) == select['metadata_sha256']
    assert len(select['records']) == len(assets['records'])
    assert len({r['annotation_id'] for r in assets['records']}) == len(assets['records'])
    old_ids = {r['annotation_id'] for r in old['records']}
    components, slides, counts = collections.Counter(), collections.Counter(), collections.Counter()
    for r in old['records']:
        if partition.get(r['site_component']) == 'training':
            counts[r['source_species']] += 1
            components[r['source_species'], r['site_component']] += 1
            slides[r['source_species'], r['source_slide']] += 1
    assert dict(counts) == select['before_by_name']
    with UDEDevelopmentArchive() as archive:
        for expected, row in zip(select['records'], assets['records']):
            for key, value in expected.items():
                assert row[key] == value
            ident, name, site, slide = (row[k] for k in ('annotation_id', 'source_species', 'source_site_component', 'source_slide_group'))
            assert ident not in old_ids and partition[site] == 'training' and name in old['per_name']
            counts[name] += 1
            components[name, site] += 1
            slides[name, slide] += 1
            target = O / row['source_crop']
            assert sha256(target) == row['source_sha256']
            source = archive.read(ident, require_plain_species=True)
            assert source['source_name'] == name and source['source_genus'] == row['source_genus']
            assert source['site_component'] == site and source['source_slide'] == slide
            assert source['archive_member_sha256'] == row['archive_member_sha256']
            assert source['archive_member_crc32'] == row['archive_member_crc32']
            assert source['source_um_per_pixel_xy'] == row['source_scale_um_px']
            with Image.open(target) as image:
                assert image.mode == 'L' and list(image.size) == row['source_dimensions_px']
                assert ImageChops.difference(image, source['image']).getbbox() is None
    assert dict(counts) == select['after_by_name']
    assert max(components.values()) <= 4 and max(slides.values()) <= 2 and max(counts.values()) <= 24
    report = {'format': 'r112-breadth-depth-extension-verify-v1',
              'selection_sha256': sha256(O / 'selection.json'), 'assets_sha256': sha256(O / 'assets.json'),
              'assets_checked_pixel_for_pixel': len(assets['records']),
              'names_extended': len({r['source_species'] for r in assets['records']}),
              'all_prior_training_components': True, 'all_grayscale': True,
              'warning': 'Source pixels, provenance and location partition checked; species identity, sample independence, mask quality and use in training not established.'}
    (O / 'verify.json').write_text(json.dumps(report, indent=2) + '\n')
    print(json.dumps(report, indent=2))


if __name__ == '__main__':
    main()
