"""
Products Tools - Tools for product management
"""
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 GetProductsTool(ReadOnlyTool):
    """Get list of products"""

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

    @property
    def description(self) -> str:
        return "Get a list of products with optional filtering by category, status, or stock level"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="category",
                type=ParameterType.STRING,
                description="Filter by product category",
                required=False
            ),
            ToolParameter(
                name="status",
                type=ParameterType.STRING,
                description="Filter by product status",
                required=False,
                enum=["active", "draft", "archived", "all"]
            ),
            ToolParameter(
                name="in_stock",
                type=ParameterType.BOOLEAN,
                description="Filter to only show in-stock products",
                required=False
            ),
            ToolParameter(
                name="limit",
                type=ParameterType.INTEGER,
                description="Maximum number of products to return",
                required=False,
                default=20
            ),
        ]

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

    @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:
            products = await connector.get_products(
                category=params.get("category"),
                status=params.get("status"),
                in_stock=params.get("in_stock"),
                limit=params.get("limit", 20)
            )

            return ToolResult.success_result(
                data=products,
                message=f"Retrieved {len(products.get('products', []))} products"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))


@register_tool
class GetProductDetailsTool(ReadOnlyTool):
    """Get details of a specific product"""

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

    @property
    def description(self) -> str:
        return "Get full details of a specific product including variants, pricing, and inventory"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="product_id",
                type=ParameterType.STRING,
                description="The product ID or SKU",
                required=True
            ),
        ]

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

    @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:
            product_id = params["product_id"]
            product = await connector.get_product_details(product_id=product_id)

            if not product:
                return ToolResult.error_result(f"Product {product_id} not found")

            return ToolResult.success_result(
                data=product,
                message=f"Product details for {product.get('title', product_id)}"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))


@register_tool
class SearchProductsTool(ReadOnlyTool):
    """Search for products by name or description"""

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

    @property
    def description(self) -> str:
        return "Search for products by name, description, SKU, or barcode"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="query",
                type=ParameterType.STRING,
                description="Search query (product name, SKU, or description)",
                required=True
            ),
            ToolParameter(
                name="limit",
                type=ParameterType.INTEGER,
                description="Maximum number of results",
                required=False,
                default=10
            ),
        ]

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

    @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:
            query = params["query"]
            limit = params.get("limit", 10)

            results = await connector.search_products(
                query=query,
                limit=limit
            )

            return ToolResult.success_result(
                data=results,
                message=f"Found {len(results.get('products', []))} products matching '{query}'"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))


@register_tool
class GetLowStockProductsTool(ReadOnlyTool):
    """Get products with low stock levels"""

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

    @property
    def description(self) -> str:
        return "Get products that are running low on stock or are out of stock"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="threshold",
                type=ParameterType.INTEGER,
                description="Stock level threshold to consider as low stock",
                required=False,
                default=10
            ),
            ToolParameter(
                name="include_out_of_stock",
                type=ParameterType.BOOLEAN,
                description="Include products with zero stock",
                required=False,
                default=True
            ),
        ]

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

    @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:
            threshold = params.get("threshold", 10)
            include_out_of_stock = params.get("include_out_of_stock", True)

            products = await connector.get_low_stock_products(
                threshold=threshold,
                include_out_of_stock=include_out_of_stock
            )

            return ToolResult.success_result(
                data=products,
                message=f"Found {len(products.get('products', []))} products with low stock"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))
