"""Rebuild factor-pilot patches and summarize stored classifier outcomes."""
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 runner
from diatom_pilot.ude_scaleup_dataset import sha256
from r112_gunduz_native_scenes import pools, render

R = Path(__file__).resolve().parents[1]
S = R / 'results/r112/gunduz-uncalibrated-scenes'
P = R / 'results/r112/gunduz-species-retention'
O = R / 'results/r112/gunduz-scene-factor-pilot'
W = Path('/tmp/diatom-diamorph-species-v2.pt')
CONDITIONS = ('source', 'actual_full', 'actual_target_only', 'flat_full', 'flat_target_only')


def top5(row, name):
    if name == 'source':
        return row['source_top5']
    if name == 'actual_full':
        return row['actual_full_top5']
    return row['conditions'][name]['top5']


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


def summary(rows):
    output = {'cases': len(rows), 'conditions': {}, 'transitions': {}}
    for condition in CONDITIONS:
        counts = collections.Counter()
        for row in rows:
            target = name(row['source_name'])
            predicted = [name(x['source_name']) for x in top5(row, condition)]
            counts['species_top1'] += predicted[0] == target
            counts['species_top5'] += target in predicted
            counts['genus_top1'] += predicted[0].split()[0] == target.split()[0]
        output['conditions'][condition] = dict(counts)
    for a, b in [('actual_full', 'actual_target_only'), ('actual_target_only', 'flat_target_only'),
                 ('flat_full', 'flat_target_only')]:
        counts = collections.Counter()
        for row in rows:
            target = name(row['source_name'])
            x, y = top5(row, a)[0], top5(row, b)[0]
            same_a, same_b = name(x['source_name']) == target, name(y['source_name']) == target
            counts['top_code_changed'] += x['code'] != y['code']
            counts['gained_exact_species_match'] += not same_a and same_b
            counts['lost_exact_species_match'] += same_a and not same_b
            counts['retained_exact_species_match'] += same_a and same_b
        output['transitions'][a + '__to__' + b] = dict(counts)
    return output


