from pathlib import Path
from PIL import Image
import numpy as np

ALPHA_THRESHOLD = 5  # pixels below this alpha are treated as transparent


def crop_transparent_canvas(
    src_path: Path,
    *,
    min_alpha: int = ALPHA_THRESHOLD,
    inplace: bool = True,
) -> Path:
    """
    Crops transparent padding from an image using alpha channel detection.

    - Works only for images with alpha (PNG, WEBP)
    - If no transparent border exists, image is unchanged
    - Returns the path to the cropped image (same path if inplace)

    Raises:
        ValueError if image has no alpha channel
    """

    img = Image.open(src_path)

    if img.mode not in ("RGBA", "LA"):
        # No alpha → nothing to crop safely
        return src_path

    rgba = img.convert("RGBA")
    alpha = np.array(rgba.split()[-1])

    # Find non-transparent pixels
    mask = alpha > min_alpha
    if not mask.any():
        # Entire image transparent → do not crop
        return src_path

    coords = np.argwhere(mask)
    y0, x0 = coords.min(axis=0)
    y1, x1 = coords.max(axis=0) + 1

    # If bounding box equals full image → no-op
    if (x0, y0, x1, y1) == (0, 0, img.width, img.height):
        return src_path

    cropped = rgba.crop((x0, y0, x1, y1))

    if inplace:
        cropped.save(src_path, format=img.format)
        return src_path

    out_path = src_path.with_name(f"{src_path.stem}_cropped{src_path.suffix}")
    cropped.save(out_path, format=img.format)
    return out_path
