"""Paired background/insertion ablation on consumed development scenes."""
import csv
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 import YOLO
from ultralytics.utils import LOGGER

import r112_gunduz_species_retention as old
from diatom_pilot.ude_scaleup_dataset import sha256
from diamorph_preview import preprocess
from r112_gunduz_native_scenes import pools, render

R = Path(__file__).resolve().parents[1]
S = R / 'results/r112/gunduz-uncalibrated-scenes'
P = R / 'results/r112/gunduz-species-retention'
O = R / 'results/r112/gunduz-scene-factor-pilot'
W = Path('/tmp/diatom-diamorph-species-v2.pt')
T = R / 'diatom_pilot/data/diatlas-taxonomic-code.csv'


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()
    input_files = ['results/r112/gunduz-uncalibrated-scenes/protocol.json',
                   'results/r112/gunduz-uncalibrated-scenes/manifest.json',
                   'results/r112/gunduz-uncalibrated-scenes/verify.json',
                   'results/r112/gunduz-species-retention/protocol.json',
                   'results/r112/gunduz-species-retention/results.json',
                   'results/r112/gunduz-species-retention/verify.json',
                   'results/r112/gunduz-species-retention/replay.json',
                   'diatom_pilot/data/diatlas-taxonomic-code.csv', 'diatom_pilot/diamorph_preview.py',
                   'research/r112_gunduz_native_scenes.py', 'research/r112_gunduz_species_retention.py',
                   'research/r112_gunduz_scene_factor_pilot.py']
    scenes = json.loads((S / 'protocol.json').read_text())['scenes']
    saved = json.loads((S / 'manifest.json').read_text())['records']
    old_rows = json.loads((P / 'results.json').read_text())['records']
    assert json.loads((P / 'verify.json').read_text())['results_sha256'] == sha256(P / 'results.json')
    assert len(scenes) == len(saved) == 9 and len(old_rows) == 51
    protocol = {'format': 'r112-gunduz-scene-factor-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in input_files}, 'model_sha256': sha256(W),
                'selection': 'All 51 existing diagnostic-scene insertions, same oracle support-derived crop boxes and classifier as the previous comparison; no case selection by prediction.',
                'conditions': {'actual_full': 'Saved composite with real Academy background and all generated insertions.',
                               'actual_target_only': 'Same real Academy background and target insertion, all other generated insertions removed.',
                               'flat_full': 'All original generated insertions over a constant field equal to the median gray value of that scene’s Academy background.',
                               'flat_target_only': 'Only the target insertion over that same constant field.'},
                'method': 'Hold target crop coordinates, source transform, opacity, contrast, rendering and classifier preprocessing fixed; re-render each condition and reuse saved source/actual-full predictions. Flat fields remove background texture and organisms but are out-of-domain. Other inserted supports can extend into a crop even without intersecting the target support. Outputs are model responses, not biological identifiability.',
                'warning': 'Exploratory reused development cases and oracle crop locations; source scale and optical fidelity unknown, names and masks not independently adjudicated, backgrounds unlabelled, taxonomy not reconciled and model outputs forced-choice. No Academy accuracy, physical causal mechanism or generalization claim.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    for sub in ('flat-backgrounds', 'actual-target-only', 'flat-target-only', 'flat-full', 'comparisons'):
        (O / sub).mkdir()
    allow = [old.ClassificationModel, old.Conv, old.C2f, old.Bottleneck, old.Classify, old.Sequential,
             old.Conv2d, old.BatchNorm2d, old.SiLU, old.ModuleList, old.AdaptiveAvgPool2d, old.Linear,
             old.Dropout, old.Compose, old.CenterCrop, old.Resize, old.ToTensor, old.Normalize, old.InterpolationMode]
    with torch.serialization.safe_globals(allow):
        trained = torch.load(W, map_location='cpu', weights_only=True)['model'].float()
    model = YOLO('yolov8l-cls.yaml', task='classify')
    model.model = trained
    taxa = {r['taxonomic_code']: r for r in csv.DictReader(T.open(), delimiter=';')}
    sources = pools()
    past = {(x['scene_id'], x['instance_index']): x for x in old_rows}
    rows = []
    for scene, existing in zip(scenes, saved):
        assert scene['id'] == existing['id'] and sha256(S / existing['image']) == existing['image_sha256']
        assert sha256(S / existing['mask_archive']) == existing['mask_archive_sha256']
        background = np.asarray(Image.open(R / scene['background']['path']).convert('L'))
        assert sha256(R / scene['background']['path']) == scene['background']['sha256']
        flat_value = int(np.median(background))
        flat_path = O / 'flat-backgrounds' / (scene['id'] + '.png')
        Image.fromarray(np.full((768, 768), flat_value, np.uint8)).save(flat_path)
        flat_scene = {**scene, 'background': {**scene['background'], 'path': str(flat_path.relative_to(R)),
                                             'sha256': sha256(flat_path)}}
        flat_full, _, _, _ = render(flat_scene, sources)
        with np.load(S / existing['mask_archive'], allow_pickle=False) as z:
            shape = tuple(z['support_shape'])
            masks = np.unpackbits(z['support_bits'], count=int(np.prod(shape))).reshape(shape).astype(bool)
        for i, item in enumerate(scene['instances']):
            prior = past[(scene['id'], i)]
            assert prior['source_id'] == item['id'] and prior['source_name'] == item['source_name']
            x0, y0, x1, y1 = prior['crop_bounds_xyxy_exclusive']
            single = {**scene, 'instances': [item]}
            flat_single = {**flat_scene, 'instances': [item]}
            actual_one, actual_support, _, _ = render(single, sources)
            flat_one, flat_support, _, _ = render(flat_single, sources)
            assert np.array_equal(actual_support[0], masks[i]) and np.array_equal(flat_support[0], masks[i])
            images = {'actual_target_only': actual_one[y0:y1, x0:x1].copy(),
                      'flat_target_only': flat_one[y0:y1, x0:x1].copy(),
                      'flat_full': flat_full[y0:y1, x0:x1].copy()}
            assert all(list(x.shape[::-1]) == prior['crop_dimensions_px'] for x in images.values())
            results = {}
            sx, sy = scene['background']['um_per_pixel_xy']
            ident = scene['id'] + '-' + str(i)
            for name, image in images.items():
                path = O / name.replace('_', '-') / (ident + '.png')
                Image.fromarray(image).save(path)
                prepared = preprocess(cv2.cvtColor(image, cv2.COLOR_GRAY2BGR), sx, sy)
                out = model.predict(prepared, imgsz=512, device='cpu', verbose=False)[0]
                probs = out.probs.data.cpu().numpy()
                ranks = np.argsort(-probs, kind='stable')[:5]
                results[name] = {'patch': str(path.relative_to(O)), 'patch_sha256': sha256(path),
                                 'top5': [{'code': trained.names[int(k)], 'source_name': taxa[trained.names[int(k)]]['species'],
                                           'score': float(probs[int(k)])} for k in ranks]}
            source_path, actual_path = P / prior['source_patch'], P / prior['composite_patch']
            assert sha256(source_path) == prior['source_patch_sha256'] and sha256(actual_path) == prior['composite_patch_sha256']
            preview_items = [('Source', np.asarray(Image.open(source_path).convert('L')), prior['source_top5'][0]['source_name']),
                             ('Actual + all', np.asarray(Image.open(actual_path).convert('L')), prior['composite_top5'][0]['source_name']),
                             ('Actual + target', images['actual_target_only'], results['actual_target_only']['top5'][0]['source_name']),
                             ('Flat + all', images['flat_full'], results['flat_full']['top5'][0]['source_name']),
                             ('Flat + target', images['flat_target_only'], results['flat_target_only']['top5'][0]['source_name'])]
            plate = Image.new('RGB', (1100, 255), 'white')
            draw = ImageDraw.Draw(plate)
            for j, (label, arr, prediction) in enumerate(preview_items):
                img = ImageOps.contain(Image.fromarray(arr).convert('RGB'), (220, 200))
                draw.text((j*220+4, 3), label, fill='black')
                plate.paste(img, (j*220 + (220-img.width)//2, 24))
                draw.text((j*220+4, 228), prediction[:30], fill='black')
            comparison = O / 'comparisons' / (ident + '.png')
            plate.save(comparison)
            rows.append({'scene_id': scene['id'], 'instance_index': i, 'source_id': item['id'],
                         'source_name': item['source_name'], 'in_frame_fraction': prior['in_frame_fraction'],
                         'overlap_other_projected_supports': prior['overlap_other_projected_supports'],
                         'crop_bounds_xyxy_exclusive': prior['crop_bounds_xyxy_exclusive'],
                         'name_in_model_vocabulary_exact': prior['name_in_model_vocabulary_exact'],
                         'flat_background_value': flat_value, 'flat_background_sha256': sha256(flat_path),
                         'source_top5': prior['source_top5'], 'actual_full_top5': prior['composite_top5'],
                         'conditions': results, 'comparison': str(comparison.relative_to(O)),
                         'comparison_sha256': sha256(comparison)})
            if len(rows) % 10 == 0:
                print('compared', len(rows), '/ 51', flush=True)
    assert len(rows) == 51
    (O / 'results.json').write_text(json.dumps({'format': 'r112-gunduz-scene-factor-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': rows}, indent=2) + '\n')


if __name__ == '__main__':
    main()
