#!/usr/bin/env python3
"""AURORA MCP Server - FastMCP implementation.

Provides Model Context Protocol server for AURORA codebase indexing and search.
"""

import argparse
import sys
from pathlib import Path

try:
    from fastmcp import FastMCP
except ImportError:
    print("Error: FastMCP not installed. Install with: pip install fastmcp", file=sys.stderr)
    sys.exit(1)

from aurora_mcp.lsp_tool import lsp as lsp_tool
from aurora_mcp.mem_search_tool import mem_search as mem_search_tool
from aurora_mcp.tools import AuroraMCPTools


class AuroraMCPServer:
    """MCP Server for AURORA codebase tools."""

    def __init__(
        self, db_path: str | None = None, config_path: str | None = None, test_mode: bool = False
    ):
        """Initialize AURORA MCP Server.

        Args:
            db_path: Path to SQLite database (default: ~/.aurora/memory.db)
            config_path: Path to AURORA config file (default: ~/.aurora/config.json)
            test_mode: If True, skip FastMCP initialization (for testing)
        """
        self.db_path = db_path or str(Path.home() / ".aurora" / "memory.db")
        self.config_path = config_path or str(Path.home() / ".aurora" / "config.json")
        self.test_mode = test_mode

        # Initialize tools
        self.tools = AuroraMCPTools(self.db_path, self.config_path)

        # Initialize FastMCP server only if not in test mode
        if not test_mode:
            self.mcp = FastMCP("aurora")
            # Register tools
            self._register_tools()
        else:
            self.mcp = None

    def _register_tools(self) -> None:
        """Register MCP tools with the server.

        Active MCP tools:
        - lsp: Code intelligence (deadcode, impact, check)
        - mem_search: Search indexed code (fast by default, enrich=True for LSP data)

        CLI equivalents:
        - aur mem search "query" - Search indexed codebase
        - aur soar "question" - Multi-turn SOAR query
        """

        # Register LSP tool with readOnlyHint
        @self.mcp.tool(
            name="lsp",
            description=lsp_tool.__doc__ or "LSP Code Intelligence",
        )
        def lsp(action: str = "check", path: str = "", line: int | None = None) -> dict:
            """LSP Code Intelligence - dead code detection, impact analysis, pre-edit checks."""
            return lsp_tool(action=action, path=path, line=line)

        # Register mem_search tool
        @self.mcp.tool(
            name="mem_search",
            description=mem_search_tool.__doc__ or "Search indexed code",
        )
        def mem_search(
            query: str, limit: int = 5, enrich: bool = False, code_only: bool = True
        ) -> list[dict]:
            """Search indexed code (default) or include KB docs."""
            return mem_search_tool(query=query, limit=limit, enrich=enrich, code_only=code_only)

    def run(self) -> None:
        """Run the MCP server."""
        self.mcp.run()

    def list_tools(self) -> list[dict]:
        """List all available tools (for testing)."""
        if self.test_mode:
            # Return list of registered tools
            tools = [
                {
                    "name": "lsp",
                    "description": "LSP Code Intelligence",
                    "readOnlyHint": True,
                    "title": "LSP Code Intelligence",
                },
                {
                    "name": "mem_search",
                    "description": "Search indexed code (enrich=True for LSP data)",
                    "readOnlyHint": True,
                    "title": "Memory Search",
                },
            ]
            return tools
        else:
            # Runtime display
            print("AURORA MCP Server - Active MCP Tools:")
            print("=" * 50)
            print("\nMCP Tools:")
            print("  lsp - Code intelligence (deadcode, impact, check)")
            print("  mem_search - Search indexed code with LSP enrichment")
            print("\nCLI equivalents:")
            print('  aur mem search "query" - Search indexed codebase')
            print('  aur soar "question"    - Multi-turn SOAR query')
            print("  aur mem stats          - Memory statistics")
            print("\n" + "=" * 50)
            print(f"Database: {self.db_path}")
            print(f"Config: {self.config_path}")
            return []


def main() -> None:
    """Main entry point for MCP server CLI."""
    parser = argparse.ArgumentParser(
        description="AURORA MCP Server - Model Context Protocol integration",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument(
        "--db-path",
        type=str,
        help="Path to SQLite database (default: ~/.aurora/memory.db)",
    )

    parser.add_argument(
        "--config",
        type=str,
        help="Path to AURORA config file (default: ~/.aurora/config.json)",
    )

    parser.add_argument(
        "--test",
        action="store_true",
        help="Test mode: start server and list available tools",
    )

    args = parser.parse_args()

    # Create server instance
    server = AuroraMCPServer(db_path=args.db_path, config_path=args.config, test_mode=args.test)

    if args.test:
        print("AURORA MCP Server - Test Mode")
        print("=" * 50)
        server.list_tools()
        print("\nTest mode complete. Server initialized successfully!")
        sys.exit(0)

    # Run server
    print("Starting AURORA MCP Server...")
    print(f"Database: {server.db_path}")
    print(f"Config: {server.config_path}")
    server.run()


if __name__ == "__main__":
    main()
