"""Load operation for reading images from disk."""

from pathlib import Path
from typing import Any

import cv2
from numpy.typing import NDArray

from axm.operations import OperationProtocol, OperationResult


class LoadOperation(OperationProtocol):
    """Load an image from disk.

    Context:
        path: Path to the image file.

    Config:
        color_space: Target color space (default: "RGB").
    """

    @property
    def name(self) -> str:
        """Operation name."""
        return "image.load"

    def execute(
        self,
        data: Any,
        context: dict[str, Any],
        config: dict[str, Any],
    ) -> OperationResult:
        """Load image from path in context.

        Args:
            data: Ignored (should be None).
            context: Must contain 'path' key.
            config: Optional color_space setting.

        Returns:
            OperationResult with loaded image array.
        """
        path = Path(context.get("path", ""))

        if not path.exists():
            return OperationResult(
                data=None,
                success=False,
                error=f"File not found: {path}",
            )

        # Load with OpenCV (BGR)
        image_bgr = cv2.imread(str(path))
        if image_bgr is None:
            return OperationResult(
                data=None,
                success=False,
                error=f"Failed to read image: {path}",
            )

        # Convert BGR to RGB
        color_space = config.get("color_space", "RGB")
        if color_space == "RGB":
            image: NDArray[Any] = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
        else:
            image = image_bgr

        return OperationResult(
            data=image,
            success=True,
            metadata={
                "width": image.shape[1],
                "height": image.shape[0],
                "channels": image.shape[2] if len(image.shape) > 2 else 1,
            },
        )
