"""Compare the R117 decoder on previously used Khanom and UDE 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]
O = R / 'results/r118'
K = R / 'results/r112/source-mask-polygon-proxy'
U = R / 'results/r112/species-breadth-extension'
P = R / 'results/r112/outside-box-prompt-pilot'
M = R / 'results/r117'
W = Path('/tmp/mobile_sam.pt')


def iou(a, b):
    union = int((a | b).sum())
    return int((a & b).sum()) / union if union else None


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/r117/protocol.json', 'results/r117/training.json', 'results/r117/verify.json', 'results/r117/decoder.pt',
             'results/r112/source-mask-polygon-proxy/results.json', 'results/r112/source-mask-polygon-proxy/verify.json',
             'results/r112/species-breadth-extension/assets.json', 'results/r112/species-breadth-extension/verify.json',
             'results/r112/species-breadth-extension/mask-hypotheses/verify.json',
             'results/r112/outside-box-prompt-pilot/protocol.json', 'research/r112_outside_box_prompt_run.py',
             'research/r118_decoder_source_transfer.py']
    kh = json.loads((K / 'results.json').read_text())['records']
    ude = json.loads((P / 'protocol.json').read_text())['records']
    assert len(kh) == 29 and len(ude) == 36
    training = json.loads((M / 'training.json').read_text())
    assert training['checkpoint_sha256'] == sha256(M / 'decoder.pt') and json.loads((M / 'verify.json').read_text())['results_sha256'] == sha256(M / 'results.json')
    protocol = {'format': 'r118-decoder-source-transfer-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in files}, 'mobile_sam_sha256': sha256(W),
                'selection': {'khanom_ids': [x['id'] for x in kh], 'ude_ids': [x['annotation_id'] for x in ude]},
                'method': 'Re-run original and R117 adapted MobileSAM decoder with the same grayscale median-padded 512px crop and existing center point, one prompt per crop. Khanom points and crops were derived from published reference polygons; UDE points were derived from rough source annotations and may target background or neighbors. Save both predictions and compare re-run original to previously saved center proposal.',
                'outcome': 'Compute polygon IoU for all 29 Khanom cases, and area, prompt containment and pairwise mask changes for 36 UDE crops. UDE has no verified reference: geometry is not accuracy.',
                'warning': 'Both sets were previously viewed and used for development; Khanom crops and clicks use privileged polygon information. R117 training was screened against these Khanom crops with a coarse DCT rule, which cannot establish non-duplication, biological independence or pretraining exposure. UDE source labels, masks, source annotations and sample independence remain uncertain. No Academy accuracy, automatic detection or real overlap recovery is established.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    for sub in ('masks', 'comparisons'):
        (O / sub).mkdir()
    assets = {x['annotation_id']: x for x in json.loads((U / 'assets.json').read_text())['records']}
    jobs = []
    for row in kh:
        paths = {k: K / row['images'][k]['file'] for k in ('crop', 'center', 'reference')}
        assert all(sha256(paths[k]) == row['images'][k]['sha256'] for k in paths)
        jobs.append(('khanom', row['id'], row['source_folder'], paths['crop'], paths['center'], paths['reference'],
                     row['source_points_xy'][0], row['model_points_xy'][0], row['triage']))
    for item in ude:
        ident = item['annotation_id']
        row = assets[ident]
        meta = json.loads((U / 'mask-hypotheses/records' / (ident + '.json')).read_text())
        img, base = U / row['source_crop'], U / 'mask-hypotheses' / meta['masks']['center']['file']
        assert sha256(img) == row['source_sha256'] == meta['source_sha256'] and sha256(base) == meta['masks']['center']['sha256']
        jobs.append(('ude', ident, row['source_species'], img, base, None,
                     meta['source_points_xy'][0], meta['inference_points_xy'][0], meta['triage']))
    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 / 'decoder.pt', map_location='cpu', weights_only=True)
    original = None
    rows = []
    for group, ident, label, img_path, prior_path, ref_path, point, expected_point, triage in jobs:
        gray = np.asarray(Image.open(img_path).convert('L'))
        prior = np.asarray(Image.open(prior_path).convert('L')) > 0
        ref = np.asarray(Image.open(ref_path).convert('L')) > 0 if ref_path else None
        h, w = gray.shape
        assert prior.shape == gray.shape and (ref is None or ref.shape == gray.shape)
        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(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)
        xy = [ox + point[0]*iw/w, oy + point[1]*ih/h]
        assert np.allclose(xy, expected_point)
        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()}
        masks, outputs = [], {}
        for mode, state in [('original', original), ('adapted', adapted)]:
            predictor.model.mask_decoder.load_state_dict(state, strict=True)
            predictor.model.eval()
            out = predictor(points=[[[xy[0], xy[1]]]], labels=[[1]], verbose=False)[0]
            if out.masks is None or len(out.masks.data) != 1:
                raise RuntimeError('Unexpected output for ' + group + '/' + ident + ' ' + mode)
            cut = out.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)
            path = O / 'masks' / f'{group}-{ident}-{mode}.png'
            Image.fromarray(mask.astype('uint8') * 255).save(path)
            outputs[mode] = {'path': str(path.relative_to(O)), 'sha256': sha256(path), 'area_px': int(mask.sum()),
                             'crop_fraction': float(mask.mean()), 'reference_iou': iou(mask, ref) if ref is not None else None,
                             'model_score_not_accuracy': float(out.boxes.conf[0].cpu())}
            masks.append(mask)
        panels = [ImageOps.contain(overlay(gray, mask, point, []), (280, 250)) for mask in (None, ref, *masks)]
        plate = Image.new('RGB', (1120, 280), 'white')
        draw = ImageDraw.Draw(plate)
        for j, (title, panel) in enumerate(zip(('Source', 'Published polygon' if ref is not None else 'No reference', 'Original decoder', 'R117 adapted'), panels)):
            draw.text((j*280+5, 3), title, fill='black')
            plate.paste(panel, (j*280+(280-panel.width)//2, 22))
        preview = O / 'comparisons' / f'{group}-{ident}.png'
        plate.save(preview)
        rows.append({'group': group, 'id': ident, 'source_name': label, 'source_image': str(img_path.relative_to(R)),
                     'source_image_sha256': sha256(img_path), 'prior_center_mask': str(prior_path.relative_to(R)),
                     'prior_center_mask_sha256': sha256(prior_path), 'reference': str(ref_path.relative_to(R)) if ref_path else None,
                     'reference_sha256': sha256(ref_path) if ref_path else None,
                     'source_point_xy': point, 'inference_point_xy': xy, 'source_dimensions_xy': [w, h], 'triage': triage,
                     'outputs': outputs, 'rerun_vs_saved_center_iou': iou(masks[0], prior),
                     'adapted_vs_original_iou': iou(masks[1], masks[0]),
                     'comparison': str(preview.relative_to(O)), 'comparison_sha256': sha256(preview)})
        if len(rows) % 15 == 0:
            print('compared', len(rows), '/ 65', flush=True)
    assert len(rows) == 65
    (O / 'results.json').write_text(json.dumps({'format': 'r118-decoder-source-transfer-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': rows}, indent=2) + '\n')


if __name__ == '__main__':
    main()
