from __future__ import annotations

import zipfile
from pathlib import Path

import pytest

from aicd.tools import visio_flowchart


pytestmark = pytest.mark.skipif(
    not visio_flowchart.vsdx_installed(),
    reason="vsdx not installed (pip install aicd[visio])",
)


def test_write_minimal_vsdx(tmp_path: Path) -> None:
    out = tmp_path / "flow.vsdx"
    r = visio_flowchart.write_flowchart_vsdx(
        out,
        [
            {"id": "a", "label": "开始", "shape": "terminator"},
            {"id": "b", "label": "处理"},
            {"id": "c", "label": "结束", "shape": "terminator"},
        ],
        [{"from": "a", "to": "b"}, {"source": "b", "target": "c"}],
        policy_check=None,
        layout_cols=2,
    )
    assert r.get("ok") is True
    assert out.is_file()
    with zipfile.ZipFile(out, "r") as z:
        names = z.namelist()
    assert any(n.startswith("visio/pages/") and n.endswith(".xml") for n in names)


def test_summarize_written(tmp_path: Path) -> None:
    out = tmp_path / "t2.vsdx"
    visio_flowchart.write_flowchart_vsdx(
        out,
        [{"id": "x", "label": "X"}],
        [],
        policy_check=None,
    )
    s = visio_flowchart.summarize_vsdx_page(out, policy_check=None, max_shapes=50)
    assert s.get("ok") is True
    rows = s.get("shape_rows") or []
    texts = [r.get("text") for r in rows if r.get("text")]
    assert any("X" in str(t) for t in texts)
