"""Recompute bounded-factor pixels, response proxies and prediction summaries."""
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_bounded_transmission import factor_field, measure
from r112_gunduz_contrast_gain_pilot import render_target
from r112_gunduz_native_scenes import pools

R = Path(__file__).resolve().parents[1]
S = R / 'results/r112/gunduz-uncalibrated-scenes'
P = R / 'results/r112/gunduz-contrast-gain-pilot'
Q = R / 'results/r112/gunduz-scene-factor-pilot'
O = R / 'results/r112/gunduz-bounded-transmission'
W = Path('/tmp/diatom-diamorph-species-v2.pt')


def predictions(row, name):
    if name == 'source':
        return row['source_top5']
    if name == 'baseline':
        return row['baseline_top5']
    if name == 'unbounded-3':
        return row['unbounded_gain3_top5']
    return row['bounded'][name]['top5']


def summary(rows):
    out = {'cases': len(rows), 'conditions': {}}
    for condition in ('source', 'baseline', 'unbounded-3', 'bounded-1p5', 'bounded-2', 'bounded-3'):
        c = collections.Counter()
        for row in rows:
            target = row['source_name'].strip().casefold()
            ranks = [x['source_name'].strip().casefold() for x in predictions(row, condition)]
            c['species_top1'] += ranks[0] == target
            c['species_top5'] += target in ranks
            c['genus_top1'] += ranks[0].split()[0] == target.split()[0]
        out['conditions'][condition] = dict(c)
    return out


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
    scenes = json.loads((S / 'protocol.json').read_text())['scenes']
    saved = {x['id']: x for x in json.loads((S / 'manifest.json').read_text())['records']}
    prior = {(x['scene_id'], x['instance_index']): x for x in json.loads((P / 'results.json').read_text())['records']}
    factor_prior = {(x['scene_id'], x['instance_index']): x for x in json.loads((Q / 'results.json').read_text())['records']}
    rows = {(x['scene_id'], x['instance_index']): x for x in result['records']}
    expected = {(s['id'], i) for s in scenes for i in range(len(s['instances']))}
    assert len(rows) == len(result['records']) == len(expected) == 51 and set(rows) == set(prior) == set(factor_prior) == 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())
    datasets = pools()
    aggregate = {k: collections.Counter() for k in ('baseline', 'unbounded-3', 'bounded-1p5', 'bounded-2', 'bounded-3')}
    for scene in scenes:
        m = saved[scene['id']]
        assert sha256(S / m['mask_archive']) == m['mask_archive_sha256']
        with np.load(S / m['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']):
            key = (scene['id'], i)
            row, before, fact = rows[key], prior[key], factor_prior[key]
            assert row['source_id'] == item['id'] == before['source_id'] and row['source_name'] == item['source_name']
            assert row['source_top5'] == before['source_top5'] and row['baseline_top5'] == before['baseline_top5']
            assert row['unbounded_gain3_top5'] == before['gains']['gain-3']['top5']
            assert row['crop_bounds_xyxy_exclusive'] == before['crop_bounds_xyxy_exclusive']
            assert row['name_in_model_vocabulary_exact'] == before['name_in_model_vocabulary_exact']
            x0, y0, x1, y1 = row['crop_bounds_xyxy_exclusive']
            bg, support, factors = factor_field(scene, item, datasets)
            raw0, mask0, bg0 = render_target(scene, item, datasets, 1.)
            assert np.array_equal(support, masks[i]) and np.array_equal(support, mask0) and np.array_equal(bg, bg0)
            assert np.array_equal(bg.astype(np.float32) * factors, raw0) and row['support_px'] == int(support.sum())
            assert row['baseline_metrics'] == measure(bg, support, factors)
            unbounded = 1 + 3 * (factors - 1)
            assert row['unbounded_gain3_metrics'] == measure(bg, support, unbounded)
            base_image = np.rint(np.clip(raw0, 0, 255)).astype('uint8')
            prior_base = Q / fact['conditions']['actual_target_only']['patch']
            assert sha256(prior_base) == fact['conditions']['actual_target_only']['patch_sha256']
            assert np.array_equal(base_image[y0:y1, x0:x1], np.asarray(Image.open(prior_base).convert('L')))
            raw3, _, _ = render_target(scene, item, datasets, 3.)
            assert np.array_equal(raw3, bg.astype(np.float32) * unbounded)
            prior3 = P / before['gains']['gain-3']['patch']
            assert sha256(prior3) == before['gains']['gain-3']['patch_sha256']
            assert np.array_equal(np.rint(np.clip(raw3, 0, 255)).astype('uint8')[y0:y1, x0:x1], np.asarray(Image.open(prior3).convert('L')))
            assert set(row['bounded']) == {'bounded-1p5', 'bounded-2', 'bounded-3'}
            measurements = {'baseline': row['baseline_metrics'], 'unbounded-3': row['unbounded_gain3_metrics']}
            for label, gain in [('bounded-1p5', 1.5), ('bounded-2', 2.), ('bounded-3', 3.)]:
                info = row['bounded'][label]
                requested = np.power(factors, gain)
                bounded = np.clip(requested, .5, 1.5)
                metrics = measure(bg, support, bounded)
                metrics.update({'floor_limited_px': int(((requested < .5) & support).sum()),
                                'ceiling_limited_px': int(((requested > 1.5) & support).sum())})
                assert info['exponent'] == gain and info['metrics'] == metrics
                image = np.rint(np.clip(bg.astype(np.float32) * bounded, 0, 255)).astype('uint8')
                assert np.array_equal(image[~support], bg[~support])
                path = O / info['patch']
                assert sha256(path) == info['patch_sha256'] and np.array_equal(image[y0:y1, x0:x1], 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))
                measurements[label] = metrics
            for label, metrics in measurements.items():
                c = aggregate[label]
                c['support_px'] += int(support.sum())
                for field in ('pre_round_out_of_range_px', 'negative_pre_round_px', 'response_eligible_px', 'response_below_half_px'):
                    c[field] += metrics[field]
                c['cases_with_out_of_range'] += metrics['pre_round_out_of_range_px'] > 0
                c['cases_with_negative'] += metrics['negative_pre_round_px'] > 0
                c['cases_response_below_half_gt_5pct'] += (metrics['response_below_half_px'] / metrics['response_eligible_px'] > .05) if metrics['response_eligible_px'] else False
                if label.startswith('bounded-'):
                    c['floor_limited_px'] += metrics['floor_limited_px']
                    c['ceiling_limited_px'] += metrics['ceiling_limited_px']
            assert sha256(O / row['comparison']) == row['comparison_sha256']
    all_rows = result['records']
    subsets = {'all': all_rows, 'exact_vocabulary': [x for x in all_rows if x['name_in_model_vocabulary_exact']],
               'source_top1_matches': [x for x in all_rows if x['source_top5'][0]['source_name'].strip().casefold() == x['source_name'].strip().casefold()],
               'support_in_frame_ge_095': [x for x in all_rows if x['in_frame_fraction'] >= .95]}
    out = {'format': 'r112-gunduz-bounded-transmission-verify-v1', 'protocol_sha256': sha256(O / 'protocol.json'),
           'results_sha256': sha256(O / 'results.json'), 'summary': {k: summary(v) for k, v in subsets.items()},
           'pixel_diagnostics': {k: dict(v) for k, v in aggregate.items()},
           'checks': 'Recomputed all gain crops and fixed-factor +4 response proxies using shared code, checked saved source, support, predictions and counts. Does not replay inference or establish optical realism, background organism visibility or species accuracy.'}
    (O / 'verify.json').write_text(json.dumps(out, indent=2) + '\n')
    print(json.dumps({'all': out['summary']['all'], 'pixel_diagnostics': out['pixel_diagnostics']}, indent=2))


if __name__ == '__main__':
    main()
