from __future__ import annotations

from typing import Any

# External-data island tools audited as MCP inbound (direction=in).
_INBOUND_EXTERNAL_TOOLS = frozenset(
    {
        "niannian_external_data",
        "niannian_external_data_archive",
        "niannian_external_recall",
        "niannian_external_list",
        "niannian_external_learn",
        "niannian_external_audit",
        "niannian_external_trace",
    }
)

_TOOLS_CACHE: list[dict[str, Any]] | None = None


def clear_client_tools_cache() -> None:
    global _TOOLS_CACHE
    _TOOLS_CACHE = None


def _tool_direction(name: str) -> str:
    if name in _INBOUND_EXTERNAL_TOOLS:
        return "in"
    return "in"


def list_client_tools(*, refresh: bool = False) -> list[dict[str, Any]]:
    """List niannian MCP tools exposed to clients (FastMCP registry)."""
    global _TOOLS_CACHE
    if _TOOLS_CACHE is not None and not refresh:
        return list(_TOOLS_CACHE)

    from niannian.mcp.server.app import build_fastmcp
    from niannian.mcp.service import create_service

    mcp = build_fastmcp(create_service())
    tools = mcp._tool_manager.list_tools()
    out: list[dict[str, Any]] = []
    for tool in tools:
        name = str(tool.name or "").strip()
        if not name:
            continue
        out.append(
            {
                "name": name,
                "description": str(tool.description or "").strip(),
                "direction": _tool_direction(name),
            }
        )
    out.sort(key=lambda row: row["name"])
    _TOOLS_CACHE = out
    return list(out)
