"""Recompute paired overlaps, crop pixels and descriptive prediction counts."""
import collections
import csv
import json
import statistics
from pathlib import Path

import numpy as np
import torch
from PIL import Image

import r112_gunduz_species_retention as defs
from diatom_pilot.ude_scaleup_dataset import sha256
from r112_gunduz_native_scenes import pools
from r112_gunduz_overlap_pair_pilot import images, placement

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/gunduz-overlap-pair-pilot'
W = Path('/tmp/diatom-diamorph-species-v2.pt')


def normalized(x):
    return x.strip().casefold()


def summarize(rows, mode):
    c = collections.Counter()
    for pair in rows:
        correct = {}
        for state in ('single', 'overlap'):
            hits = []
            for target in pair['targets']:
                source = normalized(target['source']['source_name'])
                ranks = [normalized(x['source_name']) for x in target['conditions'][mode + '_' + state]['top5']]
                hits.append(ranks[0] == source)
                c[state + '_species_top1'] += ranks[0] == source
                c[state + '_species_top5'] += source in ranks
                c[state + '_genus_top1'] += ranks[0].split()[0] == source.split()[0]
            c[state + '_both_species_top1'] += all(hits)
            correct[state] = hits
        for i in range(2):
            c['gained_species_match_on_overlap'] += not correct['single'][i] and correct['overlap'][i]
            c['lost_species_match_on_overlap'] += correct['single'][i] and not correct['overlap'][i]
            c['retained_species_match_on_overlap'] += correct['single'][i] and correct['overlap'][i]
    return dict(c)


