"""Compare apparent mask lengths for shared source-name strings, not calibration."""
import collections
import ctypes
import json
import os
import signal
import statistics
from pathlib import Path

import cv2
import numpy as np

from diatom_pilot.gunduz_expansion_asset_dataset import GunduzExpansionAssets
from diatom_pilot.gunduz_species_asset_dataset import GunduzSpeciesAssets
from diatom_pilot.ude_breadth_dataset import UDEBreadthDataset
from diatom_pilot.ude_breadth_extension_dataset import UDEBreadthExtensionDataset
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset, sha256

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/cross-source-length-pilot'


def major_extent(mask):
    ys, xs = np.nonzero(mask)
    if not len(xs):
        return None
    points = np.column_stack((xs, ys)).astype(np.int32).reshape(-1, 1, 2)
    hull = cv2.convexHull(points)
    _, (a, b), _ = cv2.minAreaRect(hull)
    return float(max(a, b) + 1.)


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)
    O.mkdir(exist_ok=True)
    assert not (O / 'protocol.json').exists()
    g_sets = [('gunduz-existing', GunduzSpeciesAssets('consumed_development')),
              ('gunduz-expansion', GunduzExpansionAssets('consumed_development'))]
    u_sets = [('scaleup', UDEScaleupDataset('training', include_unverified_masks=True)),
              ('breadth', UDEBreadthDataset('prior_training_components', include_unverified_masks=True)),
              ('breadth-extension', UDEBreadthExtensionDataset('prior_training_components', include_unverified_masks=True))]
    u_meta = {'scaleup': lambda d: d.entries, 'breadth': lambda d: [x for x, _ in d.entries],
              'breadth-extension': lambda d: d.records}
    g_names = {x['source_name'] for _, d in g_sets for x in d.records}
    u_names = {x['source_species'] for name, d in u_sets for x in u_meta[name](d)}
    names = sorted(g_names & u_names)
    assert len(names) == 19
    files = ['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',
             'results/r112/species-scaleup/assets.json','results/r112/species-scaleup/location-partitions.json',
             'results/r112/species-scaleup/mask-hypotheses/verify.json',
             'results/r112/species-breadth/assets.json','results/r112/species-breadth/prior-split-exposure.json',
             'results/r112/species-breadth/mask-hypotheses/verify.json',
             'results/r112/species-breadth-extension/assets.json','results/r112/species-breadth-extension/verify.json',
             'results/r112/species-breadth-extension/mask-hypotheses/verify.json',
             'diatom_pilot/gunduz_species_asset_dataset.py','diatom_pilot/gunduz_expansion_asset_dataset.py',
             'diatom_pilot/ude_scaleup_dataset.py','diatom_pilot/ude_breadth_dataset.py',
             'diatom_pilot/ude_breadth_extension_dataset.py','research/r112_cross_source_length_pilot.py']
    p = {'format': 'r112-cross-source-length-protocol-v1',
         'inputs_sha256': {f: sha256(R / f) for f in files}, 'exact_name_intersection': names,
         'selection': 'All already-accessed development source components from both Gündüz pools and all prior-training-location UDE crops in three source pools whose literal source names match exactly. No newly selected heldout images. Names are matched as strings, not taxonomically reconciled.',
         'measurement': 'Approximate long-axis mask extent: long side of OpenCV minimum-area rectangle around mask pixel centers plus one pixel. Gündüz uses structurally associated source components; UDE uses unverified MobileSAM center masks, with geometric triage recorded. UDE nominal source scale 0.09 µm per pixel. For each shared name report median UDE extent in µm, median Gündüz extent in pixels, and their ratio only as a descriptive cross-source statistic.',
         'warning': 'The ratio is NOT a Gündüz calibration or training resize: independent specimens may differ in size, view, preservation and taxonomy, sample sizes are small and biased, UDE masks can cover background, component links may be wrong, and source resolution/optics may differ. No independent benchmark or accuracy claim.'}
    (O / 'protocol.json').write_text(json.dumps(p, indent=2) + '\n')
    g_rows, u_rows = [], []
    for name, dataset in g_sets:
        for i, meta in enumerate(dataset.records):
            if meta['source_name'] not in names:
                continue
            x = dataset[i]
            g_rows.append({'pool': name, 'id': meta['id'], 'source_name': x['source_name'],
                           'source_image_id': x['source_image_id'], 'mask_sha256': meta['mask_sha256'],
                           'extent_px': major_extent(x['source_component_mask'])})
    for name, dataset in u_sets:
        for i, meta in enumerate(u_meta[name](dataset)):
            if meta['source_species'] not in names:
                continue
            x = dataset[i]
            assert x['source_um_per_pixel_xy'] == [.09, .09]
            path = dataset.root / 'mask-hypotheses/records' / (x['annotation_id'] + '.json')
            proposal = json.loads(path.read_text())
            u_rows.append({'pool': name, 'id': x['annotation_id'], 'source_name': x['source_name'],
                           'source_slide': meta['source_slide_group'], 'source_site_component': x['source_site_component'],
                           'mask_sha256': proposal['masks']['center']['sha256'], 'triage': x['mask_triage'],
                           'extent_px': major_extent(x['weak_mask_proposals'][0])})
    out = []
    for name in names:
        gs = [x['extent_px'] for x in g_rows if x['source_name'] == name and x['extent_px'] is not None]
        us = [x['extent_px'] for x in u_rows if x['source_name'] == name and x['extent_px'] is not None]
        assert gs and us
        gm, um = statistics.median(gs), statistics.median(us)
        out.append({'source_name': name, 'gunduz_count': len(gs), 'ude_count': len(us),
                    'gunduz_extent_px_median': gm, 'gunduz_extent_px_range': [min(gs), max(gs)],
                    'ude_extent_px_median': um, 'ude_extent_px_range': [min(us), max(us)],
                    'ude_nominal_median_extent_um': .09 * um,
                    'descriptive_median_length_ratio_um_per_gunduz_px_not_calibration': .09 * um / gm,
                    'ude_needs_inspection': sum(x['triage'] == 'needs-inspection' for x in u_rows if x['source_name'] == name)})
    result = {'format': 'r112-cross-source-length-results-v1', 'protocol_sha256': sha256(O / 'protocol.json'),
              'warning': p['warning'], 'species_comparisons': out, 'gunduz': g_rows, 'ude': u_rows}
    (O / 'results.json').write_text(json.dumps(result, indent=2) + '\n')
    print('compared', len(names), 'literal names;', len(g_rows), 'Gündüz and', len(u_rows), 'UDE masks', flush=True)


if __name__ == '__main__':
    main()
