"""
Inventory Tools - Tools for inventory management
"""
from typing import Any, Dict, List
from app.tools.base import ReadOnlyTool, WriteTool, ToolParameter, ToolResult, ParameterType
from app.tools.registry import register_tool


@register_tool
class GetInventoryTool(ReadOnlyTool):
    """Get inventory levels"""

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

    @property
    def description(self) -> str:
        return "Get current inventory levels for all or specific products"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="product_ids",
                type=ParameterType.ARRAY,
                description="List of product IDs to check (leave empty for all)",
                required=False
            ),
            ToolParameter(
                name="location",
                type=ParameterType.STRING,
                description="Filter by inventory location (warehouse, store)",
                required=False
            ),
        ]

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

    @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_ids = params.get("product_ids")
            location = params.get("location")

            inventory = await connector.get_inventory(
                product_ids=product_ids,
                location=location
            )

            return ToolResult.success_result(
                data=inventory,
                message="Inventory levels retrieved"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))


@register_tool
class GetInventoryAlertsTool(ReadOnlyTool):
    """Get inventory alerts and warnings"""

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

    @property
    def description(self) -> str:
        return "Get inventory alerts including low stock, out of stock, and overstock warnings"

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="alert_type",
                type=ParameterType.STRING,
                description="Type of alerts to retrieve",
                required=False,
                default="all",
                enum=["low_stock", "out_of_stock", "overstock", "all"]
            ),
        ]

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

    @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:
            alert_type = params.get("alert_type", "all")

            alerts = await connector.get_inventory_alerts(
                alert_type=alert_type
            )

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


@register_tool
class UpdateInventoryTool(WriteTool):
    """Update inventory levels"""

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

    @property
    def description(self) -> str:
        return "Update inventory quantity for a product. Can set absolute value or adjust by delta."

    @property
    def parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="product_id",
                type=ParameterType.STRING,
                description="Product ID to update",
                required=True
            ),
            ToolParameter(
                name="quantity",
                type=ParameterType.INTEGER,
                description="New quantity or adjustment amount",
                required=True
            ),
            ToolParameter(
                name="adjustment_type",
                type=ParameterType.STRING,
                description="Whether to set absolute value or adjust by delta",
                required=False,
                default="set",
                enum=["set", "adjust"]
            ),
            ToolParameter(
                name="location",
                type=ParameterType.STRING,
                description="Inventory location to update",
                required=False
            ),
            ToolParameter(
                name="reason",
                type=ParameterType.STRING,
                description="Reason for inventory adjustment",
                required=False
            ),
        ]

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

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

    async def execute(
        self,
        connector: Any,
        params: Dict[str, Any],
        context: Dict[str, Any]
    ) -> ToolResult:
        try:
            product_id = params["product_id"]
            quantity = params["quantity"]
            adjustment_type = params.get("adjustment_type", "set")
            location = params.get("location")
            reason = params.get("reason")

            result = await connector.update_inventory(
                product_id=product_id,
                quantity=quantity,
                adjustment_type=adjustment_type,
                location=location,
                reason=reason
            )

            return ToolResult.success_result(
                data=result,
                message=f"Inventory updated for product {product_id}"
            )
        except Exception as e:
            return ToolResult.error_result(str(e))
