"""MTurk MCP Server - Main entry point."""

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

from .client import get_mturk_client, format_error, wrap_html_question, is_sandbox

# Create server instance
server = Server("mturk")

# Import tool handlers
from .tools import hits, assignments, qualifications, workers, account

# Collect all tools from modules
ALL_TOOLS: list[Tool] = []
TOOL_HANDLERS: dict[str, callable] = {}


def register_tool(name: str, description: str, input_schema: dict, handler: callable):
    """Register a tool with its schema and handler."""
    ALL_TOOLS.append(Tool(
        name=name,
        description=description,
        inputSchema=input_schema,
    ))
    TOOL_HANDLERS[name] = handler


# Register all tools from modules
hits.register_tools(register_tool)
assignments.register_tools(register_tool)
qualifications.register_tools(register_tool)
workers.register_tools(register_tool)
account.register_tools(register_tool)


@server.list_tools()
async def handle_list_tools() -> list[Tool]:
    """Return all available MTurk tools."""
    return ALL_TOOLS


@server.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list[TextContent]:
    """Handle tool invocations."""
    if name not in TOOL_HANDLERS:
        return [TextContent(type="text", text=f"Unknown tool: {name}")]

    try:
        handler = TOOL_HANDLERS[name]
        result = await handler(arguments)
        return result
    except Exception as e:
        return [TextContent(type="text", text=format_error(e))]


async def run():
    """Run the MCP server with stdio transport."""
    print("[mturk-mcp] Starting MTurk MCP server...", file=sys.stderr)
    print(f"[mturk-mcp] Registered {len(ALL_TOOLS)} tools", file=sys.stderr)
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream, server.create_initialization_options())


def main():
    """Entry point for the MCP server."""
    asyncio.run(run())


if __name__ == "__main__":
    main()