def main():
    p = json.loads((O / 'protocol.json').read_text())
    result = json.loads((O / 'results.json').read_text())
    assert result['protocol_sha256'] == sha256(O / 'protocol.json') and p['model_sha256'] == sha256(W)
    for path, digest in p['inputs_sha256'].items():
        assert sha256(R / path) == digest
    scene_recipes = json.loads((S / 'protocol.json').read_text())['scenes']
    scene_saved = json.loads((S / 'manifest.json').read_text())['records']
    past = {(r['scene_id'], r['instance_index']): r for r in json.loads((P / 'results.json').read_text())['records']}
    results = {(r['scene_id'], r['instance_index']): r for r in result['records']}
    expected = {(s['id'], i) for s in scene_recipes for i in range(len(s['instances']))}
    assert len(results) == len(result['records']) == len(expected) == 51 and set(results) == set(past) == 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(W, map_location='cpu', weights_only=True)['model']
    codes = set(trained.names.values())
    sources = pools()
    changed_crop_counts = collections.Counter()
    for scene, stored in zip(scene_recipes, scene_saved):
        assert scene['id'] == stored['id']
        assert sha256(S / stored['image']) == stored['image_sha256'] and sha256(S / stored['mask_archive']) == stored['mask_archive_sha256']
        actual_full = np.asarray(Image.open(S / stored['image']).convert('L'))
        bg = np.asarray(Image.open(R / scene['background']['path']).convert('L'))
        assert sha256(R / scene['background']['path']) == scene['background']['sha256']
        flat_path = O / 'flat-backgrounds' / (scene['id'] + '.png')
        flat = np.asarray(Image.open(flat_path).convert('L'))
        assert flat.shape == bg.shape == (768, 768) and np.all(flat == int(np.median(bg)))
        flat_scene = {**scene, 'background': {**scene['background'], 'path': str(flat_path.relative_to(R)),
                                             'sha256': sha256(flat_path)}}
        flat_full, _, _, _ = render(flat_scene, sources)
        with np.load(S / stored['mask_archive'], allow_pickle=False) as z:
            shape = tuple(z['support_shape'])
            supports = np.unpackbits(z['support_bits'], count=int(np.prod(shape))).reshape(shape).astype(bool)
        for i, item in enumerate(scene['instances']):
            row, prior = results[(scene['id'], i)], past[(scene['id'], i)]
            assert row['source_id'] == item['id'] == prior['source_id'] and row['source_name'] == prior['source_name']
            assert row['source_top5'] == prior['source_top5'] and row['actual_full_top5'] == prior['composite_top5']
            assert row['name_in_model_vocabulary_exact'] == prior['name_in_model_vocabulary_exact']
            assert row['crop_bounds_xyxy_exclusive'] == prior['crop_bounds_xyxy_exclusive']
            assert row['overlap_other_projected_supports'] == prior['overlap_other_projected_supports']
            assert row['flat_background_value'] == int(np.median(bg)) and row['flat_background_sha256'] == sha256(flat_path)
            single = {**scene, 'instances': [item]}
            flat_single = {**flat_scene, 'instances': [item]}
            actual_one, mask, _, _ = render(single, sources)
            flat_one, mask2, _, _ = render(flat_single, sources)
            assert np.array_equal(mask[0], supports[i]) and np.array_equal(mask2[0], supports[i])
            x0, y0, x1, y1 = row['crop_bounds_xyxy_exclusive']
            arrays = {'actual_target_only': actual_one[y0:y1, x0:x1],
                      'flat_target_only': flat_one[y0:y1, x0:x1], 'flat_full': flat_full[y0:y1, x0:x1]}
            expected_path = P / prior['composite_patch']
            assert sha256(expected_path) == prior['composite_patch_sha256']
            assert np.array_equal(actual_full[y0:y1, x0:x1], np.asarray(Image.open(expected_path).convert('L')))
            changed_crop_counts['actual_full_vs_target_different'] += bool(np.any(actual_full[y0:y1, x0:x1] != arrays['actual_target_only']))
            if row['overlap_other_projected_supports'] == 0:
                changed_crop_counts['no_overlap_crops_changed_by_others'] += bool(np.any(actual_full[y0:y1, x0:x1] != arrays['actual_target_only']))
            assert set(row['conditions']) == set(arrays)
            for condition, image in arrays.items():
                info = row['conditions'][condition]
                path = O / info['patch']
                assert sha256(path) == info['patch_sha256'] and np.array_equal(image, np.asarray(Image.open(path).convert('L')))
                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[j]['score'] >= ranks[j+1]['score'] for j in range(4))
            assert sha256(O / row['comparison']) == row['comparison_sha256']
    rows = result['records']
    subsets = {'all': rows, 'exact_vocabulary': [x for x in rows if x['name_in_model_vocabulary_exact']],
               'source_top1_matches': [x for x in rows if name(top5(x, 'source')[0]['source_name']) == name(x['source_name'])],
               'inserted_support_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]}
    check = {'format': 'r112-gunduz-scene-factor-verify-v1', 'protocol_sha256': sha256(O / 'protocol.json'),
             'results_sha256': sha256(O / 'results.json'), 'summary': {k: summary(v) for k, v in subsets.items()},
             'crop_difference_counts': dict(changed_crop_counts),
             'checks': 'Reconstructed every factor crop with shared renderer, checked saved inputs, predictions, code/name mapping and summaries. Does not replay classifier inference or establish biological visibility, optical realism or species accuracy.'}
    (O / 'verify.json').write_text(json.dumps(check, indent=2) + '\n')
    print(json.dumps({'all': check['summary']['all'], 'crop_difference_counts': check['crop_difference_counts']}, indent=2))


if __name__ == '__main__':
    main()
