"""Build a small consumed-development source pool from mapped Gündüz components."""
import collections
import ctypes
import json
import os
import signal
from pathlib import Path

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

from diatom_pilot.mask_component_guard import candidates_from_binary
from diatom_pilot.ude_scaleup_dataset import sha256
from r115_leak_screen import crop_hashes

R = Path(__file__).resolve().parents[1]
D = R / 'datasets/r115-gunduz'
P = R / 'results/r115'
K = R / 'results/r112/source-mask-polygon-proxy'
O = R / 'results/r112/gunduz-expansion-assets'
E = R / 'results/r112/gunduz-expansion'
OLD = R / 'results/r112/gunduz-species-assets'


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/r115/annotation-audit.json', 'results/r115/annotation-verify.json',
              'results/r115/results.json', 'results/r115/verify.json',
              'results/r115/image-manifest.json', 'results/r115/leak-screen.json',
              'results/r115/leak-screen-verify.json', 'results/r112/source-mask-polygon-proxy/results.json',
              'diatom_pilot/mask_component_guard.py', 'research/r115_leak_screen.py',
              'research/r112_gunduz_expansion_assets.py', 'results/r112/gunduz-expansion/protocol.json',
              'results/r112/gunduz-expansion/image-manifest.json', 'results/r112/gunduz-species-assets/assets.json',
              'results/r112/gunduz-species-assets/verify.json']
    selected = json.loads((E / 'protocol.json').read_text())['image_ids']
    assert len(selected) == 22
    protocol = {'format': 'r112-gunduz-expansion-assets-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in inputs}, 'source_image_ids': selected,
                'selection': 'All structurally mapped components from the 22 previously annotation-audited R115 candidates now designated development. Coarse masked DCT and whole-file hash comparison against the earlier 29 Khanom proxy crops and 26 Gündüz source crops; flagged components are quarantined, not replaced.',
                'crop': 'Native-resolution source grayscale crop enclosing the full connected component plus 15% of its longer side, clipped to source bounds; preserve a separate binary component mask. The source foreground is semantically binary and assignment to a species box is structural, not an author-supplied instance association.',
                'warning': 'Development images from previously accessed annotation candidates; not an independent benchmark. Samples and taxonomy are not independently reconciled; components can be wrong, incomplete, touching or contain neighboring organisms. Mask background and other objects are unknown. Physical scale and optics are unknown, so do not silently scale-match Academy fields. Source license CC BY-NC-SA 4.0; attribution and share-alike requirements apply.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    for sub in ('images', 'masks', 'overlays'):
        (O / sub).mkdir()
    audit = json.loads((P / 'annotation-audit.json').read_text())
    assert json.loads((P / 'annotation-verify.json').read_text())['audit_sha256'] == sha256(P / 'annotation-audit.json')
    assert json.loads((P / 'verify.json').read_text())['results_sha256'] == sha256(P / 'results.json')
    manifest_data = json.loads((E / 'image-manifest.json').read_text());assert manifest_data['protocol_sha256'] == sha256(E / 'protocol.json');manifest = {x['id']: x for x in manifest_data['records']}
    annotations = {x['id']: x for x in audit['records']}
    source_prior = json.loads((K / 'results.json').read_text())['records']
    prior = []
    for x in source_prior:
        i, m = (K / x['images'][key]['file'] for key in ('crop', 'reference'))
        assert sha256(i) == x['images']['crop']['sha256'] and sha256(m) == x['images']['reference']['sha256']
        rgb = np.asarray(Image.open(i).convert('RGB'))
        mask = np.asarray(Image.open(m).convert('L')) > 0
        prior.append((x['id'], crop_hashes(rgb, mask), x['source_image_sha256']))
    old_assets = json.loads((OLD / 'assets.json').read_text());old_verify = json.loads((OLD / 'verify.json').read_text());assert old_verify['assets_sha256'] == sha256(OLD / 'assets.json')
    for x in old_assets['records']:
        ip, mp = OLD / x['image'], OLD / x['mask'];assert sha256(ip) == x['image_sha256'] and sha256(mp) == x['mask_sha256']
        prior.append((x['id'], crop_hashes(np.asarray(Image.open(ip).convert('RGB')), np.asarray(Image.open(mp).convert('L')) > 0), x['source_sha256']))
    records, quarantined = [], []
    for ident in selected:
        a = annotations[ident]
        image = manifest[ident]
        source_path = R / image['path']
        mask_path, xml_path = D / 'masks' / f'{ident}.png', D / 'xml' / f'{ident}.xml'
        assert sha256(source_path) == image['sha256'] and sha256(mask_path) == a['mask_sha256'] and sha256(xml_path) == a['xml_sha256']
        rgb = np.asarray(Image.open(source_path).convert('RGB'))
        gray = np.asarray(Image.open(source_path).convert('L'))
        mask_rgb = np.asarray(Image.open(mask_path).convert('RGB'))
        assert (((mask_rgb == 0).all(2)) | ((mask_rgb == 255).all(2))).all()
        binary = (mask_rgb != 0).any(2)
        mapped = candidates_from_binary(binary, [x['box'] for x in a['objects']], minimum_area=20, containment=.98)
        assert mapped['status'] == a['status'] == 'structural_match' and mapped['instances'] == a['instances']
        _, labels = cv2.connectedComponents(binary.astype('uint8'), connectivity=8)
        for component in a['instances']:
            box_index = component['box_index']
            instance = a['objects'][box_index]
            mask = labels == component['component_label']
            assert int(mask.sum()) == component['area']
            hashes = crop_hashes(rgb, mask)
            distances = [min(int(np.count_nonzero(x != y)) for x in hashes for y in p) for _, p, _ in prior]
            min_dist = min(distances)
            exact = any(image['sha256'] == h for _, _, h in prior)
            key = ident + '-box' + str(box_index)
            if exact or min_dist <= 8:
                quarantined.append({'id': key, 'minimum_crop_distance': min_dist, 'exact_prior_image': exact})
                continue
            ys, xs = np.nonzero(mask)
            margin = int(np.ceil(.15 * max(xs.max() - xs.min() + 1, ys.max() - ys.min() + 1)))
            x0, x1 = max(0, int(xs.min()) - margin), min(gray.shape[1], int(xs.max()) + 1 + margin)
            y0, y1 = max(0, int(ys.min()) - margin), min(gray.shape[0], int(ys.max()) + 1 + margin)
            crop, target = gray[y0:y1, x0:x1], mask[y0:y1, x0:x1]
            assert int(target.sum()) == component['area']
            ip, mp, op = O / 'images' / (key + '.png'), O / 'masks' / (key + '.png'), O / 'overlays' / (key + '.png')
            Image.fromarray(crop).save(ip)
            Image.fromarray(target.astype('uint8') * 255).save(mp)
            color = np.repeat(crop[:, :, None], 3, axis=2).astype(np.float32)
            color[target] = .65 * color[target] + .35 * np.array([30, 165, 255])
            edge = cv2.morphologyEx(target.astype('uint8'), cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8)) > 0
            color[edge] = [255, 80, 25]
            Image.fromarray(np.rint(color).clip(0, 255).astype('uint8')).save(op)
            records.append({'id': key, 'source_image_id': ident, 'box_index': box_index,
                            'source_name': instance['name'], 'source_class_id': instance['id'],
                            'source_box_xyxy': instance['box'], 'component_label': component['component_label'],
                            'component_area_px': component['area'], 'inside_box_pixels': component['inside_box_pixels'],
                            'crop_bounds_xyxy_exclusive': [x0, y0, x1, y1],
                            'image': str(ip.relative_to(O)), 'image_sha256': sha256(ip),
                            'mask': str(mp.relative_to(O)), 'mask_sha256': sha256(mp),
                            'overlay': str(op.relative_to(O)), 'overlay_sha256': sha256(op),
                            'source_sha256': image['sha256'], 'xml_sha256': a['xml_sha256'],
                            'source_binary_mask_sha256': a['mask_sha256'],
                            'minimum_prior_masked_dct_distance': min_dist,
                            'source_scale_um_per_pixel_xy': None, 'background_status': 'unknown; other organisms may be present',
                            'mask_status': 'source binary component structurally mapped to source box; unverified individual instance',
                            'taxonomy_status': 'source expert-reported name; not independently reconciled',
                            'usage_scope': 'development only; not independent evaluation'})
    out = {'format': 'r112-gunduz-expansion-assets-v1', 'protocol_sha256': sha256(O / 'protocol.json'),
           'source': 'Gündüz Diatom Dataset, CC BY-NC-SA 4.0; https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset',
           'quarantined': quarantined, 'warning': protocol['warning'], 'records': records}
    (O / 'assets.json').write_text(json.dumps(out, indent=2) + '\n')
    print('built', len(records), 'candidate components across', len({x['source_name'] for x in records}), 'source names; quarantined', len(quarantined), flush=True)


if __name__ == '__main__':
    main()
