"""Exact greedy mask suppression with inexpensive geometric prechecks.

This retains the same order-dependent behavior as ordinary greedy IoU NMS;
it is not an overlap-safe instance-separation algorithm. Callers should keep
all original masks and suppression aliases for later review.
"""
import numpy as np

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

def greedy_mask_nms(items,threshold):
    """Return (kept, aliases) for same-shaped 2-D boolean masks in input order.

    A mask is suppressed by the first previously kept mask with IoU greater
    than or equal to threshold. Empty-mask IoU is defined as zero. No masks are
    mutated or deleted. Exact full-resolution masks, not resized proxies, are
    used for the final comparison.
    """
    if not np.isfinite(threshold) or not 0<=threshold<=1:
        raise ValueError('Expected threshold in [0,1]')
    kept=[];aliases=[];packs=[];areas=[];bounds=[];shape=None
    for item in items:
        mask=item['mask']
        if not isinstance(mask,np.ndarray) or mask.ndim!=2 or mask.dtype!=np.bool_ or (shape is not None and mask.shape!=shape):
            raise ValueError('Expected equal-shaped 2D boolean masks')
        shape=mask.shape;ys,xs=np.nonzero(mask);area=len(xs);packed=np.packbits(mask.ravel());bound=(int(xs.min()),int(ys.min()),int(xs.max()),int(ys.max())) if area else None
        hit=None
        for j,(other,other_area,other_bound) in enumerate(zip(packs,areas,bounds)):
            if threshold>0:
                if not area or not other_area or min(area,other_area)/max(area,other_area)<threshold:
                    continue
                if bound[2]<other_bound[0] or other_bound[2]<bound[0] or bound[3]<other_bound[1] or other_bound[3]<bound[1]:
                    continue
            inter=int(_BITCOUNT[np.bitwise_and(packed,other)].sum());union=area+other_area-inter;iou=inter/union if union else 0.
            if iou>=threshold:
                hit=j;break
        if hit is None:
            kept.append(item);packs.append(packed);areas.append(area);bounds.append(bound)
        else:
            aliases.append({'candidate':item['id'],'kept':kept[hit]['id']})
    return kept,aliases
