from __future__ import annotations

from typing import TYPE_CHECKING, Any

from aicd.agent.tool_args_coerce import coerce_tool_json_array
from aicd.tools import visio_flowchart

if TYPE_CHECKING:
    from aicd.agent.tool_router import ToolRouter


def _visio_flowchart_write(router: "ToolRouter", args: dict[str, Any]) -> dict[str, Any]:
    out = router._resolve_path(str(args["path"]))
    if out.suffix.lower() != ".vsdx":
        return {"ok": False, "error": "path must end with .vsdx"}
    nodes_co = coerce_tool_json_array(args.get("nodes"), "nodes", allow_empty=False)
    if isinstance(nodes_co, dict):
        return nodes_co
    edges_co = coerce_tool_json_array(args.get("edges"), "edges", allow_empty=True)
    if isinstance(edges_co, dict):
        return edges_co
    return visio_flowchart.write_flowchart_vsdx(
        out,
        nodes_co,
        edges_co,
        policy_check=router._policy.check_allowed,
        layout_cols=int(args.get("layout_cols", 4)),
    )


def _visio_vsdx_summarize(router: "ToolRouter", args: dict[str, Any]) -> dict[str, Any]:
    p = router._resolve_path(str(args["path"]))
    return visio_flowchart.summarize_vsdx_page(
        p,
        policy_check=router._policy.check_allowed,
        max_shapes=int(args.get("max_shapes", 400)),
    )


HANDLERS: dict[str, Any] = {
    "visio_flowchart_write": _visio_flowchart_write,
    "visio_vsdx_summarize": _visio_vsdx_summarize,
}
