"""Maximum-cardinality one-to-one rectangle matching for annotation audits."""
import math

def box_iou(a,b):
    """IoU for finite ordered XYXY pixel boxes; empty boxes have zero area."""
    if len(a)!=4 or len(b)!=4 or not all(math.isfinite(float(v)) for v in (*a,*b)) or a[2]<a[0] or a[3]<a[1] or b[2]<b[0] or b[3]<b[1]:
        raise ValueError('Expected finite ordered XYXY boxes')
    w=max(0.,min(a[2],b[2])-max(a[0],b[0]));h=max(0.,min(a[3],b[3])-max(a[1],b[1]));inter=w*h;union=(a[2]-a[0])*(a[3]-a[1])+(b[2]-b[0])*(b[3]-b[1])-inter
    return inter/union if union else 0.

def match_boxes(references,predictions,threshold=.5):
    """Return maximum-cardinality assignment using IoU >= threshold.

    Matching maximizes count, not total IoU. Missing or incomplete references
    cannot be used to infer false positives. Target coordinates are used only
    for scoring, never for model inference.
    """
    if not math.isfinite(threshold) or not 0<=threshold<=1:raise ValueError('Invalid threshold')
    # Validate even when the opposite list is empty.
    for a in references:box_iou(a,a)
    for b in predictions:box_iou(b,b)
    edges=[[j for j,b in enumerate(predictions) if box_iou(a,b)>=threshold] for a in references];owner={}
    def augment(i,seen):
        for j in edges[i]:
            if j in seen:continue
            seen.add(j)
            if j not in owner or augment(owner[j],seen):owner[j]=i;return True
        return False
    for i in range(len(references)):augment(i,set())
    pairs=sorted([{'reference':i,'prediction':j,'iou':box_iou(references[i],predictions[j])} for j,i in owner.items()],key=lambda x:x['reference'])
    return {'matched':len(pairs),'reference_count':len(references),'candidate_count':len(predictions),'assignments':pairs}
