"""Label-free image/mask boundary signal, not calibrated specimen confidence."""
import cv2
import numpy as np

def gradient_map(gray):
    """Compute a fixed smoothed Sobel magnitude map from uint8 grayscale."""
    if not isinstance(gray,np.ndarray) or gray.ndim!=2 or gray.dtype!=np.uint8:
        raise ValueError('Expected uint8 grayscale image')
    src=cv2.GaussianBlur(gray,(0,0),1.0).astype('float32');gx=cv2.Sobel(src,cv2.CV_32F,1,0,ksize=3);gy=cv2.Sobel(src,cv2.CV_32F,0,1,ksize=3)
    return cv2.magnitude(gx,gy)

def score_boundary(magnitude,mask):
    """Mean gradient at the inner boundary of a boolean mask.

    This can respond to debris, background and image edges. It is not an
    accuracy score or biological identity; retain original masks and pixels.
    """
    if not isinstance(magnitude,np.ndarray) or magnitude.ndim!=2 or magnitude.dtype!=np.float32 or not np.isfinite(magnitude).all() or not isinstance(mask,np.ndarray) or mask.dtype!=np.bool_ or mask.shape!=magnitude.shape:
        raise ValueError('Expected same-shaped float32 magnitude and boolean mask')
    if not mask.any():return 0.0
    eroded=cv2.erode(mask.astype('uint8'),np.ones((3,3),'uint8'),borderType=cv2.BORDER_CONSTANT,borderValue=0)>0;edge=mask&~eroded
    return float(np.mean(magnitude[edge])) if edge.any() else 0.0

def boundary_gradient(gray,mask):
    """Calculate the fixed label-free inner-boundary signal in one call."""
    return score_boundary(gradient_map(gray),mask)
