"""Compare rough-region-initialized GrabCut on existing development proxies."""
import ctypes
import json
import os
import signal
from pathlib import Path

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageOps

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/r112/grabcut-source-pilot'
U = R / 'results/r112/species-breadth-extension'
P = R / 'results/r112/source-mask-polygon-proxy'
G = R / 'results/r115'
T = R / 'results/r112/outside-box-prompt-pilot'


def load_image(path, expected):
    assert sha256(path) == expected
    return np.asarray(Image.open(path).convert('L'))


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)
    O.mkdir(exist_ok=True)
    assert not (O / 'protocol.json').exists()
    inputs = ['results/r112/species-breadth-extension/assets.json',
              'results/r112/species-breadth-extension/mask-hypotheses/verify.json',
              'results/r112/outside-box-prompt-pilot/protocol.json',
              'results/r112/source-mask-polygon-proxy/results.json',
              'results/r112/source-mask-polygon-proxy/verify.json',
              'results/r115/results.json', 'results/r115/verify.json',
              'research/r112_grabcut_source_pilot.py', 'research/r112_outside_box_prompt_run.py']
    u_cases = json.loads((T / 'protocol.json').read_text())['records']
    kh = json.loads((P / 'results.json').read_text())['records']
    gun = [x for x in json.loads((G / 'results.json').read_text())['records'] if x['status'] == 'evaluated']
    assert len(u_cases) == 36 and len(kh) == 29 and len(gun) == 20
    protocol = {'format': 'r112-grabcut-source-pilot-v1',
                'inputs_sha256': {name: sha256(R / name) for name in inputs},
                'cases': {'ude': [x['annotation_id'] for x in u_cases], 'khanom': [x['id'] for x in kh], 'gunduz': [x['id'] for x in gun]},
                'method': 'Resize grayscale crop to at most 512px, replicate channels. Initialize GrabCut: outside rough region definite background; inside region probable foreground; a radius max(1, 2% of shorter ROI bbox axis) disk at annotation-derived positive point is definite foreground, clipped to ROI. Four iterations, fixed cv2 RNG seed per input; nearest-neighbor restore to native crop. UDE ROI is the source rough rotated rectangle. For both source-mask proxy sets, the tight bounding box of the published reference mask defines the ROI; points and original crop also derive from that reference and are privileged. R54 and R112 decoders are not used.',
                'warning': 'All inputs were previously viewed or consumed. UDE has no pixel truth. Proxy source masks are not expert-confirmed and use oracle-derived crops, boxes and points; sample and model independence unknown. Outside ROI may contain diatoms, and positive seed may not mark target. No result becomes a label.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    (O / 'masks').mkdir()
    (O / 'comparisons').mkdir()
    assets = {r['annotation_id']: r for r in json.loads((U / 'assets.json').read_text())['records']}
    jobs = []
    for record in u_cases:
        ident = record['annotation_id']
        row = assets[ident]
        rec = json.loads((U / 'mask-hypotheses/records' / (ident + '.json')).read_text())
        im = load_image(U / row['source_crop'], row['source_sha256'])
        base = load_image(U / 'mask-hypotheses' / rec['masks']['center']['file'], rec['masks']['center']['sha256']) > 0
        poly = np.asarray(row['source_annotation_points_global'], dtype=np.float32).reshape(-1, 2)
        poly -= np.asarray(row['source_bbox_global'][:2], dtype=np.float32)
        roi = np.zeros(im.shape, np.uint8)
        cv2.fillPoly(roi, [np.rint(poly).astype(np.int32)], 1)
        jobs.append(('ude', ident, row['source_species'], im, base, None, roi, rec['source_points_xy'][0]))
    for group, folder, records in [('khanom', P, kh), ('gunduz', G, gun)]:
        for row in records:
            img = row['images']
            im = load_image(folder / img['crop']['file'], img['crop']['sha256'])
            base = load_image(folder / img['center']['file'], img['center']['sha256']) > 0
            ref = load_image(folder / img['reference']['file'], img['reference']['sha256']) > 0
            ys, xs = np.nonzero(ref)
            roi = np.zeros(im.shape, np.uint8)
            roi[ys.min():ys.max() + 1, xs.min():xs.max() + 1] = 1
            point = row['source_points_xy'][0] if group == 'khanom' else row['points_xy'][0]
            jobs.append((group, row['id'], '', im, base, ref, roi, point))
    rows = []
    for index, (group, ident, label, im, base, ref, roi, point) in enumerate(jobs):
        h, w = im.shape
        assert base.shape == roi.shape == im.shape and (ref is None or ref.shape == im.shape)
        factor = min(1., 512 / max(w, h))
        iw, ih = max(1, round(w * factor)), max(1, round(h * factor))
        gray = im if (iw, ih) == (w, h) else cv2.resize(im, (iw, ih), interpolation=cv2.INTER_AREA)
        region = cv2.resize(roi, (iw, ih), interpolation=cv2.INTER_NEAREST) > 0
        xy = (int(np.clip(round(point[0] * iw / w), 0, iw - 1)), int(np.clip(round(point[1] * ih / h), 0, ih - 1)))
        ys, xs = np.nonzero(region)
        radius = max(1, round(.02 * min(xs.max() - xs.min() + 1, ys.max() - ys.min() + 1)))
        seed = np.zeros((ih, iw), np.uint8)
        cv2.circle(seed, xy, radius, 1, -1)
        labels = np.where(region, cv2.GC_PR_FGD, cv2.GC_BGD).astype(np.uint8)
        labels[(seed > 0) & region] = cv2.GC_FGD
        if not np.any(labels == cv2.GC_FGD) or not np.any(labels == cv2.GC_BGD):
            raise ValueError('Invalid foreground/background seeds: ' + group + '/' + ident)
        cv2.setRNGSeed(11268000 + index)
        cv2.grabCut(cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR), labels, None,
                    np.zeros((1, 65), np.float64), np.zeros((1, 65), np.float64), 4, cv2.GC_INIT_WITH_MASK)
        candidate = cv2.resize(((labels == cv2.GC_FGD) | (labels == cv2.GC_PR_FGD)).astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) > 0
        mask_path = O / 'masks' / f'{group}-{ident}.png'
        Image.fromarray(candidate.astype(np.uint8) * 255).save(mask_path)
        panels = [ImageOps.contain(overlay(im, mask, point, []), (280, 275)) for mask in (None, base, candidate, ref)]
        comparison = Image.new('RGB', (1120, 305), 'white')
        draw = ImageDraw.Draw(comparison)
        for i, (title, panel) in enumerate(zip(('Source', 'MobileSAM center', 'GrabCut', 'Source reference' if ref is not None else 'No reference'), panels)):
            draw.text((i * 280 + 8, 3), title, fill='black')
            comparison.paste(panel, (i * 280 + (280 - panel.width) // 2, 25))
        path = O / 'comparisons' / f'{group}-{ident}.png'
        comparison.save(path)
        metrics = {}
        if ref is not None:
            for name, m in [('center', base), ('grabcut', candidate)]:
                union = int((m | ref).sum())
                metrics[name + '_reference_iou'] = int((m & ref).sum()) / union if union else None
        rows.append({'group': group, 'id': ident, 'source_name': label, 'source_dimensions_px': [w, h],
                     'roi_area_px': int(roi.sum()), 'positive_point_xy': point,
                     'center_area_px': int(base.sum()), 'candidate_area_px': int(candidate.sum()),
                     'mask': str(mask_path.relative_to(O)), 'mask_sha256': sha256(mask_path),
                     'comparison': str(path.relative_to(O)), 'comparison_sha256': sha256(path), **metrics})
        if len(rows) % 20 == 0:
            print('completed', len(rows), '/', len(jobs), flush=True)
    (O / 'results.json').write_text(json.dumps({'format': 'r112-grabcut-source-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': rows}, indent=2) + '\n')
    print('complete', len(rows), flush=True)


if __name__ == '__main__':
    main()
