#!/usr/bin/env node
// SSE transport support for MCP is not yet available in the SDK
// This file demonstrates how to set up an HTTP server for future SSE support

import { createServer } from 'http';
import { AtlasServer } from './server.js';

const PORT = process.env.MCP_PORT || 3000;

async function startSSEServer() {
  console.error(`Starting Atlas server on port ${PORT}...`);

  // Create HTTP server
  const httpServer = createServer(async (req, res) => {
    // Enable CORS
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

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

    if (req.url === '/sse' && req.method === 'GET') {
      console.error('New SSE connection established');
      
      // Create a new MCP server instance for this connection
      const mcpServer = new AtlasServer();
      
      // SSE transport is not yet available in MCP SDK
      // For now, this serves as a demonstration
      // When available, use:
      // const transport = new SSEServerTransport(req, res);
      // await mcpServer.connectTransport(transport);
      
      res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
      });
      
      res.write('data: ' + JSON.stringify({
        error: 'SSE transport not yet implemented in MCP SDK',
        message: 'Please use STDIO connection for now',
        info: 'Check back for updates as MCP SDK adds more transport options'
      }) + '\n\n');
      
      req.on('close', () => {
        console.error('SSE connection closed');
      });
      
      req.on('error', (error) => {
        console.error('SSE error:', error);
      });
    } else {
      // Serve a simple info page
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(`
        <html>
          <head><title>Atlas MCP Server</title></head>
          <body>
            <h1>Atlas MCP Server</h1>
            <p>Server is running on port ${PORT}</p>
            <p>SSE endpoint: <code>http://localhost:${PORT}/sse</code></p>
            <h2>Available Tools:</h2>
            <ul>
              <li>Project Management</li>
              <li>Code Analysis</li>
              <li>Testing Framework</li>
              <li>Deployment Management</li>
              <li>Git Workflow</li>
              <li>Task Orchestration</li>
            </ul>
          </body>
        </html>
      `);
    }
  });

  // Start HTTP server
  httpServer.listen(PORT, () => {
    console.error(`MCP server listening on http://localhost:${PORT}`);
    console.error('SSE endpoint: http://localhost:' + PORT + '/sse');
  });

  // Handle server errors
  httpServer.on('error', (error) => {
    console.error('Server error:', error);
    process.exit(1);
  });

  // Graceful shutdown
  process.on('SIGINT', () => {
    console.error('\nShutting down server...');
    httpServer.close(() => {
      console.error('Server shut down');
      process.exit(0);
    });
  });
}

// Start the server
startSSEServer().catch((error) => {
  console.error('Failed to start server:', error);
  process.exit(1);
});