#!/usr/bin/env node

/**
 * HubSpot MCP Server - Entry Point
 * Handles environment validation, dual transport, graceful shutdown, and health checks
 */

import { HubSpotServer } from './server.js';
import { z } from 'zod';

// Environment validation schema
const envSchema = z.object({
  HUBSPOT_ACCESS_TOKEN: z.string().min(1, 'HUBSPOT_ACCESS_TOKEN is required'),
  SERVER_NAME: z.string().optional().default('@mcpengine/hubspot'),
  SERVER_VERSION: z.string().optional().default('1.0.0'),
  NODE_ENV: z.enum(['development', 'production', 'test']).optional().default('production'),
});

/**
 * Validate environment variables
 */
function validateEnvironment() {
  try {
    return envSchema.parse(process.env);
  } catch (error) {
    if (error instanceof z.ZodError) {
      console.error('Environment validation failed:');
      error.errors.forEach((err) => {
        console.error(`  - ${err.path.join('.')}: ${err.message}`);
      });
      process.exit(1);
    }
    throw error;
  }
}

/**
 * Health check endpoint (for monitoring)
 */
function setupHealthCheck() {
  // Simple health check that responds to SIGUSR1
  process.on('SIGUSR1', () => {
    console.error(JSON.stringify({
      status: 'healthy',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      memory: process.memoryUsage(),
    }));
  });
}

/**
 * Setup graceful shutdown handlers
 */
function setupGracefulShutdown(server: HubSpotServer) {
  let isShuttingDown = false;

  const shutdown = async (signal: string) => {
    if (isShuttingDown) {
      return;
    }

    isShuttingDown = true;
    console.error(`Received ${signal}, shutting down gracefully...`);

    try {
      // Give pending operations time to complete
      await new Promise((resolve) => setTimeout(resolve, 1000));

      console.error('Server shut down successfully');
      process.exit(0);
    } catch (error) {
      console.error('Error during shutdown:', error);
      process.exit(1);
    }
  };

  // Handle termination signals
  process.on('SIGTERM', () => shutdown('SIGTERM'));
  process.on('SIGINT', () => shutdown('SIGINT'));

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

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

/**
 * Main entry point
 */
async function main() {
  try {
    // Validate environment
    const env = validateEnvironment();

    console.error('Starting HubSpot MCP Server...');
    console.error(`Environment: ${env.NODE_ENV}`);
    console.error(`Server: ${env.SERVER_NAME} v${env.SERVER_VERSION}`);

    // Create and configure server
    const server = new HubSpotServer({
      accessToken: env.HUBSPOT_ACCESS_TOKEN,
      serverName: env.SERVER_NAME,
      serverVersion: env.SERVER_VERSION,
    });

    // Setup health check
    setupHealthCheck();

    // Setup graceful shutdown
    setupGracefulShutdown(server);

    // Start server (uses stdio transport by default)
    console.error('Server starting with stdio transport...');
    await server.start();

    console.error('HubSpot MCP Server is running');
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

// Run the server
main();
