#!/usr/bin/env node

/**
 * Intercom MCP Server Main Entry Point
 * Supports dual transport (stdio/SSE) with graceful shutdown
 */

import { IntercomMCPServer } from './server.js';

async function main() {
  const accessToken = process.env.INTERCOM_ACCESS_TOKEN;

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

  const server = new IntercomMCPServer(accessToken);

  // Graceful shutdown handlers
  const shutdown = async (signal: string) => {
    console.error(`\nReceived ${signal}, shutting down gracefully...`);
    process.exit(0);
  };

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

  // Handle uncaught errors
  process.on('uncaughtException', (error) => {
    console.error('Uncaught exception:', error);
    process.exit(1);
  });

  process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled rejection at:', promise, 'reason:', reason);
    process.exit(1);
  });

  // Start the server
  try {
    await server.run();
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

main();
