"""CloudSense Upgrade Compass MCP server.

Run with: python -m cloudsense_upgrade_compass.server
Or via CLI: cloudsense-upgrade-compass
"""

import asyncio
import logging

from mcp.server import Server
from mcp.server.stdio import stdio_server
import mcp.types as types

from . import __version__
from .instructions import SERVER_INSTRUCTIONS
from .tools import init_assessment, get_installed_packages

logger = logging.getLogger(__name__)

server = Server("cloudsense-upgrade-compass")

TOOLS = {
    "init_assessment": init_assessment,
    "get_installed_packages": get_installed_packages,
}


@server.list_tools()
async def list_tools() -> list[types.Tool]:
    """Return available tools."""
    return [
        types.Tool(
            name=tool_module.TOOL_DEFINITION["name"],
            description=tool_module.TOOL_DEFINITION["description"],
            inputSchema=tool_module.TOOL_DEFINITION["inputSchema"],
        )
        for tool_module in TOOLS.values()
    ]


@server.call_tool()
async def call_tool(
    name: str, arguments: dict
) -> list[types.TextContent]:
    """Handle tool calls."""
    tool_module = TOOLS.get(name)
    if tool_module is None:
        raise ValueError(f"Unknown tool: {name}")

    result = await tool_module.run(arguments)
    return [types.TextContent(type="text", text=result)]


async def _run_server():
    """Start the MCP server on stdio transport."""
    logger.info(
        "CloudSense Upgrade Compass v%s starting...", __version__
    )
    async with stdio_server() as (read_stream, write_stream):
        init_options = server.create_initialization_options()
        init_options.instructions = SERVER_INSTRUCTIONS
        await server.run(read_stream, write_stream, init_options)


def main():
    """Entry point for the CLI command."""
    logging.basicConfig(level=logging.INFO)
    asyncio.run(_run_server())


if __name__ == "__main__":
    main()
