"""Consistent foreground masking for training and candidate inference."""
import math
import numpy as np
from PIL import Image


def masked_image(image,mask):
    gray=np.asarray(image.convert('L'));selected=np.asarray(mask.convert('L'))>0
    if gray.shape!=selected.shape or not selected.any():raise ValueError('Empty or misaligned mask')
    background=gray[~selected]
    fill=int(np.median(background if background.size else gray))
    return Image.fromarray(np.where(selected,gray,fill).astype('uint8'))


def crop_field_mask(mask,box,field_size,crop_size):
    if mask.size!=(field_size,field_size):raise ValueError('Candidate mask dimensions mismatch')
    x0,y0,x1,y1=box
    if not all(math.isfinite(x) for x in box):raise ValueError('Invalid candidate box')
    box=(max(0,math.floor(x0)),max(0,math.floor(y0)),min(field_size,math.ceil(x1)),min(field_size,math.ceil(y1)))
    if box[0]>=box[2] or box[1]>=box[3]:raise ValueError('Empty candidate box')
    cropped=mask.crop(box)
    if cropped.size!=crop_size:raise ValueError('Candidate crop does not match its box')
    return cropped


def mask_bounds_crop(image,mask,pad=8):
    """Frame an image and its mask using the same padded foreground bounds."""
    if image.size!=mask.size or type(pad) is not int or pad<0:raise ValueError('Invalid image, mask or padding')
    bounds=mask.convert('L').getbbox()
    if bounds is None:raise ValueError('Empty mask')
    left,top,right,bottom=bounds
    box=(max(0,left-pad),max(0,top-pad),min(image.width,right+pad),min(image.height,bottom+pad))
    return image.crop(box),mask.crop(box),box