def main():
    p, r = (json.loads((O / f).read_text()) for f in ('protocol.json', 'results.json'))
    assert r['protocol_sha256'] == sha256(O / 'protocol.json') and p['model_sha256'] == sha256(W)
    for f, h in p['inputs_sha256'].items():
        assert sha256(R / f) == h
    assert len(p['pairs']) == len(r['records']) == 25
    taxa = {x['taxonomic_code']: x for x in csv.DictReader((R / 'diatom_pilot/data/diatlas-taxonomic-code.csv').open(), delimiter=';')}
    allow = [defs.ClassificationModel, defs.Conv, defs.C2f, defs.Bottleneck, defs.Classify, defs.Sequential,
             defs.Conv2d, defs.BatchNorm2d, defs.SiLU, defs.ModuleList, defs.AdaptiveAvgPool2d, defs.Linear,
             defs.Dropout, defs.Compose, defs.CenterCrop, defs.Resize, defs.ToTensor, defs.Normalize, defs.InterpolationMode]
    with torch.serialization.safe_globals(allow):
        trained = torch.load(W, map_location='cpu', weights_only=True)['model']
    codes = set(trained.names.values())
    vocab = {normalized(taxa[x]['species']) for x in codes}
    datasets = pools()
    expected_sources = {(pool, i) for pool, ds in datasets.items() for i in range(len(ds))}
    used = set()
    stats = {mode: collections.Counter() for mode in ('baseline', 'bounded')}
    overlap_fractions = []
    for recipe, row in zip(p['pairs'], r['records']):
        assert recipe['id'] == row['id'] and recipe['background'] == row['background']
        positioned, bg, supports, factors, shift = placement(recipe, recipe['instances'], datasets)
        assert positioned == row['positioned_instances'] and shift == row['placement_shift_index']
        inter = supports[0] & supports[1]
        assert inter.any() and int(inter.sum()) == row['intersection_px']
        path = O / row['supports']
        assert sha256(path) == row['supports_sha256']
        with np.load(path, allow_pickle=False) as z:
            shape = tuple(z['support_shape'])
            assert shape == (2, 768, 768) and str(z['background_label_status']) == 'unknown' and str(z['visible_support_status']) == 'undefined'
            assert np.array_equal(np.unpackbits(z['support_bits'], count=int(np.prod(shape))).reshape(shape).astype(bool), supports)
        computed = {}
        for mode in ('baseline', 'bounded'):
            computed[mode] = images(bg, factors, mode)
            frame = O / row['frames'][mode]['file']
            assert sha256(frame) == row['frames'][mode]['sha256'] and np.array_equal(np.asarray(Image.open(frame).convert('L')), computed[mode][2])
            factors_mode = factors if mode == 'baseline' else [np.clip(np.power(x, 3.), .5, 1.5) for x in factors]
            f = factors_mode[0] * factors_mode[1]
            raw = bg.astype(np.float32) * f
            eligible = inter & (bg <= 251)
            response = (np.clip((bg.astype(np.float32)+4)*f, 0, 255) - np.clip(raw, 0, 255)) / 4
            stats[mode]['intersection_px'] += int(inter.sum())
            stats[mode]['intersection_out_of_range_px'] += int((inter & ((raw < 0) | (raw > 255))).sum())
            stats[mode]['response_eligible_px'] += int(eligible.sum())
            stats[mode]['response_below_half_px'] += int((eligible & (response < .5 - 1e-5)).sum())
        assert len(row['targets']) == 2
        for j, target in enumerate(row['targets']):
            source = positioned[j]
            key = (source['pool'], source['index'])
            assert key not in used and key in expected_sources
            used.add(key)
            assert target['source'] == source
            assert target['source_name_in_model_vocabulary_exact'] == (normalized(source['source_name']) in vocab)
            assert target['in_frame_support_px'] == int(supports[j].sum())
            assert target['intersection_fraction'] == int(inter.sum()) / int(supports[j].sum())
            overlap_fractions.append(target['intersection_fraction'])
            ys, xs = np.nonzero(supports[j])
            bounds = [int(xs.min()), int(ys.min()), int(xs.max())+1, int(ys.max())+1]
            assert target['bbox_xyxy_exclusive'] == bounds
            x0, y0, x1, y1 = bounds
            for mode in ('baseline', 'bounded'):
                for state, image in [('single', computed[mode][j]), ('overlap', computed[mode][2])]:
                    info = target['conditions'][mode + '_' + state]
                    path = O / info['path']
                    assert sha256(path) == info['sha256']
                    assert np.array_equal(np.asarray(Image.open(path).convert('L')), image[y0:y1, x0:x1])
                    ranks = info['top5']
                    assert len(ranks) == 5 and len({x['code'] for x in ranks}) == 5
                    assert all(x['code'] in codes and x['source_name'] == taxa[x['code']]['species'] and 0 <= x['score'] <= 1 for x in ranks)
                    assert all(ranks[k]['score'] >= ranks[k+1]['score'] for k in range(4))
    unused = p['unused_source']
    assert used | {(unused['pool'], unused['index'])} == expected_sources and len(used) == 50
    both_known = [pair for pair in r['records'] if all(x['source_name_in_model_vocabulary_exact'] for x in pair['targets'])]
    result = {'format': 'r112-gunduz-overlap-pair-verify-v1', 'protocol_sha256': sha256(O / 'protocol.json'),
              'results_sha256': sha256(O / 'results.json'), 'pairs': 25, 'targets': 50,
              'source_names_in_vocabulary_exact': sum(x['source_name_in_model_vocabulary_exact'] for pair in r['records'] for x in pair['targets']),
              'pairs_with_both_names_in_vocabulary_exact': len(both_known),
              'median_target_support_intersection_fraction': statistics.median(overlap_fractions),
              'targets_intersection_fraction_ge_025': sum(x >= .25 for x in overlap_fractions),
              'prediction_summary': {mode: summarize(r['records'], mode) for mode in ('baseline', 'bounded')},
              'both_known_pair_summary': {mode: summarize(both_known, mode) for mode in ('baseline', 'bounded')},
              'overlap_pixel_response_proxy': {mode: dict(value) for mode, value in stats.items()},
              'checks': 'Reconstructed all pair placements, supports, full images and 200 classification patches with shared rendering code; checked stored top-five mappings and counts. Fixed-factor +4 response is a numerical proxy, not recognition of either diatom. No inference replay, independent sample or biological accuracy verification.'}
    (O / 'verify.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    main()
