"""Replay two Khanom and two UDE original/adapted mask inferences."""
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
from ultralytics.models.sam import Predictor
from ultralytics.utils import LOGGER

from diatom_pilot.ude_scaleup_dataset import sha256

R = Path(__file__).resolve().parents[1]
O = R / 'results/r118'
W = Path('/tmp/mobile_sam.pt')
M = R / 'results/r117/decoder.pt'


def main():
    cv2.setNumThreads(2)
    torch.set_num_threads(2)
    LOGGER.setLevel('ERROR')
    p = json.loads((O / 'protocol.json').read_text())
    assert sha256(W) == p['mobile_sam_sha256'] and sha256(M) == p['inputs_sha256']['results/r117/decoder.pt']
    records = json.loads((O / 'results.json').read_text())['records']
    sample = [x for group in ('khanom', 'ude') for x in [y for y in records if y['group'] == group][:2]]
    predictor = Predictor(overrides={'model': str(W), 'task': 'segment', 'mode': 'predict', 'imgsz': 512,
                                     'device': 'cpu', 'retina_masks': True, 'verbose': False, 'save': False, 'conf': 0.})
    adapted = torch.load(M, map_location='cpu', weights_only=True)
    original = None
    count = 0
    for row in sample:
        path = R / row['source_image']
        assert sha256(path) == row['source_image_sha256']
        gray = np.asarray(Image.open(path).convert('L'))
        h, w = gray.shape
        f = min(1., 512/max(w, h))
        iw, ih = max(1, round(w*f)), max(1, round(h*f))
        ox, oy = (512-iw)//2, (512-ih)//2
        canvas = np.full((512, 512), int(np.median(gray)), np.uint8)
        canvas[oy:oy+ih, ox:ox+iw] = gray if (iw, ih) == (w, h) else cv2.resize(gray, (iw, ih), interpolation=cv2.INTER_AREA)
        x, y = row['inference_point_xy']
        predictor.set_image(cv2.cvtColor(canvas, cv2.COLOR_GRAY2BGR))
        if original is None:
            original = {k: v.detach().clone() for k, v in predictor.model.mask_decoder.state_dict().items()}
        for mode, state in [('original', original), ('adapted', adapted)]:
            predictor.model.mask_decoder.load_state_dict(state, strict=True)
            predictor.model.eval()
            output = predictor(points=[[[x, y]]], labels=[[1]], verbose=False)[0]
            cut = output.masks.data[0].cpu().numpy()[oy:oy+ih, ox:ox+iw].astype('uint8')
            mask = cv2.resize(cut, (w, h), interpolation=cv2.INTER_NEAREST).astype(bool)
            saved = O / row['outputs'][mode]['path']
            assert sha256(saved) == row['outputs'][mode]['sha256']
            assert np.array_equal(mask, np.asarray(Image.open(saved).convert('L')) > 0)
            assert np.isclose(float(output.boxes.conf[0].cpu()), row['outputs'][mode]['model_score_not_accuracy'], rtol=1e-5, atol=1e-6)
            count += 1
    out = {'format': 'r118-decoder-source-transfer-replay-v1', 'results_sha256': sha256(O / 'results.json'),
           'cases': [x['group'] + '/' + x['id'] for x in sample], 'mask_inferences_replayed': count,
           'warning': 'Replayed previously used development cases; no biological accuracy or independence follows.'}
    (O / 'replay.json').write_text(json.dumps(out, indent=2) + '\n')
    print('replayed', count, 'mask inferences')


if __name__ == '__main__':
    main()
