#!/usr/bin/env node

// Calendly MCP Server - Main Entry Point
// Supports both stdio and HTTP modes

import { createCalendlyServer, runStdioServer } from './server.js';
import { createServer } from 'http';

const API_KEY = process.env.CALENDLY_API_KEY;
const MODE = process.env.MCP_MODE || 'stdio'; // stdio or http
const PORT = parseInt(process.env.PORT || '3000', 10);

if (!API_KEY) {
  console.error('Error: CALENDLY_API_KEY environment variable is required');
  process.exit(1);
}

async function main() {
  if (MODE === 'http') {
    // HTTP mode - useful for web-based MCP apps
    const mcpServer = createCalendlyServer(API_KEY!);
    
    const httpServer = createServer(async (req, res) => {
      // CORS headers
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

      if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
      }

      if (req.method === 'GET' && req.url === '/health') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ status: 'ok', mode: 'http' }));
        return;
      }

      if (req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
          body += chunk.toString();
        });

        req.on('end', async () => {
          try {
            const request = JSON.parse(body);
            
            // Handle MCP requests
            if (request.method === 'tools/list') {
              const tools = await (mcpServer as any).requestHandlers.get('tools/list')?.();
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify(tools));
            } else if (request.method === 'tools/call') {
              const result = await (mcpServer as any).requestHandlers.get('tools/call')?.(request);
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify(result));
            } else if (request.method === 'resources/list') {
              const resources = await (mcpServer as any).requestHandlers.get('resources/list')?.();
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify(resources));
            } else if (request.method === 'resources/read') {
              const resource = await (mcpServer as any).requestHandlers.get('resources/read')?.(request);
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify(resource));
            } else {
              res.writeHead(404, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify({ error: 'Unknown method' }));
            }
          } catch (error) {
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({
              error: error instanceof Error ? error.message : 'Unknown error',
            }));
          }
        });
      } else {
        res.writeHead(404);
        res.end();
      }
    });

    httpServer.listen(PORT, () => {
      console.error(`Calendly MCP Server running on http://localhost:${PORT}`);
      console.error('Mode: HTTP');
      console.error('Endpoints:');
      console.error('  GET  /health - Health check');
      console.error('  POST /       - MCP requests');
    });
  } else {
    // Stdio mode - default for MCP
    await runStdioServer(API_KEY!);
  }
}

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