import { SSEMCPServer } from './sse-mcp-server';
import { AuthHandler } from './auth-handler';
import { MCPHandler } from './mcp-handler';
import { tools } from './tools';

async function main() {
  try {
    // Create auth handler
    const authHandler = new AuthHandler({
      apiKey: process.env.TRACKEX_API_KEY || '',
      sessionTimeout: 3600000, // 1 hour
      maxAuthAttempts: 3
    });

    // Create MCP handler
    const mcpHandler = new MCPHandler({
      tools,
      authHandler
    });

    // Create and start SSE server
    const server = new SSEMCPServer();
    await server.start(parseInt(process.env.PORT || '3334'));

    // Handle graceful shutdown
    const gracefulShutdown = async (signal: string) => {
      console.log(`\n[SSE MCP Server] Received ${signal}, shutting down gracefully...`);
      await server.stop();
      process.exit(0);
    };

    process.on('SIGINT', () => gracefulShutdown('SIGINT'));
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));

    // Handle uncaught exceptions
    process.on('uncaughtException', (error) => {
      console.error('[SSE MCP Server] Uncaught exception:', error);
      gracefulShutdown('UNCAUGHT_EXCEPTION');
    });

    process.on('unhandledRejection', (reason, promise) => {
      console.error('[SSE MCP Server] Unhandled rejection at:', promise, 'reason:', reason);
      gracefulShutdown('UNHANDLED_REJECTION');
    });

  } catch (error) {
    console.error('[SSE MCP Server] Failed to start:', error);
    process.exit(1);
  }
}

main(); 