"""Posthoc two-instance matching and target-exclusive evidence diagnostics.

This module requires reference masks and must not be used to select or rank
candidates at inference. It does not infer biological visibility or identity.
"""
import numpy as np

def _iou(a,b):
    inter=int(np.count_nonzero(a&b));union=int(np.count_nonzero(a|b));return inter/union if union else 0.

def two_target_evidence(references,candidates,threshold=.5):
    """Maximum-cardinality, then max-IoU, one-to-one target assignment.

    For each assigned prediction report coverage of the assigned target's
    pixels outside the other target and coverage of the other target's pixels
    outside this one. Empty exclusive regions are explicitly unidentifiable.
    These reference-derived features are diagnostics, not visibility labels or
    calibrated biological evidence. Shapes must be matching boolean 2D masks.
    """
    if len(references)!=2 or not 0<=threshold<=1:
        raise ValueError('Expected two references and threshold in [0,1]')
    if any(not isinstance(m,np.ndarray) or m.ndim!=2 or m.dtype!=np.bool_ for m in references) or references[0].shape!=references[1].shape:
        raise ValueError('Expected same-shaped boolean references')
    if any(not isinstance(c.get('mask'),np.ndarray) or c['mask'].dtype!=np.bool_ or c['mask'].shape!=references[0].shape for c in candidates):
        raise ValueError('Expected same-shaped boolean candidates')
    ids=[c['id'] for c in candidates]
    if len(set(ids))!=len(ids):raise ValueError('Candidate IDs must be unique')
    hits=[[],[]]
    for idx,c in enumerate(candidates):
        for j,ref in enumerate(references):
            value=_iou(ref,c['mask'])
            if value>=threshold:hits[j].append((idx,value))
    choices=[(0,0.,None,None)]
    for idx,value in hits[0]:choices.append((1,value,idx,None))
    for idx,value in hits[1]:choices.append((1,value,None,idx))
    for i,a in hits[0]:
        for j,b in hits[1]:
            if i!=j:choices.append((2,a+b,i,j))
    # Python's stable max preserves original candidate order for exact ties.
    count,total,i,j=max(choices,key=lambda v:(v[0],v[1]));exclusive=[references[0]&~references[1],references[1]&~references[0]];areas=[int(x.sum()) for x in exclusive];assignments=[]
    for target,idx in enumerate((i,j)):
        if idx is None:continue
        mask=candidates[idx]['mask'];coverage=[int(np.count_nonzero(mask&region))/area if area else None for region,area in zip(exclusive,areas)];own=coverage[target];other=coverage[1-target];assignments.append({'target':target,'candidate_id':ids[idx],'target_iou':_iou(mask,references[target]),'exclusive_coverage':coverage,'own_minus_other_exclusive':own-other if own is not None and other is not None else None})
    return {'matched':count,'total_iou':total,'target_iou':_iou(*references),'exclusive_areas':areas,'assignments':assignments,'prediction_pair_iou':_iou(candidates[i]['mask'],candidates[j]['mask']) if i is not None and j is not None else None}
