"""Explore a cumulative factor bound on the already-used R116 pairs."""
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
from ultralytics import YOLO
from ultralytics.utils import LOGGER

import r112_gunduz_species_retention as defs
from diatom_pilot.ude_scaleup_dataset import sha256
from diamorph_preview import preprocess
from r112_gunduz_native_scenes import pools
from r112_gunduz_overlap_pair_pilot import images, placement

R = Path(__file__).resolve().parents[1]
P = R / 'results/r112/gunduz-overlap-pair-pilot'
O = R / 'results/r112/gunduz-cumulative-overlap-pilot'
W = Path('/tmp/diatom-diamorph-species-v2.pt')
T = R / 'diatom_pilot/data/diatlas-taxonomic-code.csv'


def cumulative(bg, supports, factors):
    """Apply prior bounded layers, then bound their product only in intersection."""
    bounded = [np.clip(np.power(f, 3.), .5, 1.5) for f in factors]
    inter = supports[0] & supports[1]
    product = bounded[0] * bounded[1]
    low = inter & (product < .5)
    high = inter & (product > 1.5)
    raw = bg.astype(np.float32) * bounded[0] * bounded[1]
    raw[low] = bg[low].astype(np.float32) * .5
    raw[high] = bg[high].astype(np.float32) * 1.5
    return raw, bounded, low, high


