"""Reconstruct cumulative overlap renders and measure insertion marginal effects."""
import collections
import csv
import json
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
from r116_cumulative_overlap_pilot import cumulative, pixel_metrics

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


def normalize(value):
    return value.strip().casefold()


def summaries(pairs):
    out = {}
    for state in ('single', 'previous_overlap', 'cumulative'):
        counts = collections.Counter()
        for pair in pairs:
            hits = []
            for t in pair['targets']:
                name = normalize(t['source']['source_name'])
                ranks = [normalize(x['source_name']) for x in t[state + '_top5']]
                hits.append(ranks[0] == name)
                counts['species_top1'] += ranks[0] == name
                counts['species_top5'] += name in ranks
                counts['genus_top1'] += ranks[0].split()[0] == name.split()[0]
            counts['both_species_top1'] += all(hits)
        out[state] = dict(counts)
    transition = collections.Counter()
    for pair in pairs:
        for t in pair['targets']:
            name = normalize(t['source']['source_name'])
            a, b = t['previous_overlap_top5'][0], t['cumulative_top5'][0]
            x, y = normalize(a['source_name']) == name, normalize(b['source_name']) == name
            transition['top_code_changed'] += a['code'] != b['code']
            transition['exact_species_gained'] += not x and y
            transition['exact_species_lost'] += x and not y
            transition['exact_species_retained'] += x and y
    return {'pairs': len(pairs), 'targets': 2 * len(pairs), 'states': out, 'transition_previous_to_cumulative': dict(transition)}


def main():
    protocol = json.loads((O / 'protocol.json').read_text())
    result = json.loads((O / 'results.json').read_text())
    assert result['protocol_sha256'] == sha256(O / 'protocol.json') and protocol['model_sha256'] == sha256(W)
    for path, digest in protocol['inputs_sha256'].items():
        assert sha256(R / path) == digest
    old_protocol = json.loads((P / 'protocol.json').read_text())
    old = json.loads((P / 'results.json').read_text())
    assert len(old_protocol['pairs']) == len(old['records']) == len(result['records']) == 25
    taxa = {r['taxonomic_code']: r for r 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())
    datasets = pools()
    totals = {key: collections.Counter() for key in ('previous_bounded', 'cumulative')}
    changed_outside_intersection = 0
    for recipe, before, row in zip(old_protocol['pairs'], old['records'], result['records']):
        assert recipe['id'] == before['id'] == row['id'] and recipe['background'] == row['background']
        positioned, bg, supports, factors, shift = placement(recipe, recipe['instances'], datasets)
        assert positioned == before['positioned_instances'] and shift == before['placement_shift_index']
        inter = supports[0] & supports[1]
        assert inter.any() and int(inter.sum()) == before['intersection_px']
        _, _, previous_pair = images(bg, factors, 'bounded')
        assert sha256(P / before['frames']['bounded']['file']) == before['frames']['bounded']['sha256']
        assert np.array_equal(previous_pair, np.asarray(Image.open(P / before['frames']['bounded']['file']).convert('L')))
        raw, bounded, low, high = cumulative(bg, supports, factors)
        image = np.rint(np.clip(raw, 0, 255)).astype('uint8')
        assert sha256(O / row['frame']) == row['frame_sha256'] and np.array_equal(image, np.asarray(Image.open(O / row['frame']).convert('L')))
        changed_outside_intersection += int(((image != previous_pair) & ~inter).sum())
        assert not np.any((image != previous_pair) & ~inter)
        metrics = pixel_metrics(bg, supports, raw, bounded, low, high)
        ref_raw = bg.astype(np.float32) * bounded[0] * bounded[1]
        empty = np.zeros(bg.shape, bool)
        reference = pixel_metrics(bg, supports, ref_raw, bounded, empty, empty)
        assert metrics == row['cumulative_metrics'] and reference == row['previous_bounded_metrics']
        for label, info in [('previous_bounded', reference), ('cumulative', metrics)]:
            for key in ('intersection_px', 'floor_limited_px', 'ceiling_limited_px', 'intersection_out_of_range_px', 'response_eligible_px', 'response_below_half_px'):
                totals[label][key] += info[key]
            totals[label]['target_intersection_pixels'] += 2 * info['intersection_px']
            totals[label]['target_intersection_unchanged_px'] += sum(x['intersection_unchanged_px'] for x in info['per_target_marginal'])
            totals[label]['targets_more_than_half_unchanged'] += sum(x['intersection_unchanged_px'] > info['intersection_px'] / 2 for x in info['per_target_marginal'])
        assert len(row['targets']) == len(before['targets']) == 2
        for i, (t, prev) in enumerate(zip(row['targets'], before['targets'])):
            assert t['source'] == prev['source'] == positioned[i] and t['bbox_xyxy_exclusive'] == prev['bbox_xyxy_exclusive']
            assert t['name_in_model_vocabulary_exact'] == prev['source_name_in_model_vocabulary_exact']
            assert t['single_top5'] == prev['conditions']['bounded_single']['top5'] and t['previous_overlap_top5'] == prev['conditions']['bounded_overlap']['top5']
            x0, y0, x1, y1 = t['bbox_xyxy_exclusive']
            path = O / t['patch']
            assert sha256(path) == t['patch_sha256'] and np.array_equal(np.asarray(Image.open(path).convert('L')), image[y0:y1, x0:x1])
            ranks = t['cumulative_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[j]['score'] >= ranks[j+1]['score'] for j in range(4))
    both_known = [x for x in result['records'] if all(t['name_in_model_vocabulary_exact'] for t in x['targets'])]
    out = {'format': 'r116-cumulative-overlap-verify-v1', 'protocol_sha256': sha256(O / 'protocol.json'),
           'results_sha256': sha256(O / 'results.json'), 'all': summaries(result['records']),
           'both_names_in_vocabulary': summaries(both_known), 'pixel_diagnostics': {k: dict(v) for k, v in totals.items()},
           'changed_pixels_outside_intersection': changed_outside_intersection,
           'checks': 'Reconstructed all pair placements, full frames, 50 classifier crops and pixel interventions with shared code; checked saved name mappings and counts. No inference replay or validation of biological visibility, optics or classification.'}
    (O / 'verify.json').write_text(json.dumps(out, indent=2) + '\n')
    print(json.dumps(out, indent=2))


if __name__ == '__main__':
    main()
