"""Browser automation tools for AiCippy Agents."""

from __future__ import annotations

import logging
from typing import Any, cast

from aicippy.browser.manager import BrowserManager

logger = logging.getLogger(__name__)


class UnknownBrowserToolError(ValueError):
    """Raised when an unrecognized browser tool name is requested."""

    def __init__(self, name: str) -> None:
        super().__init__(f"Unknown browser tool: {name}")


class BrowserTools:
    """Provides tool definitions for browser automation."""

    def __init__(self, browser_manager: BrowserManager) -> None:
        """Initialize browser tools with the given browser manager."""
        self._browser = browser_manager

    def get_tool_definitions(self) -> list[dict[str, Any]]:
        """Return the list of available browser tool definitions."""
        return [
            {
                "name": "browser_screenshot",
                "description": "Capture a screenshot of the active browser tab.",
                "parameters": {
                    "type": "object",
                    "properties": {},
                },
            },
            {
                "name": "browser_get_page_content",
                "description": "Get the HTML content of the active browser tab.",
                "parameters": {
                    "type": "object",
                    "properties": {},
                },
            },
            {
                "name": "browser_click",
                "description": "Click an element in the browser page.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "selector": {
                            "type": "string",
                            "description": "CSS selector of the element to click",
                        },
                    },
                    "required": ["selector"],
                },
            },
            {
                "name": "browser_fill_form",
                "description": "Fill a form in the browser page.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "data": {
                            "type": "object",
                            "description": "Map of CSS selectors to values",
                        },
                    },
                    "required": ["data"],
                },
            },
            {
                "name": "browser_scroll",
                "description": "Scroll the browser page.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "direction": {
                            "type": "string",
                            "enum": ["up", "down", "left", "right"],
                        },
                        "amount": {
                            "type": "integer",
                            "description": "Pixels to scroll",
                        },
                    },
                    "required": ["direction"],
                },
            },
        ]

    async def call_tool(self, name: str, arguments: dict[str, object]) -> str | bool | object:
        """Execute a browser tool by name and return its result."""
        if name == "browser_screenshot":
            return await self._browser.capture_screenshot()
        if name == "browser_get_page_content":
            return await self._browser.get_page_content()
        if name == "browser_click":
            return await self._browser.click_element(str(arguments["selector"]))
        if name == "browser_fill_form":
            form_data = cast(dict[str, str], arguments["data"])
            return await self._browser.fill_form(form_data)
        if name == "browser_scroll":
            return await self._browser.execute_script(
                f"window.scrollBy(0, {arguments.get('amount', 500)})",
            )  # Simple scroll for now
        raise UnknownBrowserToolError(name)
