"""桌面 GUI 自动化（非 Web）：窗口枚举/聚焦、截图、键鼠。"""

from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING, Any

from aicd.agent.tool_args_coerce import coerce_tool_json_array
from aicd.tools.desktop_gui import run_desktop_gui_automation

if TYPE_CHECKING:
    from aicd.agent.tool_router import ToolRouter


async def _desktop_gui_automation(
    router: ToolRouter, args: dict[str, Any]
) -> dict[str, Any]:
    raw = args.get("steps")
    coerced = coerce_tool_json_array(raw, "steps", allow_empty=False)
    if isinstance(coerced, dict):
        return coerced
    steps: list[dict[str, Any]] = []
    for i, item in enumerate(coerced):
        if not isinstance(item, dict):
            return {"ok": False, "error": f"steps[{i}] must be object"}
        steps.append(dict(item))
    return await asyncio.to_thread(
        run_desktop_gui_automation,
        steps=steps,
        policy_check=router._policy.check_allowed,
        cwd=router.cwd,
    )


HANDLERS: dict[str, Any] = {
    "desktop_gui_automation": _desktop_gui_automation,
}
