"""Bot-logic MCP tools.

Returns the parsed action surface (ordered nodes with command/name/line), never
the raw bot JSON blob — that stays out of tool context per the diagnosis
contract (IMPLEMENTATION_HANDOFF.md §Phase 6). The raw JSON is the input to
diagnosis, not something to dump into the LLM context.
"""

from __future__ import annotations

from pydantic import BaseModel, Field

from ..auth.auth_manager import AuthManager
from ..services import bot as bot_service
from ..utils.config import ServerConfig
from ..utils.registry import register_tool


class GetBotActionsParams(BaseModel):
    file_id: str = Field(description="Bot file id (fileId) to read actions from.")
    limit: int = Field(default=200, ge=1, le=2000, description="Max action nodes to return.")


@register_tool(
    "get_bot_actions",
    params=GetBotActionsParams,
    description="List a bot's action nodes (parsed), not the raw JSON.",
)
def get_bot_actions(
    config: ServerConfig, auth_manager: AuthManager, params: GetBotActionsParams
) -> dict:
    bot_json = bot_service.fetch_bot_content(auth_manager, params.file_id)
    nodes = bot_service.walk_actions(bot_json)
    has_handler = bot_service.has_error_handler(nodes)
    surface = [
        {
            "order": n.order,
            "path": list(n.path),
            "command": n.command,
            "name": n.name,
            "line_number": n.line_number,
            "kind": n.kind,
            "depth": n.depth,
        }
        for n in nodes[: params.limit]
    ]
    return {
        "file_id": params.file_id,
        "action_count": len(nodes),
        "returned_count": len(surface),
        "has_error_handler": has_handler,
        "actions": surface,
    }
