"""MCP Server tools for code analysis.

This module provides MCP tools that can be used by Claude Agent to analyze
project code structure, function signatures, class hierarchies, and call graphs.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from claude_agent_sdk import create_sdk_mcp_server, tool

from .ast_tools import MultiLanguageAnalyzer


def create_analysis_tools(project_root: Path):
    """Create code analysis MCP tools for the given project.

    Args:
        project_root: Root path of the project to analyze

    Returns:
        MCP server instance with analysis tools
    """
    analyzer = MultiLanguageAnalyzer(project_root)

    @tool("list_modules", "List all modules in the project with their basic info", {})
    async def list_modules(args: dict[str, Any]) -> dict[str, Any]:
        """List all modules in the project."""
        modules = analyzer.list_modules()
        return {
            "content": [
                {
                    "type": "text",
                    "text": json.dumps(modules, indent=2, ensure_ascii=False),
                }
            ]
        }

    @tool(
        "get_module_info",
        "Get detailed information about a module including files, functions, and classes",
        {"module_path": str},
    )
    async def get_module_info(args: dict[str, Any]) -> dict[str, Any]:
        """Get detailed info about a specific module."""
        module_path = args.get("module_path", "")
        result = analyzer.get_module_info(module_path)

        # Truncate large results
        text = json.dumps(result, indent=2, ensure_ascii=False, default=str)
        if len(text) > 50000:
            text = text[:50000] + "\n... (truncated)"

        return {"content": [{"type": "text", "text": text}]}

    @tool(
        "get_function_signature",
        "Get the signature of a specific function with parameters, return type, and location",
        {"file_path": str, "function_name": str},
    )
    async def get_function_signature(args: dict[str, Any]) -> dict[str, Any]:
        """Get function signature details."""
        file_path = args.get("file_path", "")
        function_name = args.get("function_name", "")

        result = analyzer.get_function_signature(file_path, function_name)

        if result is None:
            return {
                "content": [
                    {
                        "type": "text",
                        "text": f"Function '{function_name}' not found in {file_path}",
                    }
                ],
                "is_error": True,
            }

        return {
            "content": [
                {
                    "type": "text",
                    "text": json.dumps(result, indent=2, ensure_ascii=False, default=str),
                }
            ]
        }

    @tool(
        "get_class_hierarchy",
        "Get class inheritance hierarchy with base classes, methods, and location",
        {"class_name": str, "file_path": str},
    )
    async def get_class_hierarchy(args: dict[str, Any]) -> dict[str, Any]:
        """Get class hierarchy and details."""
        class_name = args.get("class_name", "")
        file_path = args.get("file_path")  # Optional, can be None

        result = analyzer.get_class_hierarchy(class_name, file_path)

        if result is None:
            message = f"Class '{class_name}' not found"
            if file_path:
                message += f" in {file_path}"
            return {"content": [{"type": "text", "text": message}], "is_error": True}

        return {
            "content": [
                {
                    "type": "text",
                    "text": json.dumps(result, indent=2, ensure_ascii=False, default=str),
                }
            ]
        }

    @tool(
        "get_imports",
        "Get imports for a module, categorized as internal (project) "
        "or external (stdlib/third-party)",
        {"module_path": str},
    )
    async def get_imports(args: dict[str, Any]) -> dict[str, Any]:
        """Get module imports."""
        module_path = args.get("module_path", "")
        result = analyzer.get_imports(module_path)

        return {
            "content": [
                {
                    "type": "text",
                    "text": json.dumps(result, indent=2, ensure_ascii=False, default=str),
                }
            ]
        }

    @tool(
        "get_function_calls",
        "Get all functions called by a specific function (outgoing calls)",
        {"file_path": str, "function_name": str},
    )
    async def get_function_calls(args: dict[str, Any]) -> dict[str, Any]:
        """Get functions called by a function."""
        file_path = args.get("file_path", "")
        function_name = args.get("function_name", "")

        result = analyzer.get_function_calls(file_path, function_name)

        return {
            "content": [
                {
                    "type": "text",
                    "text": json.dumps(result, indent=2, ensure_ascii=False, default=str),
                }
            ]
        }

    @tool(
        "get_callers",
        "Find all places in the project that call a specific function (incoming calls)",
        {"function_name": str},
    )
    async def get_callers(args: dict[str, Any]) -> dict[str, Any]:
        """Find all callers of a function."""
        function_name = args.get("function_name", "")
        result = analyzer.get_callers(function_name)

        return {
            "content": [
                {
                    "type": "text",
                    "text": json.dumps(result, indent=2, ensure_ascii=False, default=str),
                }
            ]
        }

    # Create and return the MCP server
    return create_sdk_mcp_server(
        name="nanowiki-analyzer",
        version="1.0.0",
        tools=[
            list_modules,
            get_module_info,
            get_function_signature,
            get_class_hierarchy,
            get_imports,
            get_function_calls,
            get_callers,
        ],
    )


# Tool names for reference (used in allowedTools)
TOOL_NAMES = [
    "mcp__nanowiki-analyzer__list_modules",
    "mcp__nanowiki-analyzer__get_module_info",
    "mcp__nanowiki-analyzer__get_function_signature",
    "mcp__nanowiki-analyzer__get_class_hierarchy",
    "mcp__nanowiki-analyzer__get_imports",
    "mcp__nanowiki-analyzer__get_function_calls",
    "mcp__nanowiki-analyzer__get_callers",
]
