"""
Data Collection Tool Wrapper - Tool interface for Agent to access data collection functionality

This module wraps the DataCollectionTool as a BaseTool for Agent integration.
"""

import logging
from typing import Dict, Any

from openfund_agent.tools.base import BaseTool, register_tool
from openfund_agent.datas.collection import DataCollectionTool


@register_tool
class DataTool(BaseTool):
    """
    Data collection tool wrapper for Agent

    This tool provides Agent with access to market data and SMC indicators
    through a standardized Tool interface.
    """

    def __init__(self, exchange_config: Dict[str, Any], cache_ttl: int = 60):
        """
        Initialize data tool

        Args:
            exchange_config: Exchange configuration
            cache_ttl: Cache time-to-live in minutes
        """
        super().__init__(
            name="data_collection", description="Fetch market data and SMC-ICT technical indicators"
        )

        self.logger = logging.getLogger(__name__)
        self.collector = DataCollectionTool(exchange_config=exchange_config, cache_ttl=cache_ttl)

    def _define_parameters(self) -> Dict[str, Any]:
        """
        Define parameter schema for data collection tool

        Returns:
            Parameter schema dictionary
        """
        return {
            "action": {
                "type": str,
                "required": True,
                "enum": ["fetch_kline", "fetch_indicators"],
                "description": "Action to perform: fetch_kline or fetch_indicators",
            },
            "symbol": {
                "type": str,
                "required": True,
                "description": 'Trading pair symbol in CCXT format (e.g., "BTC/USDT:USDT")',
            },
            "timeframe": {
                "type": str,
                "required": True,
                "enum": ["1m", "5m", "15m", "1h", "4h", "1d"],
                "description": "Timeframe for data",
            },
            "limit": {
                "type": int,
                "required": False,
                "description": "Number of data points to fetch (default: 500)",
            },
            "indicator_types": {
                "type": list,
                "required": False,
                "description": "List of indicator types: struct, fvg, orderblock, pdarray",
            },
        }

    def execute(self, parameters: Dict[str, Any]) -> Any:
        """
        Execute data collection tool

        Args:
            parameters: Tool parameters
                - action: 'fetch_kline' or 'fetch_indicators'
                - symbol: Trading pair symbol
                - timeframe: Timeframe
                - limit: Number of data points (optional, default: 500)
                - indicator_types: List of indicators (required for fetch_indicators)

        Returns:
            Execution result:
            - For fetch_kline: pandas DataFrame with OHLCV data
            - For fetch_indicators: Dictionary with indicator data

        Raises:
            ValueError: If parameters are invalid
            DataCollectionError: If data fetching fails
        """
        action = parameters["action"]
        symbol = parameters["symbol"]
        timeframe = parameters["timeframe"]
        limit = parameters.get("limit", 500)

        self.logger.info(
            f"Executing data tool: action={action}, symbol={symbol}, "
            f"timeframe={timeframe}, limit={limit}"
        )

        if action == "fetch_kline":
            return self._fetch_kline(symbol, timeframe, limit)

        elif action == "fetch_indicators":
            indicator_types = parameters.get("indicator_types", [])
            if not indicator_types:
                raise ValueError("indicator_types is required for fetch_indicators action")
            return self._fetch_indicators(symbol, timeframe, indicator_types, limit)

        else:
            raise ValueError(
                f"Invalid action: '{action}'. Must be 'fetch_kline' or 'fetch_indicators'"
            )

    def _fetch_kline(self, symbol: str, timeframe: str, limit: int) -> Dict[str, Any]:
        """
        Fetch K-line data

        Args:
            symbol: Trading pair symbol
            timeframe: Timeframe
            limit: Number of data points

        Returns:
            Dictionary with K-line data and metadata
        """
        df = self.collector.fetch_kline_data(symbol, timeframe, limit)

        # Convert DataFrame to dictionary for serialization
        return {
            "success": True,
            "data": {
                "symbol": symbol,
                "timeframe": timeframe,
                "records": len(df),
                "klines": df.to_dict("records"),
                "columns": list(df.columns),
            },
            "metadata": {"action": "fetch_kline", "cached": False},  # Could track this if needed
        }

    def _fetch_indicators(
        self, symbol: str, timeframe: str, indicator_types: list, limit: int
    ) -> Dict[str, Any]:
        """
        Fetch SMC indicators

        Args:
            symbol: Trading pair symbol
            timeframe: Timeframe
            indicator_types: List of indicator types
            limit: Number of data points

        Returns:
            Dictionary with indicator data and metadata
        """
        indicators = self.collector.fetch_smc_indicators(
            symbol=symbol, timeframe=timeframe, indicator_types=indicator_types, limit=limit
        )

        return {
            "success": True,
            "data": {"symbol": symbol, "timeframe": timeframe, "indicators": indicators},
            "metadata": {
                "action": "fetch_indicators",
                "indicator_types": indicator_types,
                "cached": False,
            },
        }
