"""Conservative binary-mask/component correspondence to annotated object boxes.

A successful structural match is a candidate instance mask, not proof of
biological correctness, annotation completeness or independent samples.
"""
import math
import cv2
import numpy as np


def candidates_from_binary(binary, boxes, *, minimum_area=20, containment=0.98):
    mask=np.asarray(binary)
    if mask.ndim!=2 or not np.isin(mask,[0,1,False,True]).all():raise ValueError('Expected a two-dimensional binary foreground mask')
    if type(minimum_area) is not int or minimum_area<1 or not isinstance(containment,(int,float)) or isinstance(containment,bool) or not math.isfinite(containment) or not 0<containment<=1:raise ValueError('Invalid matching rule')
    h,w=mask.shape;clean=[]
    if not isinstance(boxes,list) or not boxes:raise ValueError('Expected at least one box')
    for b in boxes:
        if (not isinstance(b,list) or len(b)!=4 or any(type(v) is not int for v in b)
            or not (0<=b[0]<b[2]<=w and 0<=b[1]<b[3]<=h)):raise ValueError('Invalid bounding box')
        clean.append(b)
    for i,a in enumerate(clean):
        for b in clean[i+1:]:
            if max(a[0],b[0])<min(a[2],b[2]) and max(a[1],b[1])<min(a[3],b[3]):
                return {'status':'ambiguous','reason':'intersecting_boxes','instances':[]}
    count,labels,stats,_=cv2.connectedComponentsWithStats(mask.astype('uint8'),connectivity=8)
    relevant=[i for i in range(1,count) if int(stats[i,cv2.CC_STAT_AREA])>=minimum_area]
    small_pixels=sum(int(stats[i,cv2.CC_STAT_AREA]) for i in range(1,count) if i not in relevant)
    if len(relevant)!=len(clean):return {'status':'ambiguous','reason':'component_box_count_mismatch','small_component_pixels':small_pixels,'instances':[]}
    assignments={};instances=[]
    for ident in relevant:
        area=int(stats[ident,cv2.CC_STAT_AREA]);shares=[]
        for b in clean:
            x0,y0,x1,y1=b;shares.append(int((labels[y0:y1,x0:x1]==ident).sum()))
        eligible=[i for i,n in enumerate(shares) if n/area>=containment]
        # Any significant cross-box pixels are ambiguous even with 98% containment.
        if len(eligible)!=1 or any(n>=minimum_area for i,n in enumerate(shares) if i!=eligible[0]):
            return {'status':'ambiguous','reason':'component_box_mapping','small_component_pixels':small_pixels,'instances':[]}
        box_id=eligible[0]
        if box_id in assignments:return {'status':'ambiguous','reason':'multiple_components_per_box','small_component_pixels':small_pixels,'instances':[]}
        assignments[box_id]=ident;instances.append({'box_index':box_id,'component_label':ident,'area':area,'inside_box_pixels':shares[box_id]})
    if set(assignments)!=set(range(len(clean))):return {'status':'ambiguous','reason':'box_without_component','small_component_pixels':small_pixels,'instances':[]}
    return {'status':'structural_match','reason':None,'small_component_pixels':small_pixels,'instances':sorted(instances,key=lambda x:x['box_index'])}
