"""
agent67.tools.browser_controller — 浏览器控制器

Lambda: λ action_json. browser_op(action)
"""
import json
import platform
import subprocess
import webbrowser


def control_browser(input_json: str) -> str:
    """
    浏览器操作。

    支持: open / search / chrome (AppleScript)
    """
    try:
        data = json.loads(input_json)
    except json.JSONDecodeError:
        text = input_json.strip()
        if text.startswith("http"):
            data = {"action": "open", "url": text}
        else:
            data = {"action": "search", "query": text}

    action = data.get("action", "open")

    try:
        if action == "open":
            url = data.get("url", "")
            if not url.startswith("http"):
                url = "https://" + url
            webbrowser.open(url)
            return f"🌐 已打开: {url}"

        elif action == "search":
            query = data.get("query", "")
            engine = data.get("engine", "google")
            urls = {
                "google": f"https://www.google.com/search?q={query}",
                "bing": f"https://www.bing.com/search?q={query}",
                "baidu": f"https://www.baidu.com/s?wd={query}",
            }
            url = urls.get(engine, urls["google"])
            webbrowser.open(url)
            return f"🔍 已搜索: {query} (使用 {engine})"

        elif action == "chrome" and platform.system() == "Darwin":
            script = data.get("script", "")
            result = subprocess.run(
                ["osascript", "-e", script],
                capture_output=True, text=True, timeout=10,
            )
            return result.stdout.strip() or "✅ AppleScript 已执行"

        else:
            return f"❌ 未知浏览器操作: {action}"

    except Exception as e:
        return f"❌ 浏览器错误: {e}"