def pixel_metrics(bg, supports, raw, factors, low, high):
    """Calculate fixed-factor response and per-target omission diagnostics."""
    inter = supports[0] & supports[1]
    eligible = inter & (bg <= 251)
    perturbed = (bg.astype(np.float32) + 4) * factors[0] * factors[1]
    perturbed[low] = (bg[low].astype(np.float32) + 4) * .5
    perturbed[high] = (bg[high].astype(np.float32) + 4) * 1.5
    response = (np.clip(perturbed, 0, 255) - np.clip(raw, 0, 255)) / 4
    pair = np.rint(np.clip(raw, 0, 255)).astype('uint8')
    marginal = []
    for target in range(2):
        other = np.rint(np.clip(bg.astype(np.float32) * factors[1-target], 0, 255)).astype('uint8')
        diff = np.abs(pair.astype(np.int16) - other.astype(np.int16))
        marginal.append({'intersection_unchanged_px': int(((diff == 0) & inter).sum()),
                         'intersection_mean_abs_change': float(diff[inter].mean())})
    return {'intersection_px': int(inter.sum()), 'floor_limited_px': int(low.sum()), 'ceiling_limited_px': int(high.sum()),
            'intersection_out_of_range_px': int((((raw < 0) | (raw > 255)) & inter).sum()),
            'response_eligible_px': int(eligible.sum()),
            'response_below_half_px': int(((response < .5 - 1e-5) & eligible).sum()),
            'per_target_marginal': marginal}


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-overlap-pair-pilot/protocol.json', 'results/r112/gunduz-overlap-pair-pilot/results.json',
             'results/r112/gunduz-overlap-pair-pilot/verify.json', 'results/r112/gunduz-overlap-pair-pilot/replay.json',
             'diatom_pilot/data/diatlas-taxonomic-code.csv', 'diatom_pilot/diamorph_preview.py',
             'research/r112_gunduz_overlap_pair_pilot.py', 'research/r112_gunduz_bounded_transmission.py',
             'research/r116_cumulative_overlap_pilot.py']
    original = json.loads((P / 'results.json').read_text())
    original_protocol = json.loads((P / 'protocol.json').read_text())
    assert json.loads((P / 'verify.json').read_text())['results_sha256'] == sha256(P / 'results.json')
    assert len(original['records']) == len(original_protocol['pairs']) == 25
    protocol = {'format': 'r116-cumulative-overlap-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in files}, 'model_sha256': sha256(W),
                'selection': 'All 25 previously viewed R116 pairs and all 50 oracle target crops; no selection by outcome. This exploration was motivated by the earlier results and is not a fresh validation.',
                'method': 'Keep both prior per-layer factors clip(f**3,0.5,1.5) and all positions. Only where projected supports intersect, clamp the product of the two factors to [0.5,1.5] before multiplying by the background. Outside intersection preserve the previously saved bounded pair exactly; target-alone controls remain identical. Reuse prior predictions and infer new pair crops with the same fixed classifier.',
                'outcomes': 'Record factor-limited pixels, clipping, the same pre-round +4 background-response proxy, and changes in the pair when each target is removed. These are renderer interventions, not anatomical visibility.',
                'warning': 'These 25 hard pairs and bounds were already examined; no statistical validation, biological correctness, physical optics or Academy accuracy follows. Cumulative clamping can hide a target or flatten details. Source masks/names/scale are uncertain and real backgrounds remain unknown. No automatic training promotion.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    (O / 'frames').mkdir()
    (O / 'patches').mkdir()
    allow = [defs.ClassificationModel, defs.Conv, defs.C2f, defs.Bottleneck, defs.Classify, defs.Sequential,
             defs.Conv2d, defs.BatchNorm2d, defs.SiLU, defs.ModuleList, defs.AdaptiveAvgPool2d, defs.Linear,
             defs.Dropout, defs.Compose, defs.CenterCrop, defs.Resize, defs.ToTensor, defs.Normalize, defs.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=';')}
    datasets = pools()
    rows = []
    for recipe, previous in zip(original_protocol['pairs'], original['records']):
        assert recipe['id'] == previous['id']
        positioned, bg, supports, factors, shift = placement(recipe, recipe['instances'], datasets)
        assert positioned == previous['positioned_instances'] and shift == previous['placement_shift_index']
        assert int((supports[0] & supports[1]).sum()) == previous['intersection_px']
        old_single_a, old_single_b, old_pair = images(bg, factors, 'bounded')
        assert sha256(P / previous['frames']['bounded']['file']) == previous['frames']['bounded']['sha256']
        assert np.array_equal(old_pair, np.asarray(Image.open(P / previous['frames']['bounded']['file']).convert('L')))
        raw, bounded, low, high = cumulative(bg, supports, factors)
        out = np.rint(np.clip(raw, 0, 255)).astype('uint8')
        assert np.array_equal(out[~(supports[0] & supports[1])], old_pair[~(supports[0] & supports[1])])
        metrics = pixel_metrics(bg, supports, raw, bounded, low, high)
        reference_raw = bg.astype(np.float32) * bounded[0] * bounded[1]
        zeros = np.zeros(bg.shape, bool)
        reference = pixel_metrics(bg, supports, reference_raw, bounded, zeros, zeros)
        frame_path = O / 'frames' / (recipe['id'] + '.png')
        Image.fromarray(out).save(frame_path)
        targets = []
        for i, target in enumerate(previous['targets']):
            x0, y0, x1, y1 = target['bbox_xyxy_exclusive']
            crop = out[y0:y1, x0:x1].copy()
            fp = O / 'patches' / f"{recipe['id']}-{i}.png"
            Image.fromarray(crop).save(fp)
            sx, sy = recipe['background']['um_per_pixel_xy']
            prepared = preprocess(cv2.cvtColor(crop, cv2.COLOR_GRAY2BGR), sx, sy)
            result = model.predict(prepared, imgsz=512, device='cpu', verbose=False)[0]
            scores = result.probs.data.cpu().numpy()
            order = np.argsort(-scores, kind='stable')[:5]
            targets.append({'source': target['source'], 'bbox_xyxy_exclusive': target['bbox_xyxy_exclusive'],
                            'name_in_model_vocabulary_exact': target['source_name_in_model_vocabulary_exact'],
                            'single_top5': target['conditions']['bounded_single']['top5'],
                            'previous_overlap_top5': target['conditions']['bounded_overlap']['top5'],
                            'cumulative_top5': [{'code': trained.names[int(k)], 'source_name': taxa[trained.names[int(k)]]['species'],
                                                 'score': float(scores[int(k)])} for k in order],
                            'patch': str(fp.relative_to(O)), 'patch_sha256': sha256(fp)})
        rows.append({'id': recipe['id'], 'background': recipe['background'], 'frame': str(frame_path.relative_to(O)),
                     'frame_sha256': sha256(frame_path), 'previous_bounded_metrics': reference,
                     'cumulative_metrics': metrics, 'targets': targets})
        if len(rows) % 5 == 0:
            print('compared', len(rows), '/ 25 pairs', flush=True)
    (O / 'results.json').write_text(json.dumps({'format': 'r116-cumulative-overlap-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': rows}, indent=2) + '\n')


if __name__ == '__main__':
    main()
