/**
 * C-001: MCP Server Framework
 * 
 * Bootstrap the MCP server with SSE transport using @modelcontextprotocol/sdk.
 * Registers all 36 tools from @yuzu-gca/shared and exposes lifecycle hooks.
 */

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { ALL_TOOL_DEFS, type ToolDef, type DeviceConfig } from "@yuzu-gca/shared";

export interface ServerOptions {
  config: DeviceConfig;
  toolHandlers: Map<string, (args: any) => Promise<any>>;
}

/**
 * Creates and returns an MCP Server instance with all tools registered.
 * Call `server.connect(transport)` to start handling requests.
 */
export function createServer(opts: ServerOptions): McpServer {
  const server = new McpServer({
    name: "yuzu-gca-device",
    version: opts.config.identity.id,
  });

  // Register every tool from the shared type definitions
  for (const toolDef of ALL_TOOL_DEFS) {
    const handler = opts.toolHandlers.get(toolDef.name);
    if (handler) {
      server.tool(
        toolDef.name,
        toolDef.description,
        toolDef.inputSchema.properties,
        async (args: any) => {
          const result = await handler(args);
          return {
            content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
          };
        },
      );
    } else {
      // Register placeholder for unimplemented tools
      server.tool(
        toolDef.name,
        toolDef.description,
        { ...toolDef.inputSchema.properties, _required: toolDef.inputSchema.required },
        async (args: any) => {
          content: [{ type: "text", text: JSON.stringify({ error: "Tool not yet implemented", tool: toolDef.name }) }],
        }),
      );
    }
  }

  return server;
}

/**
 * Start the server with SSE transport on a given port.
 */
export async function startServer(
  server: McpServer,
  port: number = 3001,
): Promise<void> {
  const transport = new SSEServerTransport({
    port,
    endpoint: "/sse",
  });

  await server.connect(transport);
  console.log(`[Yuzu-GCA] MCP Server listening on :${port}/sse`);
}

/**
 * Convenience — create + start in one call.
 */
export async function bootstrap(
  opts: ServerOptions,
  port?: number,
): Promise<McpServer> {
  const server = createServer(opts);
  await startServer(server, port);
  return server;
}
