"""Test bounded positive multiplicative contrast on development sources."""
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_contrast_gain_pilot import render_target
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-contrast-gain-pilot'
Q = R / 'results/r112/gunduz-scene-factor-pilot'
O = R / 'results/r112/gunduz-bounded-transmission'
W = Path('/tmp/diatom-diamorph-species-v2.pt')
T = R / 'diatom_pilot/data/diatlas-taxonomic-code.csv'


def factor_field(scene, item, datasets):
    """Return source-only factor and support before intensity quantization."""
    bg_path = R / scene['background']['path']
    assert sha256(bg_path) == scene['background']['sha256']
    bg = np.asarray(Image.open(bg_path).convert('L'))
    source = datasets[item['pool']][item['index']]
    meta = datasets[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)
    support = np.zeros(bg.shape, bool)
    factors = np.ones(bg.shape, np.float32)
    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.)
        local = 1 - item['opacity'] + item['opacity'] * np.power(ratio, item['contrast_exponent'])
        factors[ay:by, ax:bx][cut] = local[cut]
    return bg, support, factors


def measure(bg, support, factors):
    """Measure clipping and a +4-level background perturbation proxy."""
    raw = bg.astype(np.float32) * factors
    # Measure a fixed-factor response only where the input perturbation is not itself clipped.
    eligible = support & (bg <= 251)
    response = (np.clip((bg.astype(np.float32) + 4) * factors, 0, 255) - np.clip(raw, 0, 255)) / 4
    return {'pre_round_out_of_range_px': int((((raw < 0) | (raw > 255)) & support).sum()),
            'negative_pre_round_px': int(((raw < 0) & support).sum()),
            'response_eligible_px': int(eligible.sum()),
            'response_below_half_px': int(((response < .5 - 1e-5) & eligible).sum()),
            'response_median': float(np.median(response[eligible])) if eligible.any() else None}


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-contrast-gain-pilot/results.json',
             'results/r112/gunduz-contrast-gain-pilot/verify.json', 'results/r112/gunduz-scene-factor-pilot/results.json',
             'results/r112/gunduz-species-retention/results.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', 'research/r112_gunduz_bounded_transmission.py']
    scenes = json.loads((S / 'protocol.json').read_text())['scenes']
    old_rows = json.loads((P / 'results.json').read_text())['records']
    assert json.loads((P / 'verify.json').read_text())['results_sha256'] == sha256(P / 'results.json') and len(old_rows) == 51
    protocol = {'format': 'r112-gunduz-bounded-transmission-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in files}, 'model_sha256': sha256(W),
                'selection': 'All 51 previously evaluated source insertions, with identical target-only Academy backgrounds, source transforms and oracle crop boxes.',
                'method': 'Starting from the existing positive factor f, use clip(f**g,0.5,1.5) for g=1.5,2,3 inside the support. Outside is unchanged. Reuse prior gain-1 and unconstrained linear-gain-3 predictions. The factor bounds are engineering choices, not measured optics. Record floor/ceiling limits, pre-round out-of-range values and classifier outputs.',
                'background_response_proxy': 'Holding source factor fixed, add 4 gray levels to background pixels at most 251 and measure the output difference after clipping but before quantization. Report support pixels with response below 2 levels (<half input perturbation). This is pointwise sensitivity, not recognition or preservation of a real background organism.',
                'warning': 'Exploratory reused development examples; source names, masks, scale and classifier domain are uncertain. The factor floor limits pre-clip attenuation but clipping can still suppress background variation. No guarantee of physical optics, species correctness or actual background visibility; never treat background as negative.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    for folder in ('bounded-1p5', 'bounded-2', 'bounded-3', 'comparisons'):
        (O / folder).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=';')}
    previous = {(x['scene_id'], x['instance_index']): x for x in old_rows}
    factor_rows = {(x['scene_id'], x['instance_index']): x for x in json.loads((Q / 'results.json').read_text())['records']}
    datasets = pools()
    rows = []
    for scene in scenes:
        sx, sy = scene['background']['um_per_pixel_xy']
        for i, item in enumerate(scene['instances']):
            prior, factor_prior = previous[(scene['id'], i)], factor_rows[(scene['id'], i)]
            assert prior['source_id'] == factor_prior['source_id'] == item['id']
            x0, y0, x1, y1 = prior['crop_bounds_xyxy_exclusive']
            bg, support, factors = factor_field(scene, item, datasets)
            old_raw, old_mask, old_bg = render_target(scene, item, datasets, 1.)
            assert np.array_equal(support, old_mask) and np.array_equal(bg, old_bg)
            assert np.array_equal(bg.astype(np.float32) * factors, old_raw)
            assert np.all(factors[support] > 0)
            baseline_metrics = measure(bg, support, factors)
            unbounded = 1 + 3 * (factors - 1)
            unbounded_metrics = measure(bg, support, unbounded)
            outputs, visuals = {}, []
            ident = scene['id'] + '-' + str(i)
            for gain, label in [(1.5, 'bounded-1p5'), (2., 'bounded-2'), (3., 'bounded-3')]:
                requested = np.power(factors, gain)
                bounded = np.clip(requested, .5, 1.5)
                metrics = measure(bg, support, bounded)
                metrics.update({'floor_limited_px': int(((requested < .5) & support).sum()),
                                'ceiling_limited_px': int(((requested > 1.5) & support).sum())})
                image = np.rint(np.clip(bg.astype(np.float32) * bounded, 0, 255)).astype('uint8')
                assert np.array_equal(image[~support], bg[~support])
                crop = image[y0:y1, x0:x1].copy()
                path = O / label / (ident + '.png')
                Image.fromarray(crop).save(path)
                prepared = preprocess(cv2.cvtColor(crop, 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]
                outputs[label] = {'exponent': gain, 'patch': str(path.relative_to(O)), 'patch_sha256': sha256(path),
                                  'metrics': metrics,
                                  'top5': [{'code': trained.names[int(k)], 'source_name': taxa[trained.names[int(k)]]['species'],
                                            'score': float(probs[int(k)])} for k in ranks]}
                visuals.append(crop)
            prior_base = Q / factor_prior['conditions']['actual_target_only']['patch']
            prior_3 = P / prior['gains']['gain-3']['patch']
            assert sha256(prior_base) == factor_prior['conditions']['actual_target_only']['patch_sha256']
            assert sha256(prior_3) == prior['gains']['gain-3']['patch_sha256']
            panel_items = [('Original factor', np.asarray(Image.open(prior_base).convert('L')), prior['baseline_top5'][0]['source_name']),
                           ('Unbounded gain 3', np.asarray(Image.open(prior_3).convert('L')), prior['gains']['gain-3']['top5'][0]['source_name'])]
            panel_items += [(key, arr, outputs[key]['top5'][0]['source_name']) for key, arr in zip(('bounded-1p5', 'bounded-2', 'bounded-3'), visuals)]
            plate = Image.new('RGB', (1100, 255), 'white')
            draw = ImageDraw.Draw(plate)
            for j, (label, arr, prediction) in enumerate(panel_items):
                image = ImageOps.contain(Image.fromarray(arr).convert('RGB'), (220, 200))
                draw.text((j*220+4, 3), label, fill='black')
                plate.paste(image, (j*220 + (220-image.width)//2, 24))
                draw.text((j*220+4, 228), prediction[:30], fill='black')
            path = O / 'comparisons' / (ident + '.png')
            plate.save(path)
            rows.append({'scene_id': scene['id'], 'instance_index': i, 'source_id': item['id'],
                         'source_name': item['source_name'], 'name_in_model_vocabulary_exact': prior['name_in_model_vocabulary_exact'],
                         'in_frame_fraction': prior['in_frame_fraction'], 'crop_bounds_xyxy_exclusive': prior['crop_bounds_xyxy_exclusive'],
                         'support_px': int(support.sum()), 'source_top5': prior['source_top5'],
                         'baseline_top5': prior['baseline_top5'], 'unbounded_gain3_top5': prior['gains']['gain-3']['top5'],
                         'baseline_metrics': baseline_metrics, 'unbounded_gain3_metrics': unbounded_metrics,
                         'bounded': outputs, 'comparison': str(path.relative_to(O)), 'comparison_sha256': sha256(path)})
            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-bounded-transmission-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': rows}, indent=2) + '\n')


if __name__ == '__main__':
    main()
