"""PFC Command Query Tool - Keyword search for command documentation."""

from typing import Any

from fastmcp import FastMCP
from pydantic import Field

from pfc_mcp.contracts import build_docs_data, build_ok
from pfc_mcp.knowledge.commands import CommandLoader
from pfc_mcp.knowledge.query import CommandSearch
from pfc_mcp.utils import CommandDocVersion, SearchLimit, SearchQuery, normalize_command_doc_version


def register(mcp: FastMCP) -> None:
    """Register pfc_query_command tool with the MCP server."""

    @mcp.tool()
    def pfc_query_command(
        query: SearchQuery,
        limit: SearchLimit = 10,
        version: CommandDocVersion = Field(
            CommandDocVersion.V7_0,
            description="PFC documentation version to search. Defaults to 7.0.",
        ),
    ) -> dict[str, Any]:
        """Search PFC command documentation by keywords (like grep).

        Returns matching command paths. Use pfc_browse_commands for full documentation.

        When to use:
        - You have keywords but don't know exact command path
        - Example: "ball create", "contact property", "model solve"

        Related tools:
        - pfc_browse_commands: Get full documentation for a known command path
        - pfc_browse_reference: Browse reference docs (e.g., "contact-models linear")
        - pfc_query_python_api: Search Python SDK by keywords
        """
        version_value = normalize_command_doc_version(version)
        results = CommandSearch.search_commands_only(query, top_k=limit, version=version_value)
        matches: list[dict[str, Any]] = []
        for result in results:
            metadata = result.document.metadata or {}
            matches.append(
                {
                    "path": result.document.title,
                    "name": result.document.name,
                    "category": result.document.category,
                    "syntax": result.document.syntax,
                    "short_description": metadata.get("short_description"),
                    "score": round(result.score, 2),
                    "rank": result.rank,
                    "version": metadata.get("version", version_value),
                }
            )

        payload: dict[str, Any] = build_docs_data(
            source="commands",
            action="query",
            entries=matches,
            summary={
                "count": len(matches),
                "version": version_value,
            },
        )

        if not matches:
            categories = sorted(CommandLoader.load_index().get("categories", {}).keys())
            payload["summary"]["hints"] = [
                "Try broader keywords (for example: create, property, solve).",
                "Try category + action (for example: ball create, contact property).",
            ]
            payload["summary"]["available_categories"] = categories

        return build_ok(payload)
