from typing import Dict, Any, Tuple, Callable, Optional
from app.core.tools.base import BaseToolPlugin

class BrowserAutomationAgentTool(BaseToolPlugin):
    @property
    def name(self) -> str:
        return "browser_automation_agent"

    def prepare_task(self, args: Dict[str, Any], context: Dict[str, Any]) -> Tuple[Optional[Callable], Dict[str, Any]]:
        services = context.get("services")
        resolved_sid = context.get("session_id")
        on_event = context.get("on_event")
        
        browser_service = getattr(services, "browser_service", None)
        if not browser_service:
            return None, {"success": False, "error": "Browser Service not available"}
        
        action = args.get("action", "navigate").lower()
        if action == "navigate":
            return browser_service.navigate, {"url": args.get("url"), "session_id": resolved_sid, "on_event": on_event}
        elif action == "click":
            return browser_service.click, {"selector": args.get("selector"), "session_id": resolved_sid, "x": args.get("x", 0), "y": args.get("y", 0), "on_event": on_event}
        elif action == "type":
            return browser_service.type, {"text": args.get("text"), "selector": args.get("selector", ""), "session_id": resolved_sid, "on_event": on_event}
        elif action == "snapshot":
            return browser_service.get_snapshot, {"session_id": resolved_sid, "on_event": on_event}
        elif action == "screenshot":
            return browser_service.screenshot, {"session_id": resolved_sid, "on_event": on_event}
        elif action == "hover":
            return browser_service.hover, {"selector": args.get("selector"), "session_id": resolved_sid, "on_event": on_event}
        elif action == "close":
            return browser_service.close, {"session_id": resolved_sid, "on_event": on_event}
        elif action == "eval":
            # The SKILL.md schema uses 'text' for eval JS, but also support 'script' for backward compat
            script = args.get("script") or args.get("text", "")
            return browser_service.eval, {"script": script, "session_id": resolved_sid, "on_event": on_event}
        elif action == "scroll":
            return browser_service.scroll, {
                "delta_x": int(args.get("delta_x", 0)), 
                "delta_y": int(args.get("delta_y", 0)), 
                "selector": args.get("selector", ""), 
                "session_id": resolved_sid, 
                "on_event": on_event
            }
        elif action == "research":
            return browser_service.parallel_fetch, {
                "urls": args.get("urls", []),
                "session_id": resolved_sid,
                "max_concurrent": int(args.get("max_concurrent", 5)),
                "on_event": on_event
            }
        
        return None, {"success": False, "error": f"Unsupported browser action: {action}"}
