"""browser_cdp_automation：Playwright 多步 UI（可选，依赖 Chromium）。"""

from __future__ import annotations

import asyncio

import pytest

from aicd.config import PathPolicyConfig
from aicd.tools.browser_automation import run_browser_automation
from aicd.tools.path_policy import PathPolicy


def _chromium_available() -> bool:
    try:
        from playwright.sync_api import sync_playwright

        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True)
            browser.close()
        return True
    except Exception:
        return False


@pytest.mark.skipif(not _chromium_available(), reason="Playwright Chromium not installed")
def test_browser_automation_file_fill_screenshot(tmp_path) -> None:
    html = tmp_path / "page.html"
    html.write_text(
        "<!DOCTYPE html><html><body>"
        '<h1 id="t">Hello</h1>'
        '<input id="q" type="text" />'
        "</body></html>",
        encoding="utf-8",
    )
    png = tmp_path / "out.png"
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    uri = html.resolve().as_uri()
    r = asyncio.run(
        run_browser_automation(
            steps=[
                {"op": "goto", "url": uri},
                {"op": "wait_for_selector", "selector": "#t"},
                {"op": "fill", "selector": "#q", "text": "abc"},
                {"op": "get_text", "selector": "#t"},
                {"op": "screenshot", "path": str(png), "full_page": True},
            ],
            policy_check=pol.check_allowed,
            cwd=tmp_path,
            default_timeout_ms=45_000,
        )
    )
    assert r.get("ok") is True, r
    assert png.is_file() and png.stat().st_size > 0
    texts = [
        x.get("text", "")
        for x in (r.get("step_results") or [])
        if x.get("op") == "get_text"
    ]
    assert any("Hello" in t for t in texts)


def test_browser_automation_rejects_javascript_url(tmp_path) -> None:
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    r = asyncio.run(
        run_browser_automation(
            steps=[{"op": "goto", "url": "javascript:alert(1)"}],
            policy_check=pol.check_allowed,
            cwd=tmp_path,
        )
    )
    assert r.get("ok") is False
    err = (r.get("error") or "").lower()
    if r.get("failed_step_index") == 0:
        assert "blocked" in err or "scheme" in err
    else:
        assert "playwright" in err or "chromium" in err or "executable" in err
