"""
Sales Tools - Tools for sales data and analytics
"""
from typing import Any, Dict, List
from app.tools.base import ReadOnlyTool, ToolParameter, ToolResult, ParameterType
from app.tools.registry import register_tool


@register_tool
class GetSalesTool(ReadOnlyTool):
    """Get sales data for a specific period"""

    @property
    def name(self) -> str:
        return "get_sales"

    @property
    def description(self) -> str:
        return "Get sales data including total revenue, order count, and average order value for a specified time period"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="period",
                type=ParameterType.STRING,
                description="Time period for sales data",
                required=False,
                default="today",
                enum=["today", "yesterday", "this_week", "last_week", "this_month", "last_month", "this_year", "custom"]
            ),
            ToolParameter(
                name="start_date",
                type=ParameterType.DATE,
                description="Start date for custom period (YYYY-MM-DD)",
                required=False
            ),
            ToolParameter(
                name="end_date",
                type=ParameterType.DATE,
                description="End date for custom period (YYYY-MM-DD)",
                required=False
            ),
        ]

    @property
    def category(self) -> str:
        return "sales"

    @property
    def agent_types(self) -> List[str]:
        return ["ecommerce", "pos", "general"]

    async def execute(
        self,
        connector: Any,
        params: Dict[str, Any],
        context: Dict[str, Any]
    ) -> ToolResult:
        try:
            period = params.get("period", "today")
            start_date = params.get("start_date")
            end_date = params.get("end_date")

            # Call connector to get sales data
            sales_data = await connector.get_sales(
                period=period,
                start_date=start_date,
                end_date=end_date
            )

            return ToolResult.success_result(
                data=sales_data,
                message=f"Sales data retrieved for {period}"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))


@register_tool
class GetSalesComparisonTool(ReadOnlyTool):
    """Compare sales between two periods"""

    @property
    def name(self) -> str:
        return "get_sales_comparison"

    @property
    def description(self) -> str:
        return "Compare sales data between two time periods to show growth or decline percentages"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="current_period",
                type=ParameterType.STRING,
                description="Current period to analyze",
                required=False,
                default="this_month",
                enum=["this_week", "this_month", "this_quarter", "this_year"]
            ),
            ToolParameter(
                name="compare_to",
                type=ParameterType.STRING,
                description="Period to compare against",
                required=False,
                default="previous",
                enum=["previous", "same_last_year"]
            ),
        ]

    @property
    def category(self) -> str:
        return "sales"

    @property
    def agent_types(self) -> List[str]:
        return ["ecommerce", "pos", "general"]

    async def execute(
        self,
        connector: Any,
        params: Dict[str, Any],
        context: Dict[str, Any]
    ) -> ToolResult:
        try:
            current_period = params.get("current_period", "this_month")
            compare_to = params.get("compare_to", "previous")

            comparison = await connector.get_sales_comparison(
                current_period=current_period,
                compare_to=compare_to
            )

            return ToolResult.success_result(
                data=comparison,
                message=f"Sales comparison: {current_period} vs {compare_to}"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))


@register_tool
class GetTopProductsTool(ReadOnlyTool):
    """Get top selling products"""

    @property
    def name(self) -> str:
        return "get_top_products"

    @property
    def description(self) -> str:
        return "Get the top selling products by revenue or quantity for a specified period"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="period",
                type=ParameterType.STRING,
                description="Time period for analysis",
                required=False,
                default="this_month",
                enum=["today", "this_week", "this_month", "this_year"]
            ),
            ToolParameter(
                name="sort_by",
                type=ParameterType.STRING,
                description="Sort products by revenue or quantity sold",
                required=False,
                default="revenue",
                enum=["revenue", "quantity"]
            ),
            ToolParameter(
                name="limit",
                type=ParameterType.INTEGER,
                description="Number of products to return",
                required=False,
                default=10
            ),
        ]

    @property
    def category(self) -> str:
        return "sales"

    @property
    def agent_types(self) -> List[str]:
        return ["ecommerce", "pos", "general"]

    async def execute(
        self,
        connector: Any,
        params: Dict[str, Any],
        context: Dict[str, Any]
    ) -> ToolResult:
        try:
            period = params.get("period", "this_month")
            sort_by = params.get("sort_by", "revenue")
            limit = params.get("limit", 10)

            top_products = await connector.get_top_products(
                period=period,
                sort_by=sort_by,
                limit=limit
            )

            return ToolResult.success_result(
                data=top_products,
                message=f"Top {limit} products by {sort_by} for {period}"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))


@register_tool
class GetRevenueBreakdownTool(ReadOnlyTool):
    """Get revenue breakdown by category, channel, or region"""

    @property
    def name(self) -> str:
        return "get_revenue_breakdown"

    @property
    def description(self) -> str:
        return "Get revenue breakdown by category, sales channel, payment method, or region"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="period",
                type=ParameterType.STRING,
                description="Time period for analysis",
                required=False,
                default="this_month",
                enum=["this_week", "this_month", "this_quarter", "this_year"]
            ),
            ToolParameter(
                name="group_by",
                type=ParameterType.STRING,
                description="How to group the revenue breakdown",
                required=False,
                default="category",
                enum=["category", "channel", "payment_method", "region"]
            ),
        ]

    @property
    def category(self) -> str:
        return "sales"

    @property
    def agent_types(self) -> List[str]:
        return ["ecommerce", "pos", "general"]

    async def execute(
        self,
        connector: Any,
        params: Dict[str, Any],
        context: Dict[str, Any]
    ) -> ToolResult:
        try:
            period = params.get("period", "this_month")
            group_by = params.get("group_by", "category")

            breakdown = await connector.get_revenue_breakdown(
                period=period,
                group_by=group_by
            )

            return ToolResult.success_result(
                data=breakdown,
                message=f"Revenue breakdown by {group_by} for {period}"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))
