# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.

"""
Detection computation module
----------------------------

This module provides algorithms for detecting objects or patterns in images,
such as blobs, peaks, or custom structures.

Main features include:

- Blob and peak detection algorithms
- Support for object localization and counting

Detection algorithms are fundamental for many image analysis pipelines,
enabling automated extraction of regions or features of interest.
"""

# pylint: disable=invalid-name  # Allows short reference names like x, y, ...

# Note:
# ----
# All dataset classes must also be imported in the sigima.params module.

from __future__ import annotations

import guidata.dataset as gds

import sigima.enums
import sigima.tools.image
from sigima.config import _
from sigima.objects import (
    GeometryResult,
    ImageObj,
    KindShape,
    create_image_roi_around_points,
)
from sigima.proc.decorator import computation_function
from sigima.proc.image.base import compute_geometry_from_obj

# NOTE: Only parameter classes DEFINED in this module should be included in __all__.
# Parameter classes imported from other modules (like sigima.proc.base) should NOT
# be re-exported to avoid Sphinx cross-reference conflicts. The sigima.params module
# serves as the central API point that imports and re-exports all parameter classes.
__all__ = [
    "BaseBlobParam",
    "BlobDOGParam",
    "BlobDOHParam",
    "BlobLOGParam",
    "BlobOpenCVParam",
    "ContourShapeParam",
    "DetectionROIParam",
    "GenericDetectionParam",
    "HoughCircleParam",
    "Peak2DDetectionParam",
    "apply_detection_rois",
    "blob_dog",
    "blob_doh",
    "blob_log",
    "blob_opencv",
    "contour_shape",
    "hough_circle_peaks",
    "peak_detection",
    "store_roi_creation_metadata",
]


class DetectionROIParam(gds.DataSet):
    """ROI creation parameters for detection algorithms.

    This class can be inherited by any detection parameter class to provide
    standardized ROI creation functionality.
    """

    _roi_g = gds.BeginGroup(_("Regions of interest"))
    _prop_create_rois = gds.ValueProp(False)
    create_rois = gds.BoolItem(
        _("Create regions of interest"),
        default=False,
        help=_(
            "Regions of interest will be created around detected features, "
            "if at least two features are detected.\n"
            "ROI size is optimized based on feature spacing."
        ),
    ).set_prop("display", store=_prop_create_rois)
    roi_geometry = gds.ChoiceItem(
        _("ROI geometry"),
        sigima.enums.DetectionROIGeometry,
        default=sigima.enums.DetectionROIGeometry.RECTANGLE,
    ).set_prop("display", active=_prop_create_rois)
    _roi_g_e = gds.EndGroup(_("Regions of interest"))


def store_roi_creation_metadata(
    geometry: GeometryResult | None,
    create_rois: bool,
    roi_geometry: sigima.enums.DetectionROIGeometry | None = None,
) -> GeometryResult | None:
    """Store ROI creation metadata in geometry result attributes.

    This function is called by computation functions to mark that ROI creation
    should be performed on the result. The actual ROI creation is done later
    via apply_detection_rois().

    Args:
        geometry: Geometry result from detection
        create_rois: Whether to create ROIs
        roi_geometry: ROI geometry type (if None, uses default RECTANGLE)

    Returns:
        The same geometry object (for chaining), or None if geometry is None

    Example:
        >>> geometry = compute_geometry_from_obj(...)
        >>> return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)
    """
    if geometry is not None and create_rois and len(geometry) > 1:
        geometry.attrs["create_rois"] = True
        if roi_geometry is None:
            roi_geometry = sigima.enums.DetectionROIGeometry.RECTANGLE
        # Store as string value for HDF5 serialization compatibility
        geometry.attrs["roi_geometry"] = roi_geometry.value
    return geometry


