"""CloudSense Customer Compass MCP server.

Run with: python -m cloudsense_customer_compass.server
Or via CLI: cloudsense-customer-compass
"""

import asyncio
import logging
import sys

from anyio import BrokenResourceError, ClosedResourceError
from mcp.server import Server
from mcp.server.stdio import stdio_server
import mcp.types as types

from . import __version__
from .tools import connect_lma, find_customer

logger = logging.getLogger(__name__)

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

TOOLS = {
    "connect_lma": connect_lma,
    "find_customer": find_customer,
}

SERVER_INSTRUCTIONS = (
    "You are connected to the CloudSense Customer Compass MCP server.\n\n"
    "SAFETY: This server is STRICTLY READ-ONLY against customer Salesforce orgs. "
    "NEVER deploy, push, insert, update, delete, or modify anything in the org.\n\n"
    "WORKFLOW:\n"
    "1. connect_lma -- Connect to the License Management Portal (FIRST step)\n"
    "2. find_customer -- Search for a customer by name, confirm selection\n"
    "3. (more tools coming soon)\n\n"
    "ORG RESOLUTION: If the user mentions an org, pass it as org_alias. "
    "If not, omit — the tool uses defaults or state.\n"
)


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


@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
    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)]


def _is_disconnect(exc: BaseException) -> bool:
    if isinstance(exc, (BrokenResourceError, ClosedResourceError)):
        return True
    if isinstance(exc, BaseExceptionGroup):
        return all(_is_disconnect(e) for e in exc.exceptions)
    return False


async def _run_server():
    logger.info("CloudSense Customer Compass v%s starting...", __version__)
    try:
        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)
    except BaseExceptionGroup as eg:
        if _is_disconnect(eg):
            logger.info("Client disconnected — shutting down.")
        else:
            raise
    except (BrokenResourceError, ClosedResourceError):
        logger.info("Client disconnected — shutting down.")


def main():
    logging.basicConfig(level=logging.INFO)
    try:
        asyncio.run(_run_server())
    except KeyboardInterrupt:
        pass
    except (BrokenPipeError, EOFError):
        logger.info("Pipe closed — exiting.")
    sys.exit(0)


if __name__ == "__main__":
    main()
