"""viz_html_to_png / render_html_file_to_png；无 Chromium 时跳过。"""

from __future__ import annotations

from pathlib import Path

import pytest

from aicd.config import PathPolicyConfig
from aicd.tools.html_screenshot import render_html_file_to_png
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_render_simple_html_to_png_keeps_html(tmp_path: Path) -> None:
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    html = tmp_path / "page.html"
    html.write_text(
        "<!DOCTYPE html><html><body><h1 id='t'>Hello</h1></body></html>",
        encoding="utf-8",
    )
    png = tmp_path / "out.png"
    r = render_html_file_to_png(
        html,
        png,
        policy_check=pol.check_allowed,
        full_page=True,
        wait_after_load_ms=200,
    )
    assert r["ok"] is True
    assert png.is_file() and png.stat().st_size > 100
    assert html.is_file()
    assert r.get("source_retained") is True


@pytest.mark.skipif(not _chromium_available(), reason="Playwright Chromium not installed")
def test_render_html_selector_screenshot(tmp_path: Path) -> None:
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    html = tmp_path / "page.html"
    html.write_text(
        "<!DOCTYPE html><html><body><div id='box' style='width:200px;height:120px;background:#00aa00'>"
        "</div></body></html>",
        encoding="utf-8",
    )
    png = tmp_path / "box.png"
    r = render_html_file_to_png(
        html,
        png,
        policy_check=pol.check_allowed,
        selector="#box",
        wait_after_load_ms=200,
    )
    assert r["ok"] is True
    assert png.is_file() and png.stat().st_size > 80
