"""Compare two existing adapted decoders on the previously viewed source crops."""
import ctypes
import json
import os
import signal
from pathlib import Path

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

from diatom_pilot.ude_scaleup_dataset import sha256
from r112_outside_box_prompt_run import overlay

R = Path(__file__).resolve().parents[1]
D = R / 'results/r112/species-breadth-extension'
P = R / 'results/r112/outside-box-prompt-pilot'
O = R / 'results/r112/local-decoder-source-pilot'
WEIGHTS = {'r54': R / 'experiments/checkpoints/r54-freshwater-decoder.pt',
           'r112': R / 'results/r112/decoder-adaptation/mask-decoder.pt'}


def main():
    parent = os.getppid()
    assert ctypes.CDLL(None, use_errno=True).prctl(1, signal.SIGTERM) == 0
    if parent != os.getppid():
        raise RuntimeError('Parent exited')
    cv2.setNumThreads(2)
    torch.set_num_threads(2)
    LOGGER.setLevel('ERROR')
    O.mkdir(exist_ok=True)
    assert not (O / 'protocol.json').exists()
    files = ['results/r112/outside-box-prompt-pilot/protocol.json',
             'results/r112/outside-box-prompt-pilot/verify.json',
             'results/r112/species-breadth-extension/assets.json',
             'results/r112/species-breadth-extension/mask-hypotheses/verify.json',
             'research/r112_local_decoder_source_pilot.py', 'research/r112_outside_box_prompt_run.py',
             'experiments/checkpoints/r54-freshwater-decoder.pt',
             'results/r112/decoder-adaptation/mask-decoder.pt']
    cases = json.loads((P / 'protocol.json').read_text())['records']
    protocol = {'format': 'r112-local-decoder-source-pilot-v1',
                'inputs_sha256': {f: sha256(R / f) for f in files},
                'model_sha256': sha256(Path('/tmp/mobile_sam.pt')),
                'cases': cases,
                'selection': 'Same 36 previously viewed outside-box pilot cases; first two were chosen after observing failures. This is not an independent evaluation.',
                'method': 'Same 512-pixel median-padded grayscale image and original positive center point as saved MobileSAM center proposal. Compare that saved proposal with two existing modified MobileSAM mask decoders, without outside negative points. R54 used a small box-prompted synthetic Gündüz set; R112 used weak positive-only synthetic Academy-background scenes with teacher regularization.',
                'warning': 'All outputs are unverified. Source masks, rough point, training/slide independence and taxonomy remain uncertain. R54 used CC BY-NC-SA source-derived training; consider derivative license constraints. No expert truth or biological accuracy is measured.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    (O / 'masks').mkdir()
    (O / 'comparisons').mkdir()
    sources = {x['annotation_id']: x for x in json.loads((D / 'assets.json').read_text())['records']}
    states = {name: torch.load(path, map_location='cpu', weights_only=True) for name, path in WEIGHTS.items()}
    predictors = {name: Predictor(overrides={'model': '/tmp/mobile_sam.pt', 'task': 'segment',
                                            'mode': 'predict', 'imgsz': 512, 'device': 'cpu',
                                            'retina_masks': True, 'verbose': False, 'save': False, 'conf': 0.})
                  for name in WEIGHTS}
    records = []
    for case in cases:
        ident = case['annotation_id']
        src = sources[ident]
        im_path = D / src['source_crop']
        assert sha256(im_path) == src['source_sha256']
        im = np.asarray(Image.open(im_path).convert('L'))
        h, w = im.shape
        old = json.loads((D / 'mask-hypotheses/records' / (ident + '.json')).read_text())
        original_path = D / 'mask-hypotheses' / old['masks']['center']['file']
        assert sha256(original_path) == old['masks']['center']['sha256']
        original = np.asarray(Image.open(original_path).convert('L')) > 0
        factor = min(1., 512 / max(w, h))
        iw, ih = max(1, round(w * factor)), max(1, round(h * factor))
        ox, oy = (512 - iw) // 2, (512 - ih) // 2
        canvas = np.full((512, 512), int(np.median(im)), np.uint8)
        canvas[oy:oy + ih, ox:ox + iw] = im if (iw, ih) == (w, h) else cv2.resize(im, (iw, ih), interpolation=cv2.INTER_AREA)
        x, y = old['source_points_xy'][0]
        point = [ox + x * iw / w, oy + y * ih / h]
        saved, masks = {}, []
        for name in ('r54', 'r112'):
            predictor = predictors[name]
            predictor.set_image(cv2.cvtColor(canvas, cv2.COLOR_GRAY2BGR))
            predictor.model.mask_decoder.load_state_dict(states[name], strict=True)
            predictor.model.eval()
            output = predictor(points=[[point]], labels=[[1]], verbose=False)[0]
            if output.masks is None or len(output.masks.data) != 1:
                raise RuntimeError('Unexpected mask count for ' + ident + ' ' + name)
            raw = output.masks.data[0].cpu().numpy()[oy:oy + ih, ox:ox + iw].astype('uint8')
            mask = cv2.resize(raw, (w, h), interpolation=cv2.INTER_NEAREST).astype(bool)
            path = O / 'masks' / f'{ident}-{name}.png'
            Image.fromarray(mask.astype('uint8') * 255).save(path)
            union = int((original | mask).sum())
            saved[name] = {'path': str(path.relative_to(O)), 'sha256': sha256(path),
                           'area_px': int(mask.sum()), 'iou_original': int((original & mask).sum()) / union if union else None}
            masks.append(mask)
        panel_images = [ImageOps.contain(overlay(im, mask, [x, y], []), (280, 275)) for mask in (None, original, *masks)]
        comparison = Image.new('RGB', (1120, 305), 'white')
        draw = ImageDraw.Draw(comparison)
        for i, (title, panel) in enumerate(zip(('Source', 'Original center', 'R54 decoder', 'R112 decoder'), panel_images)):
            draw.text((i * 280 + 8, 3), title, fill='black')
            comparison.paste(panel, (i * 280 + (280 - panel.width) // 2, 25))
        comparison_path = O / 'comparisons' / f'{ident}.png'
        comparison.save(comparison_path)
        records.append({'annotation_id': ident, 'group': case['group'], 'source_name': src['source_species'],
                        'source_sha256': src['source_sha256'], 'original_mask_sha256': sha256(original_path),
                        'original_area_px': int(original.sum()), 'masks': saved,
                        'comparison': str(comparison_path.relative_to(O)), 'comparison_sha256': sha256(comparison_path)})
        if len(records) % 6 == 0:
            print('completed', len(records), '/', len(cases), flush=True)
    (O / 'results.json').write_text(json.dumps({'format': 'r112-local-decoder-source-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': records}, indent=2) + '\n')


if __name__ == '__main__':
    main()
