"""Reversible cross-plane mask overlap links; no identity or track assertions."""
import math
import numpy as np
from .proposal_graph import mask_digest

_BITCOUNT = np.asarray([i.bit_count() for i in range(256)], dtype=np.uint8)


def build_possible_links(candidates, *, iou_threshold=0.5):
    """Return all adjacent-plane overlap links while preserving candidate identity.

    ``candidates`` is an ordered iterable of dictionaries containing a unique
    nonempty string ``id``, nonnegative integer ``z`` and a 2-D boolean ``mask``.
    All masks must share a coordinate frame and shape; no registration is
    estimated or applied here. Each output node retains its source index, exact
    mask digest, and plane. Each edge means only that the two masks overlap by
    at least the threshold. No candidates are merged, discarded, or classified.
    Empty masks remain nodes and have no edges. Other metadata and full masks
    should be retained in the caller's original archive.
    """
    if isinstance(iou_threshold, bool) or not isinstance(iou_threshold, (int, float)) or not math.isfinite(iou_threshold) or not 0 < iou_threshold <= 1:
        raise ValueError('iou_threshold must be finite and in (0, 1]')
    nodes = []
    packs = []
    ids = set()
    shape = None
    for index, candidate in enumerate(candidates):
        if not isinstance(candidate, dict):
            raise ValueError('candidate must be a dictionary')
        ident, plane, mask = candidate.get('id'), candidate.get('z'), candidate.get('mask')
        if not isinstance(ident, str) or not ident or ident in ids or type(plane) is not int or plane < 0:
            raise ValueError('candidate needs a unique id and nonnegative integer plane')
        if not isinstance(mask, np.ndarray) or mask.ndim != 2 or mask.dtype != np.bool_:
            raise ValueError('candidate mask must be a 2-D boolean array')
        if shape is None:
            shape = mask.shape
        if mask.shape != shape:
            raise ValueError('candidate masks must share a coordinate frame and shape')
        ids.add(ident)
        nodes.append({'id': ident, 'z': plane, 'source_index': index, 'area': int(mask.sum()), 'mask_sha256': mask_digest(mask)})
        packs.append(np.packbits(mask.ravel()))
    edges = []
    for i, a in enumerate(nodes):
        for j in range(i + 1, len(nodes)):
            b = nodes[j]
            if abs(a['z'] - b['z']) != 1:
                continue
            aa, bb = a['area'], b['area']
            if not aa or not bb or min(aa, bb) / max(aa, bb) < iou_threshold:
                continue
            inter = int(_BITCOUNT[np.bitwise_and(packs[i], packs[j])].sum())
            score = inter / (aa + bb - inter)
            if score >= iou_threshold:
                lo, hi = (a, b) if a['z'] < b['z'] else (b, a)
                edges.append({'a': lo['id'], 'b': hi['id'], 'lower_plane': lo['z'], 'iou': score,
                              'semantics': 'possible_overlap_not_specimen_identity'})
    edges.sort(key=lambda edge: (edge['lower_plane'], edge['a'], edge['b']))
    return {'format': 'diatom-crossplane-links-v1', 'mask_shape': list(shape) if shape is not None else None,
            'iou_threshold': float(iou_threshold), 'candidates': nodes, 'possible_links': edges,
            'warning': 'Links indicate geometric overlap only. Candidates, including identical or empty masks, remain separate; registration and biological identity are not established.'}
