"""Replay classifier outputs for the first two fixed synthetic pairs."""
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 defs
from diatom_pilot.ude_scaleup_dataset import sha256
from diamorph_preview import preprocess

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/gunduz-overlap-pair-pilot'
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']
    pairs = json.loads((O / 'results.json').read_text())['records'][:2]
    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'].float()
    model = YOLO('yolov8l-cls.yaml', task='classify')
    model.model = trained
    count = 0
    for pair in pairs:
        sx, sy = pair['background']['um_per_pixel_xy']
        for target in pair['targets']:
            for info in target['conditions'].values():
                path = O / info['path']
                assert sha256(path) == info['sha256']
                gray = np.asarray(Image.open(path).convert('L'))
                output = model.predict(preprocess(cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR), sx, sy), imgsz=512, device='cpu', verbose=False)[0]
                scores = output.probs.data.cpu().numpy()
                order = np.argsort(-scores, kind='stable')[:5]
                assert [trained.names[int(i)] for i in order] == [x['code'] for x in info['top5']]
                assert np.allclose([float(scores[int(i)]) for i in order], [x['score'] for x in info['top5']], rtol=1e-5, atol=1e-6)
                count += 1
    out = {'format': 'r112-gunduz-overlap-pair-replay-v1', 'results_sha256': sha256(O / 'results.json'),
           'pair_ids': [p['id'] for p in pairs], 'individual_inferences_replayed': count,
           'warning': 'Replays previously used inputs, not an independent biological accuracy measurement.'}
    (O / 'replay.json').write_text(json.dumps(out, indent=2) + '\n')
    print('replayed', count, 'classifier inferences')


if __name__ == '__main__':
    main()