def apply_detection_rois(
    obj: ImageObj,
    geometry: GeometryResult,
    force: bool = False,
    roi_geometry: sigima.enums.DetectionROIGeometry | None = None,
) -> bool:
    """Apply ROI creation from detection geometry result.

    This function checks if the geometry result contains ROI creation metadata
    and applies it to the image object by creating ROIs around detected features.

    Args:
        obj: Image object to modify
        geometry: Geometry result from a detection function
        force: If True, create ROIs even if not requested in the result attrs
        roi_geometry: Override ROI geometry from attrs (if None, uses attrs value)

    Returns:
        True if ROIs were created, False otherwise

    Example:
        >>> from sigima.proc.image import peak_detection, apply_detection_rois
        >>> from sigima.params import Peak2DDetectionParam
        >>> param = Peak2DDetectionParam()
        >>> param.create_rois = True
        >>> geometry = peak_detection(img, param)
        >>> apply_detection_rois(img, geometry)  # Creates ROIs on img
    """
    if geometry is None:
        return False

    # Check if ROI creation was requested (or forced)
    create_rois = force or geometry.attrs.get("create_rois", False)

    if not create_rois or len(geometry) < 2:
        return False

    # Get ROI geometry from parameter, attrs, or use default
    if roi_geometry is None:
        roi_geometry = geometry.attrs.get(
            "roi_geometry",
            sigima.enums.DetectionROIGeometry.RECTANGLE,
        )

    # Get detection coordinates (centers of detected objects)
    coords = geometry.centers()

    try:
        obj.roi = create_image_roi_around_points(coords, roi_geometry=roi_geometry)
        return True
    except ValueError:
        return False


class GenericDetectionParam(gds.DataSet):
    """Generic detection parameters"""

    threshold = gds.FloatItem(
        _("Relative threshold"),
        default=0.5,
        min=0.1,
        max=0.9,
        help=_(
            "Detection threshold, relative to difference between "
            "data maximum and minimum"
        ),
    )


class Peak2DDetectionParam(DetectionROIParam, GenericDetectionParam):
    """Peak detection parameters"""

    size = gds.IntItem(
        _("Neighborhoods size"),
        default=None,
        check=False,  # Allow None value
        min=1,
        unit="pixels",
        help=_(
            "Size of the sliding window used in maximum/minimum filtering algorithm "
            "(if no value is provided, the algorithm will use a default size "
            "based on the image size). "
        ),
    )


@computation_function()
def peak_detection(obj: ImageObj, p: Peak2DDetectionParam) -> GeometryResult | None:
    """Compute 2D peak detection
    with :py:func:`sigima.tools.image.get_2d_peaks_coords`

    Args:
        obj: input image
        p: parameters

    Returns:
        Peak coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "peak",
        KindShape.POINT,
        obj,
        sigima.tools.image.get_2d_peaks_coords,
        p.size,
        p.threshold,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class ContourShapeParam(GenericDetectionParam):
    """Contour shape parameters"""

    # Keep choices aligned with supported geometry kinds
    assert set(item.name for item in sigima.enums.ContourShape).issubset(
        set(item.name for item in KindShape)
    )
    shape = gds.ChoiceItem(_("Shape"), sigima.enums.ContourShape)


@computation_function()
def contour_shape(image: ImageObj, p: ContourShapeParam) -> GeometryResult | None:
    """Compute contour shape with :py:func:`sigima.tools.image.get_contour_shapes`."""
    shape: sigima.enums.ContourShape = p.shape
    kindshape = getattr(KindShape, shape.name)
    geometry = compute_geometry_from_obj(
        "contour",
        kindshape,
        image,
        sigima.tools.image.get_contour_shapes,
        shape,
        p.threshold,
    )
    return geometry


class BaseBlobParam(gds.DataSet):
    """Base class for blob detection parameters"""

    min_sigma = gds.FloatItem(
        "σ<sub>min</sub>",
        default=10.0,
        unit="pixels",
        min=0,
        nonzero=True,
        help=_(
            "The minimum standard deviation for Gaussian Kernel. "
            "Keep this low to detect smaller blobs."
        ),
    )
    max_sigma = gds.FloatItem(
        "σ<sub>max</sub>",
        default=30.0,
        unit="pixels",
        min=0,
        nonzero=True,
        help=_(
            "The maximum standard deviation for Gaussian Kernel. "
            "Keep this high to detect larger blobs."
        ),
    )
    threshold_rel = gds.FloatItem(
        _("Relative threshold"),
        default=0.2,
        min=0.0,
        max=1.0,
        help=_("Minimum intensity of blobs."),
    )
    overlap = gds.FloatItem(
        _("Overlap"),
        default=0.5,
        min=0.0,
        max=1.0,
        help=_(
            "If two blobs overlap by a fraction greater than this value, the "
            "smaller blob is eliminated."
        ),
    )


class BlobDOGParam(DetectionROIParam, BaseBlobParam):
    """Blob detection using Difference of Gaussian method"""

    exclude_border = gds.BoolItem(
        _("Exclude border"),
        default=True,
        help=_("If True, exclude blobs from the border of the image."),
    )


@computation_function()
def blob_dog(image: ImageObj, p: BlobDOGParam) -> GeometryResult | None:
    """Compute blobs using Difference of Gaussian method
    with :py:func:`sigima.tools.image.find_blobs_dog`

    Args:
        imageOutput: input image
        p: parameters

    Returns:
        Blobs coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "blob_dog",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.find_blobs_dog,
        p.min_sigma,
        p.max_sigma,
        p.overlap,
        p.threshold_rel,
        p.exclude_border,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class BlobDOHParam(DetectionROIParam, BaseBlobParam):
    """Blob detection using Determinant of Hessian method"""

    log_scale = gds.BoolItem(
        _("Log scale"),
        default=False,
        help=_(
            "If set intermediate values of standard deviations are interpolated "
            "using a logarithmic scale to the base 10. "
            "If not, linear interpolation is used."
        ),
    )


