import { validateAPIKeys, getConfigSummary, isAIConfigured } from '../config/ai.config';

/**
 * Validates all required configurations on application startup
 * Exits the process if critical configurations are missing
 */
export async function validateStartup(): Promise<void> {
  console.log('🚀 Starting application configuration validation...');
  
  try {
    // Validate AI configuration
    console.log('🔐 Validating AI API keys...');
    validateAPIKeys();
    console.log('✅ AI API keys validated successfully');
    
    // Check if AI is properly configured
    if (!isAIConfigured()) {
      throw new Error('AI services are not properly configured');
    }
    
    // Log configuration summary (without sensitive data)
    const configSummary = getConfigSummary();
    console.log('📊 AI Configuration Summary:');
    console.log(JSON.stringify(configSummary, null, 2));
    
    // Validate database connection (if needed)
    await validateDatabaseConnection();
    
    // Validate Redis connection (if needed)
    await validateRedisConnection();
    
    console.log('✅ All startup validations passed successfully');
  } catch (error) {
    console.error('❌ Startup validation failed:', error);
    console.error('Please check your environment configuration and try again.');
    process.exit(1);
  }
}

/**
 * Validates database connection
 */
async function validateDatabaseConnection(): Promise<void> {
  // This will be implemented when we set up TypeORM connection
  // For now, just log that we're skipping it
  console.log('⏭️  Database validation skipped (not yet configured)');
}

/**
 * Validates Redis connection
 */
async function validateRedisConnection(): Promise<void> {
  // This will be implemented when we set up Redis
  // For now, just log that we're skipping it
  console.log('⏭️  Redis validation skipped (not yet configured)');
}

/**
 * Graceful shutdown handler
 */
export function setupGracefulShutdown(): void {
  process.on('SIGINT', async () => {
    console.log('\n📴 Received SIGINT, shutting down gracefully...');
    await shutdown();
  });
  
  process.on('SIGTERM', async () => {
    console.log('\n📴 Received SIGTERM, shutting down gracefully...');
    await shutdown();
  });
}

/**
 * Performs graceful shutdown
 */
async function shutdown(): Promise<void> {
  try {
    // Close database connections
    // Close Redis connections
    // Complete any pending operations
    
    console.log('✅ Graceful shutdown completed');
    process.exit(0);
  } catch (error) {
    console.error('❌ Error during shutdown:', error);
    process.exit(1);
  }
}