"""Reconstruct paired patches and summarize frozen classifier output matches."""
import collections
import csv
import json
from pathlib import Path

import numpy as np
import torch
from PIL import Image

from diatom_pilot.ude_scaleup_dataset import sha256
from r112_gunduz_native_scenes import pools
from r112_gunduz_species_retention import matched_patches, norm
import r112_gunduz_species_retention as runner

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


def summarize(rows):
    out = {'cases': len(rows), 'source_top1': 0, 'composite_top1': 0, 'source_top5': 0, 'composite_top5': 0,
           'source_genus_top1': 0, 'composite_genus_top1': 0, 'same_top1_code': 0,
           'source_only_top1_match': 0, 'composite_only_top1_match': 0, 'both_top1_match': 0}
    for row in rows:
        name, genus = norm(row['source_name']), norm(row['source_name']).split()[0]
        source = [norm(x['source_name']) for x in row['source_top5']]
        composite = [norm(x['source_name']) for x in row['composite_top5']]
        a, b = source[0] == name, composite[0] == name
        out['source_top1'] += a
        out['composite_top1'] += b
        out['source_top5'] += name in source
        out['composite_top5'] += name in composite
        out['source_genus_top1'] += source[0].split()[0] == genus
        out['composite_genus_top1'] += composite[0].split()[0] == genus
        out['same_top1_code'] += row['source_top5'][0]['code'] == row['composite_top5'][0]['code']
        out['source_only_top1_match'] += a and not b
        out['composite_only_top1_match'] += b and not a
        out['both_top1_match'] += a and b
    return out


def main():
    p = json.loads((O / 'protocol.json').read_text())
    results = json.loads((O / 'results.json').read_text())
    assert results['protocol_sha256'] == sha256(O / 'protocol.json')
    for path, digest in p['inputs_sha256'].items():
        assert sha256(R / path) == digest
    assert p['model_sha256'] == sha256(Path('/tmp/diatom-diamorph-species-v2.pt'))
    scenes = json.loads((S / 'manifest.json').read_text())['records']
    actual = {(r['scene_id'], r['instance_index']): r for r in results['records']}
    expected = {(s['id'], i) for s in scenes for i in range(len(s['instances']))}
    assert len(actual) == len(results['records']) == len(expected) == 51 and set(actual) == expected
    taxa = {r['taxonomic_code']: r for r in csv.DictReader((R / 'diatom_pilot/data/diatlas-taxonomic-code.csv').open(), delimiter=';')}
    allow = [runner.ClassificationModel, runner.Conv, runner.C2f, runner.Bottleneck, runner.Classify,
             runner.Sequential, runner.Conv2d, runner.BatchNorm2d, runner.SiLU, runner.ModuleList,
             runner.AdaptiveAvgPool2d, runner.Linear, runner.Dropout, runner.Compose, runner.CenterCrop,
             runner.Resize, runner.ToTensor, runner.Normalize, runner.InterpolationMode]
    with torch.serialization.safe_globals(allow):
        trained = torch.load('/tmp/diatom-diamorph-species-v2.pt', map_location='cpu', weights_only=True)['model']
    codes = set(trained.names.values())
    vocabulary = {norm(taxa[code]['species']) for code in codes}
    datasets = pools()
    for scene in scenes:
        assert sha256(S / scene['image']) == scene['image_sha256'] and sha256(S / scene['mask_archive']) == scene['mask_archive_sha256']
        img = np.asarray(Image.open(S / scene['image']).convert('L'))
        with np.load(S / scene['mask_archive'], allow_pickle=False) as z:
            shape = tuple(z['support_shape'])
            masks = np.unpackbits(z['support_bits'], count=int(np.prod(shape))).reshape(shape).astype(bool)
        for i, item in enumerate(scene['instances']):
            row = actual[(scene['id'], i)]
            assert row['source_id'] == item['id'] and row['source_name'] == item['source_name']
            assert row['name_in_model_vocabulary_exact'] == (norm(row['source_name']) in vocabulary)
            assert row['in_frame_fraction'] == item['in_frame_fraction']
            assert row['overlap_other_projected_supports'] == sum(bool((masks[i] & masks[j]).any()) for j in range(len(masks)) if j != i)
            src, comp, bounds = matched_patches(scene, item, masks[i], img, datasets)
            assert bounds == row['crop_bounds_xyxy_exclusive'] and row['crop_dimensions_px'] == [src.shape[1], src.shape[0]]
            for arr, field in [(src, 'source_patch'), (comp, 'composite_patch')]:
                path = O / row[field]
                assert sha256(path) == row[field + '_sha256'] and np.array_equal(arr, np.asarray(Image.open(path).convert('L')))
            assert sha256(O / row['comparison']) == row['comparison_sha256']
            for field in ('source_top5', 'composite_top5'):
                ranks = row[field]
                assert len(ranks) == 5 and len({v['code'] for v in ranks}) == 5
                assert all(v['code'] in codes and v['source_name'] == taxa[v['code']]['species'] and 0 <= v['score'] <= 1 for v in ranks)
                assert all(ranks[k]['score'] >= ranks[k+1]['score'] for k in range(4))
    rows = results['records']
    subsets = {'all': rows, 'exact_vocabulary': [x for x in rows if x['name_in_model_vocabulary_exact']],
               'support_in_frame_ge_095': [x for x in rows if x['in_frame_fraction'] >= .95],
               'overlap': [x for x in rows if x['overlap_other_projected_supports'] > 0],
               'no_inserted_support_overlap': [x for x in rows if x['overlap_other_projected_supports'] == 0]}
    out = {'format': 'r112-gunduz-species-retention-verify-v1',
           'protocol_sha256': sha256(O / 'protocol.json'), 'results_sha256': sha256(O / 'results.json'),
           'summary': {key: summarize(value) for key, value in subsets.items()},
           'checks': 'Reconstructed all source and composite patches, supports and geometry; checked saved top-five name mapping and scores and recomputed descriptive match counts. Does not independently rerun inference or validate taxonomy, optics, source masks or Academy accuracy.'}
    (O / 'verify.json').write_text(json.dumps(out, indent=2) + '\n')
    print(json.dumps(out['summary'], indent=2))


if __name__ == '__main__':
    main()