@computation_function()
def blob_doh(image: ImageObj, p: BlobDOHParam) -> GeometryResult | None:
    """Compute blobs using Determinant of Hessian method
    with :py:func:`sigima.tools.image.find_blobs_doh`

    Args:
        imageOutput: input image
        p: parameters

    Returns:
        Blobs coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "blob_doh",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.find_blobs_doh,
        p.min_sigma,
        p.max_sigma,
        p.overlap,
        p.log_scale,
        p.threshold_rel,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class BlobLOGParam(BlobDOHParam):
    """Blob detection using Laplacian of Gaussian method"""

    exclude_border = gds.BoolItem(
        _("Exclude border"),
        default=True,
        help=_("If True, exclude blobs from the border of the image."),
    )


@computation_function()
def blob_log(image: ImageObj, p: BlobLOGParam) -> GeometryResult | None:
    """Compute blobs using Laplacian of Gaussian method
    with :py:func:`sigima.tools.image.find_blobs_log`

    Args:
        imageOutput: input image
        p: parameters

    Returns:
        Blobs coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "blob_log",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.find_blobs_log,
        p.min_sigma,
        p.max_sigma,
        p.overlap,
        p.log_scale,
        p.threshold_rel,
        p.exclude_border,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class BlobOpenCVParam(DetectionROIParam, gds.DataSet):
    """Blob detection using OpenCV"""

    min_threshold = gds.FloatItem(
        _("Min. threshold"),
        default=10.0,
        min=0.0,
        help=_(
            "The minimum threshold between local maxima and minima. "
            "This parameter does not affect the quality of the blobs, "
            "only the quantity. Lower thresholds result in larger "
            "numbers of blobs."
        ),
    )
    max_threshold = gds.FloatItem(
        _("Max. threshold"),
        default=200.0,
        min=0.0,
        help=_(
            "The maximum threshold between local maxima and minima. "
            "This parameter does not affect the quality of the blobs, "
            "only the quantity. Lower thresholds result in larger "
            "numbers of blobs."
        ),
    )
    min_repeatability = gds.IntItem(
        _("Min. repeatability"),
        default=2,
        min=1,
        help=_(
            "The minimum number of times a blob needs to be detected "
            "in a sequence of images to be considered valid."
        ),
    )
    min_dist_between_blobs = gds.FloatItem(
        _("Min. distance between blobs"),
        default=10.0,
        min=0.0,
        nonzero=True,
        help=_(
            "The minimum distance between two blobs. If blobs are found "
            "closer together than this distance, the smaller blob is removed."
        ),
    )
    _prop_col = gds.ValueProp(False)
    filter_by_color = gds.BoolItem(
        _("Filter by color"),
        default=True,
        help=_("If true, the image is filtered by color instead of intensity."),
    ).set_prop("display", store=_prop_col)
    blob_color = gds.IntItem(
        _("Blob color"),
        default=0,
        help=_(
            "The color of the blobs to detect (0 for dark blobs, 255 for light blobs)."
        ),
    ).set_prop("display", active=_prop_col)
    _prop_area = gds.ValueProp(False)
    filter_by_area = gds.BoolItem(
        _("Filter by area"),
        default=True,
        help=_("If true, the image is filtered by blob area."),
    ).set_prop("display", store=_prop_area)
    min_area = gds.FloatItem(
        _("Min. area"),
        default=25.0,
        min=0.0,
        help=_("The minimum blob area."),
    ).set_prop("display", active=_prop_area)
    max_area = gds.FloatItem(
        _("Max. area"),
        default=500.0,
        min=0.0,
        help=_("The maximum blob area."),
    ).set_prop("display", active=_prop_area)
    _prop_circ = gds.ValueProp(False)
    filter_by_circularity = gds.BoolItem(
        _("Filter by circularity"),
        default=False,
        help=_("If true, the image is filtered by blob circularity."),
    ).set_prop("display", store=_prop_circ)
    min_circularity = gds.FloatItem(
        _("Min. circularity"),
        default=0.8,
        min=0.0,
        max=1.0,
        help=_("The minimum circularity of the blobs."),
    ).set_prop("display", active=_prop_circ)
    max_circularity = gds.FloatItem(
        _("Max. circularity"),
        default=1.0,
        min=0.0,
        max=1.0,
        help=_("The maximum circularity of the blobs."),
    ).set_prop("display", active=_prop_circ)
    _prop_iner = gds.ValueProp(False)
    filter_by_inertia = gds.BoolItem(
        _("Filter by inertia"),
        default=False,
        help=_("If true, the image is filtered by blob inertia."),
    ).set_prop("display", store=_prop_iner)
    min_inertia_ratio = gds.FloatItem(
        _("Min. inertia ratio"),
        default=0.6,
        min=0.0,
        max=1.0,
        help=_("The minimum inertia ratio of the blobs."),
    ).set_prop("display", active=_prop_iner)
    max_inertia_ratio = gds.FloatItem(
        _("Max. inertia ratio"),
        default=1.0,
        min=0.0,
        max=1.0,
        help=_("The maximum inertia ratio of the blobs."),
    ).set_prop("display", active=_prop_iner)
    _prop_conv = gds.ValueProp(False)
    filter_by_convexity = gds.BoolItem(
        _("Filter by convexity"),
        default=False,
        help=_("If true, the image is filtered by blob convexity."),
    ).set_prop("display", store=_prop_conv)
    min_convexity = gds.FloatItem(
        _("Min. convexity"),
        default=0.8,
        min=0.0,
        max=1.0,
        help=_("The minimum convexity of the blobs."),
    ).set_prop("display", active=_prop_conv)
    max_convexity = gds.FloatItem(
        _("Max. convexity"),
        default=1.0,
        min=0.0,
        max=1.0,
        help=_("The maximum convexity of the blobs."),
    ).set_prop("display", active=_prop_conv)


