"""diagram_drawio_export_png（可选网络 + Playwright；可由环境变量禁用或仅离线 CLI）。"""

from __future__ import annotations

import os
from pathlib import Path

import pytest

from aicd.agent.tools_openai import openai_tools
from aicd.config import PathPolicyConfig
from aicd.kit import drawio_spec
from aicd.tools.drawio_embed_export import export_drawio_file_to_png
from aicd.tools.path_policy import PathPolicy


def _tool_names() -> set[str]:
    return {t["function"]["name"] for t in openai_tools()}


def test_openai_tools_omits_drawio_export_by_default(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.delenv("AICD_ENABLE_DRAWIO_EXPORT_PNG", raising=False)
    monkeypatch.delenv("AICD_DISABLE_DRAWIO_EXPORT_PNG", raising=False)
    assert "diagram_drawio_export_png" not in _tool_names()
    assert "diagram_drawio_write" in _tool_names()


def test_openai_tools_includes_drawio_export_when_enabled(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setenv("AICD_ENABLE_DRAWIO_EXPORT_PNG", "1")
    monkeypatch.delenv("AICD_DISABLE_DRAWIO_EXPORT_PNG", raising=False)
    assert "diagram_drawio_export_png" in _tool_names()


def test_export_png_disabled_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("AICD_ENABLE_DRAWIO_EXPORT_PNG", raising=False)
    monkeypatch.delenv("AICD_DISABLE_DRAWIO_EXPORT_PNG", raising=False)
    built = drawio_spec.build_drawio_xml([{"id": "a", "label": "A"}], [])
    assert built.get("ok")
    p_drawio = tmp_path / "d.drawio"
    p_drawio.write_text(str(built["xml"]), encoding="utf-8")
    p_png = tmp_path / "d.png"
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    r = export_drawio_file_to_png(p_drawio, p_png, policy_check=pol.check_allowed)
    assert r.get("ok") is False
    assert "未启用" in str(r.get("error", "")) or "ENABLE" in str(r.get("error", ""))


def test_disable_overrides_enable(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("AICD_ENABLE_DRAWIO_EXPORT_PNG", "1")
    monkeypatch.setenv("AICD_DISABLE_DRAWIO_EXPORT_PNG", "1")
    built = drawio_spec.build_drawio_xml([{"id": "a", "label": "A"}], [])
    assert built.get("ok")
    p_drawio = tmp_path / "d.drawio"
    p_drawio.write_text(str(built["xml"]), encoding="utf-8")
    p_png = tmp_path / "d.png"
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    r = export_drawio_file_to_png(p_drawio, p_png, policy_check=pol.check_allowed)
    assert r.get("ok") is False


def test_offline_only_skips_embed_without_cli(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("AICD_ENABLE_DRAWIO_EXPORT_PNG", "1")
    monkeypatch.setenv("AICD_DRAWIO_OFFLINE_ONLY", "1")
    monkeypatch.delenv("AICD_DRAWIO_CLI", raising=False)
    built = drawio_spec.build_drawio_xml([{"id": "a", "label": "A"}], [])
    assert built.get("ok")
    p_drawio = tmp_path / "d.drawio"
    p_drawio.write_text(str(built["xml"]), encoding="utf-8")
    p_png = tmp_path / "d.png"
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    r = export_drawio_file_to_png(p_drawio, p_png, policy_check=pol.check_allowed)
    assert r.get("ok") is False
    assert "OFFLINE_ONLY" in str(r.get("error", ""))


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

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


@pytest.mark.skipif(
    os.environ.get("AICD_NETWORK_TEST") != "1",
    reason="Set AICD_NETWORK_TEST=1 to run (hits embed.diagrams.net)",
)
@pytest.mark.skipif(not _chromium_ok(), reason="Playwright Chromium not installed")
def test_export_minimal_drawio_to_png(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.setenv("AICD_ENABLE_DRAWIO_EXPORT_PNG", "1")
    built = drawio_spec.build_drawio_xml(
        [{"id": "x", "label": "X"}, {"id": "y", "label": "Y"}],
        [{"source": "x", "target": "y"}],
    )
    assert built.get("ok")
    p_drawio = tmp_path / "d.drawio"
    p_drawio.write_text(str(built["xml"]), encoding="utf-8")
    p_png = tmp_path / "d.png"
    pol = PathPolicy(PathPolicyConfig(full_disk=True))
    r = export_drawio_file_to_png(
        p_drawio,
        p_png,
        policy_check=pol.check_allowed,
        timeout_ms=180_000,
    )
    assert r.get("ok") is True
    assert p_png.is_file()
    assert p_png.stat().st_size > 500
