"""Compare target-only contrast gains on fixed busy Academy backgrounds."""
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

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


def render_target(scene, item, dataset, gain):
    """Amplify target's multiplicative residual; never overwrite outside support."""
    path = R / scene['background']['path']
    assert sha256(path) == scene['background']['sha256']
    background = np.asarray(Image.open(path).convert('L'))
    assert background.shape == (768, 768)
    source = dataset[item['pool']][item['index']]
    meta = dataset[item['pool']].records[item['index']]
    assert meta['id'] == item['id'] and source['source_name'] == item['source_name']
    im, mask = np.asarray(source['image']), source['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))
    support0 = 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
    ox, oy = item['center_xy'][0] - rw // 2, item['center_xy'][1] - rh // 2
    ax, ay, bx, by = max(0, ox), max(0, oy), min(768, ox + rw), min(768, oy + rh)
    canvas = background.astype(np.float32).copy()
    support = np.zeros((768, 768), bool)
    if ax < bx and ay < by:
        cut = support0[ay-oy:by-oy, ax-ox:bx-ox]
        support[ay:by, ax:bx] = cut
        vals = rotated[ay-oy:by-oy, ax-ox:bx-ox].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'])
        adjusted = factor if gain == 1.0 else 1 + gain * (factor - 1)
        canvas[ay:by, ax:bx][cut] *= adjusted[cut]
    return canvas, support, 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)
    torch.set_num_threads(2)
    LOGGER.setLevel('ERROR')
    O.mkdir(exist_ok=True)
    assert not (O / 'protocol.json').exists()
    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-scene-factor-pilot/results.json',
             'results/r112/gunduz-scene-factor-pilot/verify.json',
             'results/r112/gunduz-species-retention/results.json',
             'results/r112/gunduz-species-retention/verify.json',
             'diatom_pilot/data/diatlas-taxonomic-code.csv', 'diatom_pilot/diamorph_preview.py',
             'research/r112_gunduz_native_scenes.py', 'research/r112_gunduz_contrast_gain_pilot.py']
    scene_recipes = json.loads((S / 'protocol.json').read_text())['scenes']
    previous = json.loads((P / 'results.json').read_text())['records']
    assert json.loads((P / 'verify.json').read_text())['results_sha256'] == sha256(P / 'results.json')
    assert len(previous) == 51
    protocol = {'format': 'r112-gunduz-contrast-gain-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in files}, 'model_sha256': sha256(W),
                'selection': 'All 51 previously evaluated source insertions; target alone on its same Academy background, with same position, transform, opacity, crop and classifier. No case selected by outcome.',
                'method': 'Keep baseline transmission factor f and change it to 1+g*(f-1) inside target support for g in 1, 1.5, 2 and 3; clip to 8-bit and preserve original background outside the support. Record extra pre-round out-of-range pixels, mean change and exact-name classifier output. Gain 1 must reproduce the saved target-only patch.',
                'warning': 'This is an exploratory source-contrast perturbation, not a validated physical transparency model. Gain can suppress underlying background structures, amplify noise and clip; the Academy background remains unknown even inside support. Masks, source names, source physical scale, classifier domain and specimen independence remain unverified. No gain is automatically promoted to training.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    for sub in ('gain-1p5', 'gain-2', 'gain-3', '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=';')}
    data = pools()
    prior = {(r['scene_id'], r['instance_index']): r for r in previous}
    source_predictions = {(r['scene_id'], r['instance_index']): r for r in json.loads((Q / 'results.json').read_text())['records']}
    rows = []
    for scene in scene_recipes:
        sx, sy = scene['background']['um_per_pixel_xy']
        for i, item in enumerate(scene['instances']):
            prev, source = prior[(scene['id'], i)], source_predictions[(scene['id'], i)]
            assert prev['source_id'] == source['source_id'] == item['id']
            x0, y0, x1, y1 = prev['crop_bounds_xyxy_exclusive']
            raw0, support, bg = render_target(scene, item, data, 1.)
            assert support.any()
            baseline = np.rint(np.clip(raw0, 0, 255)).astype('uint8')
            baseline_crop = baseline[y0:y1, x0:x1]
            old_path = P / prev['conditions']['actual_target_only']['patch']
            assert sha256(old_path) == prev['conditions']['actual_target_only']['patch_sha256']
            assert np.array_equal(baseline_crop, np.asarray(Image.open(old_path).convert('L')))
            baseline_clip = ((raw0 < 0) | (raw0 > 255)) & support
            baseline_metrics = {'support_px': int(support.sum()), 'pre_round_out_of_range_px': int(baseline_clip.sum()),
                                'mean_absolute_change_in_support': float(np.abs(baseline.astype(np.int16) - bg.astype(np.int16))[support].mean())}
            outputs, patches = {}, []
            ident = scene['id'] + '-' + str(i)
            for gain, label in [(1.5, 'gain-1p5'), (2., 'gain-2'), (3., 'gain-3')]:
                raw, support2, same_bg = render_target(scene, item, data, gain)
                assert np.array_equal(support, support2) and np.array_equal(bg, same_bg)
                image = np.rint(np.clip(raw, 0, 255)).astype('uint8')
                assert np.array_equal(image[~support], bg[~support])
                crop = image[y0:y1, x0:x1].copy()
                fp = O / label / (ident + '.png')
                Image.fromarray(crop).save(fp)
                prepared = preprocess(cv2.cvtColor(crop, cv2.COLOR_GRAY2BGR), sx, sy)
                pred = model.predict(prepared, imgsz=512, device='cpu', verbose=False)[0]
                scores = pred.probs.data.cpu().numpy()
                ranks = np.argsort(-scores, kind='stable')[:5]
                clipped = ((raw < 0) | (raw > 255)) & support
                outputs[label] = {'gain': gain, 'patch': str(fp.relative_to(O)), 'patch_sha256': sha256(fp),
                                  'pre_round_out_of_range_px': int(clipped.sum()),
                                  'newly_out_of_range_vs_gain1_px': int((clipped & ~baseline_clip).sum()),
                                  'mean_absolute_change_in_support': float(np.abs(image.astype(np.int16) - bg.astype(np.int16))[support].mean()),
                                  'top5': [{'code': trained.names[int(k)], 'source_name': taxa[trained.names[int(k)]]['species'],
                                            'score': float(scores[int(k)])} for k in ranks]}
                patches.append(crop)
            src_path = Q / source['source_patch']
            assert sha256(src_path) == source['source_patch_sha256']
            panels = [('Source', np.asarray(Image.open(src_path).convert('L')), source['source_top5'][0]['source_name']),
                      ('Gain 1', baseline_crop, prev['conditions']['actual_target_only']['top5'][0]['source_name'])]
            panels += [(key, patch, outputs[key]['top5'][0]['source_name']) for key, patch in zip(('gain-1p5', 'gain-2', 'gain-3'), patches)]
            plate = Image.new('RGB', (1100, 255), 'white')
            draw = ImageDraw.Draw(plate)
            for j, (title, arr, prediction) in enumerate(panels):
                img = ImageOps.contain(Image.fromarray(arr).convert('RGB'), (220, 200))
                draw.text((j*220+4, 3), title, fill='black')
                plate.paste(img, (j*220+(220-img.width)//2, 24))
                draw.text((j*220+4, 228), prediction[:30], fill='black')
            cp = O / 'comparisons' / (ident + '.png')
            plate.save(cp)
            rows.append({'scene_id': scene['id'], 'instance_index': i, 'source_id': item['id'],
                         'source_name': item['source_name'], 'name_in_model_vocabulary_exact': prev['name_in_model_vocabulary_exact'],
                         'in_frame_fraction': prev['in_frame_fraction'], 'crop_bounds_xyxy_exclusive': prev['crop_bounds_xyxy_exclusive'],
                         'source_top5': source['source_top5'], 'baseline_top5': prev['conditions']['actual_target_only']['top5'],
                         'baseline_metrics': baseline_metrics, 'gains': outputs,
                         'comparison': str(cp.relative_to(O)), 'comparison_sha256': sha256(cp)})
            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-contrast-gain-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': rows}, indent=2) + '\n')


if __name__ == '__main__':
    main()
