"""desktop_gui_automation：依赖 pyautogui + mss 时测试。"""

from __future__ import annotations

import asyncio

import pytest

from aicd.config import PathPolicyConfig
from aicd.tools.desktop_gui import run_desktop_gui_automation
from aicd.tools.path_policy import PathPolicy


def _desktop_deps() -> bool:
    try:
        import mss  # noqa: F401
        import pyautogui  # noqa: F401
    except ImportError:
        return False
    return True


def test_desktop_unknown_op_fails(tmp_path) -> None:
    pytest.importorskip("pyautogui")
    pytest.importorskip("mss")
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    r = asyncio.run(
        asyncio.to_thread(
            run_desktop_gui_automation,
            steps=[{"op": "not_a_real_op"}],
            policy_check=pol.check_allowed,
            cwd=tmp_path,
        )
    )
    assert r.get("ok") is False
    assert r.get("failed_step_index") == 0


@pytest.mark.skipif(not _desktop_deps(), reason="pyautogui+mss not installed")
def test_desktop_gui_list_windows_step(tmp_path) -> None:
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    r = asyncio.run(
        asyncio.to_thread(
            run_desktop_gui_automation,
            steps=[{"op": "list_windows", "max": 5}],
            policy_check=pol.check_allowed,
            cwd=tmp_path,
        )
    )
    assert r.get("ok") is True
    srs = r.get("step_results") or []
    assert srs and srs[0].get("op") == "list_windows"
