"""Compare frozen classifier outputs on matched source and composite patches."""
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 torchvision.transforms import Compose, CenterCrop, Resize, ToTensor, Normalize, InterpolationMode
from torch.nn import Sequential, Conv2d, BatchNorm2d, SiLU, ModuleList, AdaptiveAvgPool2d, Linear, Dropout
from ultralytics import YOLO
from ultralytics.nn.modules import Conv, C2f, Bottleneck, Classify
from ultralytics.nn.tasks import ClassificationModel
from ultralytics.utils import LOGGER

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'
O = R / 'results/r112/gunduz-species-retention'
W = Path('/tmp/diatom-diamorph-species-v2.pt')
T = R / 'diatom_pilot/data/diatlas-taxonomic-code.csv'


def norm(value):
    return value.strip().casefold()


def matched_patches(scene, item, mask, composite, sources):
    """Crop matching image rectangles using the known projected support box."""
    x = sources[item['pool']][item['index']]
    original = np.asarray(x['image'])
    oh, ow = original.shape
    nw, nh = max(1, round(ow * item['image_scale'])), max(1, round(oh * item['image_scale']))
    scaled = Image.fromarray(cv2.resize(original, (nw, nh), interpolation=cv2.INTER_AREA))
    transformed = np.asarray(scaled.rotate(item['rotation_degrees'], resample=Image.Resampling.BICUBIC, expand=True))
    rh, rw = transformed.shape
    ox, oy = item['center_xy'][0] - rw // 2, item['center_xy'][1] - rh // 2
    ys, xs = np.nonzero(mask)
    assert len(xs)
    x0, y0, x1, y1 = int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1
    assert 0 <= x0 - ox < x1 - ox <= rw and 0 <= y0 - oy < y1 - oy <= rh
    original_patch = transformed[y0-oy:y1-oy, x0-ox:x1-ox].copy()
    composite_patch = composite[y0:y1, x0:x1].copy()
    assert original_patch.shape == composite_patch.shape == (y1-y0, x1-x0)
    return original_patch, composite_patch, [x0, y0, x1, y1]


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()
    inputs = ['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-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/data/diatlas-taxonomic-code.csv', 'diatom_pilot/diamorph_preview.py',
              'research/r112_gunduz_native_scenes.py', 'research/r112_gunduz_species_retention.py']
    m = json.loads((S / 'manifest.json').read_text())
    v = json.loads((S / 'verify.json').read_text())
    assert v['manifest_sha256'] == sha256(S / 'manifest.json') and v['counts']['instances'] == 51
    protocol = {'format': 'r112-gunduz-species-retention-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in inputs}, 'model_sha256': sha256(W),
                'selection': 'All 51 pre-existing insertions in nine already-viewed uncalibrated diagnostic scenes. No sample or scene selection by classifier outcome.',
                'method': 'Use each saved projected support to supply an oracle axis-aligned crop; extract the same rectangle from the resized and rotated original source and the final composite. Apply identical DIAMORPH grayscale preprocessing using the background grid XY values to both arrays, then frozen 549-code classifier. The source pixel scale is unknown and arbitrary image-space resizing was used, so this is not calibrated for Gündüz or a parity claim.',
                'outcomes': 'Report top-1/top-5 exact source-name matches, known-name subset, top-1 agreement between source and composite, and match transitions; input crops can contain neighbors and occlusion. Names are matched case-insensitively without taxonomy reconciliation.',
                'warning': 'Same specimens and source masks underpin both patches; source names and mask associations are not independently adjudicated, known location is oracle, model and data are previously inspected, sources may contain other organisms, and backgrounds are unlabelled. Forced classifier outputs and match counts do not measure Academy or end-to-end accuracy, optical fidelity or biological identity.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    for sub in ('source-patches', 'composite-patches', 'comparisons'):
        (O / sub).mkdir()
    allow = [ClassificationModel, Conv, C2f, Bottleneck, Classify, Sequential, Conv2d, BatchNorm2d, SiLU,
             ModuleList, AdaptiveAvgPool2d, Linear, Dropout, Compose, CenterCrop, Resize, ToTensor,
             Normalize, InterpolationMode]
    with torch.serialization.safe_globals(allow):
        checkpoint = torch.load(W, map_location='cpu', weights_only=True)
    trained = checkpoint['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=';')}
    assert all(v in taxa for v in trained.names.values())
    known = {norm(taxa[v]['species']) for v in trained.names.values()}
    sources = pools()
    records = []
    for scene in m['records']:
        assert sha256(S / scene['image']) == scene['image_sha256'] and sha256(S / scene['mask_archive']) == scene['mask_archive_sha256']
        im = np.asarray(Image.open(S / scene['image']).convert('L'))
        with np.load(S / scene['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']):
            src, comp, bounds = matched_patches(scene, item, masks[i], im, sources)
            ident = scene['id'] + '-' + str(i)
            paths = []
            for folder, arr in [('source-patches', src), ('composite-patches', comp)]:
                fp = O / folder / (ident + '.png')
                Image.fromarray(arr).save(fp)
                paths.append(fp)
            predictions = []
            sx, sy = scene['background']['um_per_pixel_xy']
            for patch in (src, comp):
                rgb = cv2.cvtColor(patch, cv2.COLOR_GRAY2BGR)
                prepared = preprocess(rgb, sx, sy)
                output = model.predict(prepared, imgsz=512, device='cpu', verbose=False)[0]
                values = output.probs.data.cpu().numpy()
                idx = np.argsort(-values, kind='stable')[:5]
                predictions.append([{'code': trained.names[int(k)], 'source_name': taxa[trained.names[int(k)]]['species'],
                                     'score': float(values[int(k)])} for k in idx])
            source_name = item['source_name']
            panels = [ImageOps.contain(Image.fromarray(arr).convert('RGB'), (320, 280)) for arr in (src, comp)]
            preview = Image.new('RGB', (640, 335), 'white')
            draw = ImageDraw.Draw(preview)
            for j, (title, panel) in enumerate(zip(('Transformed source', 'Composite crop'), panels)):
                draw.text((j * 320 + 5, 3), title, fill='black')
                preview.paste(panel, (j * 320 + (320-panel.width)//2, 25))
                draw.text((j * 320 + 5, 310), predictions[j][0]['source_name'][:45], fill='black')
            preview_path = O / 'comparisons' / (ident + '.png')
            preview.save(preview_path)
            overlaps = sum(bool((masks[i] & masks[j]).any()) for j in range(len(masks)) if j != i)
            records.append({'scene_id': scene['id'], 'instance_index': i, 'source_id': item['id'],
                            'source_name': source_name, 'name_in_model_vocabulary_exact': norm(source_name) in known,
                            'in_frame_fraction': item['in_frame_fraction'], 'overlap_other_projected_supports': overlaps,
                            'crop_bounds_xyxy_exclusive': bounds, 'crop_dimensions_px': [src.shape[1], src.shape[0]],
                            'source_patch': str(paths[0].relative_to(O)), 'source_patch_sha256': sha256(paths[0]),
                            'composite_patch': str(paths[1].relative_to(O)), 'composite_patch_sha256': sha256(paths[1]),
                            'comparison': str(preview_path.relative_to(O)), 'comparison_sha256': sha256(preview_path),
                            'source_top5': predictions[0], 'composite_top5': predictions[1]})
            if len(records) % 10 == 0:
                print('compared', len(records), '/ 51', flush=True)
    assert len(records) == 51
    (O / 'results.json').write_text(json.dumps({'format': 'r112-gunduz-species-retention-results-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'warning': protocol['warning'], 'records': records}, indent=2) + '\n')


if __name__ == '__main__':
    main()
