"""
agent67.tools.app_controller — 应用控制器 (macOS)

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

from .safety import ask_user_confirm


def control_app(input_json: str) -> str:
    """
    应用程序控制。

    支持: launch / quit / list / focus / notify
    """
    try:
        data = json.loads(input_json)
    except json.JSONDecodeError:
        data = {"action": "launch", "app": input_json.strip()}

    action = data.get("action", "launch")
    app_name = data.get("app", "")

    if platform.system() != "Darwin":
        return "⚠️ 应用控制目前仅支持 macOS"

    try:
        if action == "launch":
            subprocess.run(["open", "-a", app_name], check=True, timeout=10)
            return f"🚀 已启动: {app_name}"

        elif action == "quit":
            if not ask_user_confirm(f"关闭应用: {app_name}"):
                return "❌ 用户取消"
            script = f'tell application "{app_name}" to quit'
            subprocess.run(["osascript", "-e", script], timeout=10)
            return f"✅ 已关闭: {app_name}"

        elif action == "list":
            script = ('tell application "System Events" to get name of '
                      'every process whose background only is false')
            result = subprocess.run(
                ["osascript", "-e", script],
                capture_output=True, text=True, timeout=10,
            )
            return f"🖥️ 运行中的应用:\n{result.stdout.strip()}"

        elif action == "focus":
            script = f'tell application "{app_name}" to activate'
            subprocess.run(["osascript", "-e", script], timeout=10)
            return f"✅ 已切换到: {app_name}"

        elif action == "notify":
            title = data.get("title", "lambda 通知 🐂")
            message = data.get("message", "")
            script = f'display notification "{message}" with title "{title}"'
            subprocess.run(["osascript", "-e", script], timeout=10)
            return f"🔔 通知已发送: {title}"

        else:
            return f"❌ 未知操作: {action}. 支持: launch/quit/list/focus/notify"

    except subprocess.CalledProcessError as e:
        return f"❌ 应用操作失败: {e}"
    except Exception as e:
        return f"❌ 错误: {e}"
