"""Build uncalibrated source-component scene diagnostics, not training data."""
import ctypes
import json
import os
import random
import signal
from pathlib import Path

import cv2
import numpy as np
from PIL import Image

from diatom_pilot.gunduz_expansion_asset_dataset import GunduzExpansionAssets
from diatom_pilot.gunduz_species_asset_dataset import GunduzSpeciesAssets
from diatom_pilot.ude_scaleup_dataset import sha256

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/gunduz-uncalibrated-scenes'
B = R / 'results/r112/academy-backgrounds-v2'
SIZE = 768


def pools():
    return {'existing': GunduzSpeciesAssets('consumed_development'),
            'expansion': GunduzExpansionAssets('consumed_development')}


def render(scene, sources, omit=None):
    bg_path = R / scene['background']['path']
    assert sha256(bg_path) == scene['background']['sha256']
    background = np.asarray(Image.open(bg_path).convert('L'))
    assert background.shape == (SIZE, SIZE)
    canvas = background.astype(np.float32).copy()
    supports, details = [], []
    for j, item in enumerate(scene['instances']):
        x = sources[item['pool']][item['index']]
        meta = sources[item['pool']].records[item['index']]
        assert meta['id'] == item['id'] and x['source_name'] == item['source_name']
        assert x['source_um_per_pixel_xy'] is None
        im = np.asarray(x['image'])
        mask = x['source_component_mask']
        h, w = im.shape
        nw, nh = max(1, round(w * item['image_scale'])), max(1, round(h * item['image_scale']))
        scaled = Image.fromarray(cv2.resize(im, (nw, nh), interpolation=cv2.INTER_AREA))
        scaled_mask = Image.fromarray(cv2.resize(mask.astype('uint8'), (nw, nh), interpolation=cv2.INTER_NEAREST))
        rotated = np.asarray(scaled.rotate(item['rotation_degrees'], resample=Image.Resampling.BICUBIC, expand=True))
        rotated_mask = np.asarray(scaled_mask.rotate(item['rotation_degrees'], resample=Image.Resampling.NEAREST, expand=True)) > 0
        median = float(np.median(im[~mask])) if (~mask).any() else float(np.median(im))
        rh, rw = rotated.shape
        px, py = item['center_xy']
        x0, y0 = px - rw // 2, py - rh // 2
        ax, ay, bx, by = max(0, x0), max(0, y0), min(SIZE, x0 + rw), min(SIZE, y0 + rh)
        support = np.zeros((SIZE, SIZE), bool)
        if ax < bx and ay < by:
            cut = rotated_mask[ay-y0:by-y0, ax-x0:bx-x0]
            support[ay:by, ax:bx] = cut
            if j != omit:
                vals = rotated[ay-y0:by-y0, ax-x0:bx-x0].astype(np.float32)
                ratio = np.clip(np.maximum(vals, 1.) / max(median, 1.), .05, 2.)
                factor = 1 - item['opacity'] + item['opacity'] * np.power(ratio, item['contrast_exponent'])
                canvas[ay:by, ax:bx][cut] *= factor[cut]
        supports.append(support)
        full, inside = int(rotated_mask.sum()), int(support.sum())
        details.append({**item, 'source_image_id': x['source_image_id'], 'source_crop_sha256': meta['image_sha256'],
                        'source_mask_sha256': meta['mask_sha256'], 'source_background_median': median,
                        'resized_dimensions_px': [nw, nh], 'transformed_support_px': full,
                        'in_frame_support_px': inside, 'in_frame_fraction': inside / full if full else None,
                        'source_scale_um_per_pixel_xy': None, 'mask_status': x['mask_status'],
                        'taxonomy_status': x['taxonomy_status'], 'visible_support_status': 'undefined',
                        'background_status': 'unknown, including under insertions'})
    return np.rint(np.clip(canvas, 0, 255)).astype('uint8'), np.stack(supports), details, background


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()
    sources = pools()
    choices = [(name, i, row) for name, ds in sources.items() for i, row in enumerate(ds.records)]
    assert len(choices) == 51 and len({r['source_name'] for _, _, r in choices}) == 29
    backgrounds = []
    for record in json.loads((B / 'manifest.json').read_text())['records']:
        for image in record['images']:
            backgrounds.append({'path': str((B / image['path']).relative_to(R)), 'sha256': image['sha256'],
                                'slide': record['slide'], 'origin_xy': record['origin_xy'],
                                'z_index': image['z_index'], 'um_per_pixel_xy': record['um_per_pixel_xy']})
    assert len(backgrounds) == 192
    rng = random.Random(11274003)
    rng.shuffle(choices)
    rng.shuffle(backgrounds)
    counts = [1, 2, 3, 4, 5, 6, 8, 10, 12]
    assert sum(counts) == len(choices)
    scenes, cursor = [], 0
    for i, count in enumerate(counts):
        anchor = [rng.randrange(200, 568), rng.randrange(200, 568)]
        instances = []
        for j, (name, index, meta) in enumerate(choices[cursor:cursor+count]):
            if j == 0 and i in (2, 5, 8):
                center = [rng.choice([0, 767]), rng.randrange(768)]
            elif i >= 5 and j < min(count, 5):
                center = [max(0, min(767, anchor[0] + rng.randrange(-45, 46))),
                          max(0, min(767, anchor[1] + rng.randrange(-45, 46)))]
            else:
                center = [rng.randrange(100, 668), rng.randrange(100, 668)]
            instances.append({'pool': name, 'index': index, 'id': meta['id'], 'source_name': meta['source_name'],
                              'center_xy': center, 'image_scale': rng.choice([.4, .5, .6, .7, .8]),
                              'rotation_degrees': rng.randrange(0, 360, 15),
                              'opacity': round(rng.uniform(.3, .9), 8),
                              'contrast_exponent': round(rng.uniform(.7, 1.3), 8)})
        cursor += count
        scenes.append({'id': f'scene-{i:04d}', 'background': backgrounds[i], 'instances': instances})
    files = ['results/r112/gunduz-species-assets/assets.json', 'results/r112/gunduz-species-assets/verify.json',
             'results/r112/gunduz-expansion-assets/assets.json', 'results/r112/gunduz-expansion-assets/verify.json',
             'diatom_pilot/gunduz_species_asset_dataset.py', 'diatom_pilot/gunduz_expansion_asset_dataset.py',
             'results/r112/academy-backgrounds-v2/manifest.json', 'research/r112_gunduz_native_scenes.py']
    protocol = {'format': 'r112-gunduz-uncalibrated-scenes-v1', 'seed': 11274003,
                'inputs_sha256': {f: sha256(R / f) for f in files}, 'scenes': scenes,
                'selection': 'Every one of 51 previously accessed development candidate components once, shuffled across nine previously used Academy backgrounds. Instance counts 1,2,3,4,5,6,8,10,12.',
                'rendering': 'Arbitrary image-space scale factors 0.4–0.8, rotation, opacity and contrast; multiply source intensity residual into grayscale Academy background inside separately stored supports. These values are not physical calibration, an optical model or true visibility.',
                'warning': 'Development diagnostics only, not training-ready or an independent test. Source scale unknown, names and structurally mapped binary components unverified, background may include real diatoms even under insertions. Supports may overlap and do not define visibility. Source CC BY-NC-SA 4.0; attribution, noncommercial and share-alike terms apply.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    rows = []
    for scene in scenes:
        img, masks, details, bg = render(scene, sources)
        name = scene['id']
        ip, mp = O / (name + '.png'), O / (name + '.npz')
        Image.fromarray(img).save(ip)
        np.savez_compressed(mp, support_bits=np.packbits(masks.ravel()), support_shape=np.array(masks.shape),
                            background_label_status=np.array('unknown'), visible_support_status=np.array('undefined'))
        pairs = sum(bool((masks[a] & masks[b]).any()) for a in range(len(masks)) for b in range(a + 1, len(masks)))
        contributions = []
        for i, mask in enumerate(masks):
            without, _, _, _ = render(scene, sources, omit=i)
            diff = np.abs(img.astype(np.int16) - without.astype(np.int16))
            assert not np.any(diff[~mask])
            contributions.append({'changed_pixels': int((diff > 0).sum()),
                                  'mean_absolute_change_in_support': float(diff[mask].mean()) if mask.any() else None})
        rows.append({'id': name, 'background': scene['background'], 'image': ip.name, 'image_sha256': sha256(ip),
                     'mask_archive': mp.name, 'mask_archive_sha256': sha256(mp), 'instances': details,
                     'support_overlap_pairs': pairs, 'changed_pixels_vs_background': int((img != bg).sum()),
                     'omission_contributions': contributions})
        print('rendered', len(rows), '/', len(scenes), flush=True)
    (O / 'manifest.json').write_text(json.dumps({'format': protocol['format'],
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': rows}, indent=2) + '\n')


if __name__ == '__main__':
    main()
