"""Run the frozen outside-rough-box negative-point development pilot."""
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

R = Path(__file__).resolve().parents[1]
D = R / 'results/r112/species-breadth-extension'
O = R / 'results/r112/outside-box-prompt-pilot'


def overlay(im, mask, positive, negatives):
    rgb = np.repeat(im[:, :, None], 3, axis=2).astype(np.float32)
    if mask is not None:
        rgb[mask] = .65 * rgb[mask] + .35 * np.array([30, 165, 255])
        edge = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8)) > 0
        rgb[edge] = [255, 80, 25]
    result = Image.fromarray(np.rint(rgb).clip(0, 255).astype(np.uint8))
    draw = ImageDraw.Draw(result)
    for point, color in [(positive, (255, 0, 190))] + [(p, (255, 230, 0)) for p in negatives]:
        x, y = point
        draw.line((x - 5, y, x + 5, y), fill=color, width=2)
        draw.line((x, y - 5, x, y + 5), fill=color, width=2)
    return result


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')
    protocol = json.loads((O / 'protocol.json').read_text())
    assert not (O / 'results.json').exists()
    for name, digest in protocol['inputs_sha256'].items():
        assert sha256(R / name) == digest
    assert sha256(Path('/tmp/mobile_sam.pt')) == protocol['model_sha256']
    sources = {x['annotation_id']: x for x in json.loads((D / 'assets.json').read_text())['records']}
    (O / 'masks').mkdir(exist_ok=True)
    (O / 'comparisons').mkdir(exist_ok=True)
    model = Predictor(overrides={'model': '/tmp/mobile_sam.pt', 'task': 'segment', 'mode': 'predict',
                                 'imgsz': 512, 'device': 'cpu', 'retina_masks': True,
                                 'verbose': False, 'save': False, 'conf': 0.})
    records = []
    for selection in protocol['records']:
        ident = selection['annotation_id']
        src = sources[ident]
        original_record = json.loads((D / 'mask-hypotheses/records' / (ident + '.json')).read_text())
        path = D / src['source_crop']
        assert sha256(path) == src['source_sha256'] == original_record['source_sha256']
        im = np.asarray(Image.open(path).convert('L'))
        h, w = im.shape
        original_path = D / 'mask-hypotheses' / original_record['masks']['center']['file']
        assert sha256(original_path) == original_record['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))
        img = im if (iw, ih) == (w, h) else cv2.resize(im, (iw, ih), interpolation=cv2.INTER_AREA)
        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] = img
        positive = original_record['source_points_xy'][0]
        all_pts = [positive] + selection['negative_points_xy']
        model_pts = [[ox + x * iw / w, oy + y * ih / h] for x, y in all_pts]
        model.set_image(cv2.cvtColor(canvas, cv2.COLOR_GRAY2BGR))
        prediction = model(points=[model_pts], labels=[[1] + [0] * (len(all_pts) - 1)], verbose=False)[0]
        if prediction.masks is None or len(prediction.masks.data) != 1:
            raise RuntimeError('Unexpected mask count for ' + ident)
        raw = prediction.masks.data[0].cpu().numpy()[oy:oy + ih, ox:ox + iw].astype('uint8')
        candidate = cv2.resize(raw, (w, h), interpolation=cv2.INTER_NEAREST).astype(bool)
        mask_path = O / 'masks' / (ident + '.png')
        Image.fromarray(candidate.astype('uint8') * 255).save(mask_path)
        panels = [overlay(im, mask, positive, selection['negative_points_xy']) for mask in (None, original, candidate)]
        panels = [ImageOps.contain(p, (340, 300)) for p in panels]
        comparison = Image.new('RGB', (1020, 330), 'white')
        draw = ImageDraw.Draw(comparison)
        for i, (label, panel) in enumerate(zip(('Source and points', 'Original center', 'With negative points'), panels)):
            draw.text((i * 340 + 8, 3), label, fill='black')
            comparison.paste(panel, (i * 340 + (340 - panel.width) // 2, 25))
        comparison_path = O / 'comparisons' / (ident + '.png')
        comparison.save(comparison_path)
        union = int((original | candidate).sum())
        records.append({**selection, 'source_sha256': src['source_sha256'], 'source_name': src['source_species'],
                        'positive_point_xy': positive, 'original_mask_sha256': sha256(original_path),
                        'candidate_mask': str(mask_path.relative_to(O)), 'candidate_mask_sha256': sha256(mask_path),
                        'comparison': str(comparison_path.relative_to(O)), 'comparison_sha256': sha256(comparison_path),
                        'original_area_px': int(original.sum()), 'candidate_area_px': int(candidate.sum()),
                        'candidate_original_iou': int((original & candidate).sum()) / union if union else None})
        print('completed', len(records), '/', len(protocol['records']), flush=True)
    (O / 'results.json').write_text(json.dumps({'format': 'r112-outside-box-prompt-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': records}, indent=2) + '\n')


if __name__ == '__main__':
    main()
