"""Load operation for reading tabular data."""

from pathlib import Path
from typing import Any

import polars as pl

from axm.operations import OperationProtocol, OperationResult


class LoadOperation(OperationProtocol):
    """Load a tabular file using Polars.

    Context:
        path: Path to the data file.
    """

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

    def execute(
        self,
        data: Any,
        context: dict[str, Any],
        config: dict[str, Any],
    ) -> OperationResult:
        path_str = context.get("path")
        if not path_str:
            return OperationResult(
                data=None, success=False, error="Missing 'path' in context"
            )

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

        try:
            if path.suffix == ".parquet":
                df = pl.read_parquet(path)
            elif path.suffix == ".csv":
                df = pl.read_csv(path)
            else:
                return OperationResult(
                    data=None,
                    success=False,
                    error=f"Unsupported extension: {path.suffix}",
                )

            return OperationResult(data=df, success=True)
        except Exception as e:
            return OperationResult(data=None, success=False, error=str(e))