@computation_function()
def blob_opencv(image: ImageObj, p: BlobOpenCVParam) -> GeometryResult | None:
    """Compute blobs using OpenCV
    with :py:func:`sigima.tools.image.find_blobs_opencv`

    Args:
        imageOutput: input image
        p: parameters

    Returns:
        Blobs coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "blob_opencv",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.find_blobs_opencv,
        p.min_threshold,
        p.max_threshold,
        p.min_repeatability,
        p.min_dist_between_blobs,
        p.filter_by_color,
        p.blob_color,
        p.filter_by_area,
        p.min_area,
        p.max_area,
        p.filter_by_circularity,
        p.min_circularity,
        p.max_circularity,
        p.filter_by_inertia,
        p.min_inertia_ratio,
        p.max_inertia_ratio,
        p.filter_by_convexity,
        p.min_convexity,
        p.max_convexity,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)


class HoughCircleParam(DetectionROIParam, gds.DataSet):
    """Circle Hough transform parameters"""

    min_radius = gds.IntItem(
        _("Radius<sub>min</sub>"), unit="pixels", min=0, nonzero=True
    )
    max_radius = gds.IntItem(
        _("Radius<sub>max</sub>"), unit="pixels", min=0, nonzero=True
    )
    min_distance = gds.IntItem(_("Minimal distance"), min=0)


@computation_function()
def hough_circle_peaks(image: ImageObj, p: HoughCircleParam) -> GeometryResult | None:
    """Compute Hough circles
    with :py:func:`sigima.tools.image.get_hough_circle_peaks`

    Args:
        image: input image
        p: parameters

    Returns:
        Circle coordinates (with ROI creation info in attrs if requested)
    """
    geometry = compute_geometry_from_obj(
        "hough_circle_peak",
        KindShape.CIRCLE,
        image,
        sigima.tools.image.get_hough_circle_peaks,
        p.min_radius,
        p.max_radius,
        None,
        p.min_distance,
    )
    return store_roi_creation_metadata(geometry, p.create_rois, p.roi_geometry)
