#!/usr/bin/env node

import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { createServer } from './server.js';

// ---------- Configuration ----------

const config = {
  apiUrl: process.env.CML_API_URL || 'http://localhost:4002',
  mediaApiUrl: process.env.CML_MEDIA_API_URL || 'http://localhost:4100',
  serviceEmail: process.env.CML_SERVICE_EMAIL || '',
  servicePassword: process.env.CML_SERVICE_PASSWORD || '',
};

if (!config.serviceEmail || !config.servicePassword) {
  console.error(
    '[MCP] Error: CML_SERVICE_EMAIL and CML_SERVICE_PASSWORD must be set.\n' +
      'These credentials are for the MCP service account that authenticates with the Changemaker API.\n' +
      'Example:\n' +
      '  CML_SERVICE_EMAIL=mcp-agent@cmlite.org CML_SERVICE_PASSWORD=YourSecure12Pass tsx src/index.ts'
  );
  process.exit(1);
}

// ---------- Transport Selection ----------

const args = process.argv.slice(2);
const transportArg = args.indexOf('--transport');
const transportType = transportArg !== -1 ? args[transportArg + 1] : 'stdio';

async function main() {
  const server = await createServer(config);

  if (transportType === 'http') {
    // Streamable HTTP transport (for remote Claude Desktop)
    const portArg = args.indexOf('--port');
    const port = portArg !== -1 ? parseInt(args[portArg + 1], 10) : 4200;

    // Dynamic import to avoid loading HTTP deps when using stdio
    const { StreamableHTTPServerTransport } = await import(
      '@modelcontextprotocol/sdk/server/streamableHttp.js'
    );
    const http = await import('node:http');

    const httpTransport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
    await server.connect(httpTransport);

    const httpServer = http.createServer(async (req, res) => {
      // Health check endpoint
      if (req.url === '/health') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ status: 'ok', transport: 'http' }));
        return;
      }

      // MCP endpoint
      if (req.url === '/mcp') {
        await httpTransport.handleRequest(req, res);
        return;
      }

      res.writeHead(404);
      res.end('Not found');
    });

    httpServer.listen(port, () => {
      console.error(`[MCP] HTTP transport listening on port ${port}`);
      console.error(`[MCP] MCP endpoint: http://localhost:${port}/mcp`);
      console.error(`[MCP] Health check: http://localhost:${port}/health`);
    });
  } else {
    // stdio transport (default — for Claude Code)
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.error('[MCP] Connected via stdio transport');
  }
}

main().catch((err) => {
  console.error('[MCP] Fatal error:', err);
  process.exit(1);
});
