"""
DcisionAI MCP Server

Main entry point for the MCP server. This server exposes DcisionAI's
optimization capabilities via the Model Context Protocol.
"""

import asyncio
import sys
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, Resource

from .tools.optimization import get_tools as get_optimization_tools
from .tools.optimization import (
    dcisionai_solve,
    dcisionai_solve_with_model,
)
from .resources.models import get_model_resources, read_model_resource
from .resources.solvers import get_solver_resources, read_solver_resource
from .config import MCPConfig


# Create MCP server instance with domain-aware name
from .config import MCPConfig
_domain_filter = MCPConfig.get_domain_filter()
if _domain_filter != "all":
    server_name = f"dcisionai-optimization-{_domain_filter}"
else:
    server_name = "dcisionai-optimization"

server = Server(server_name)


@server.list_tools()
async def handle_list_tools() -> list[Tool]:
    """List all available tools"""
    tools = []
    tools.extend(get_optimization_tools())
    return tools


@server.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list:
    """Handle tool calls"""
    if name == "dcisionai_solve":
        return await dcisionai_solve(arguments.get("problem_description", ""))
    elif name == "dcisionai_solve_with_model":
        return await dcisionai_solve_with_model(
            arguments.get("model_id", ""),
            arguments.get("data", {})
        )
    else:
        raise ValueError(f"Unknown tool: {name}")


@server.list_resources()
async def handle_list_resources() -> list[Resource]:
    """List all available resources"""
    resources = []
    resources.extend(get_model_resources())
    resources.extend(get_solver_resources())
    return resources


@server.read_resource()
async def handle_read_resource(uri: str) -> str:
    """Handle resource reads"""
    if uri.startswith("dcisionai://models/"):
        return await read_model_resource(uri)
    elif uri.startswith("dcisionai://solvers/"):
        return await read_solver_resource(uri)
    else:
        raise ValueError(f"Unknown resource URI: {uri}")


async def main():
    """Main entry point"""
    # Run server with stdio transport
    async with stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            server.create_initialization_options()
        )


if __name__ == "__main__":
    asyncio.run(main())

