"""Replay the first three cases in all three new contrast gains."""
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
from ultralytics import YOLO
from ultralytics.utils import LOGGER

import r112_gunduz_species_retention as runner
from diatom_pilot.ude_scaleup_dataset import sha256
from diamorph_preview import preprocess

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


def main():
    cv2.setNumThreads(2)
    torch.set_num_threads(2)
    LOGGER.setLevel('ERROR')
    protocol = json.loads((O / 'protocol.json').read_text())
    assert sha256(W) == protocol['model_sha256']
    rows = json.loads((O / 'results.json').read_text())['records'][:3]
    scenes = {x['id']: x for x in json.loads((S / 'manifest.json').read_text())['records']}
    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'].float()
    model = YOLO('yolov8l-cls.yaml', task='classify')
    model.model = trained
    for row in rows:
        sx, sy = scenes[row['scene_id']]['background']['um_per_pixel_xy']
        for info in row['gains'].values():
            path = O / info['patch']
            assert sha256(path) == info['patch_sha256']
            gray = np.asarray(Image.open(path).convert('L'))
            out = model.predict(preprocess(cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR), sx, sy), imgsz=512, device='cpu', verbose=False)[0]
            probs = out.probs.data.cpu().numpy()
            order = np.argsort(-probs, kind='stable')[:5]
            assert [trained.names[int(i)] for i in order] == [x['code'] for x in info['top5']]
            assert np.allclose([float(probs[int(i)]) for i in order], [x['score'] for x in info['top5']], rtol=1e-5, atol=1e-6)
    out = {'format': 'r112-gunduz-contrast-gain-replay-v1', 'results_sha256': sha256(O / 'results.json'),
           'case_ids': [x['scene_id'] + '-' + str(x['instance_index']) for x in rows],
           'individual_inferences_replayed': len(rows) * 3,
           'warning': 'Replays previously viewed development inputs; this is not an accuracy or independence test.'}
    (O / 'replay.json').write_text(json.dumps(out, indent=2) + '\n')
    print('replayed', len(rows) * 3, 'classifier inferences')


if __name__ == '__main__':
    main()
