/**
 * Deployment compatibility checks and error handling
 * Handles missing system dependencies gracefully
 */

export class DeploymentChecker {
  private static instance: DeploymentChecker;
  
  static getInstance(): DeploymentChecker {
    if (!DeploymentChecker.instance) {
      DeploymentChecker.instance = new DeploymentChecker();
    }
    return DeploymentChecker.instance;
  }

  /**
   * Check if we're running in a production environment
   */
  isProduction(): boolean {
    return process.env.NODE_ENV === 'production';
  }

  /**
   * Check if we're running in Cloud Run
   */
  isCloudRun(): boolean {
    return !!(process.env.K_SERVICE || process.env.GOOGLE_CLOUD_PROJECT);
  }

  /**
   * Get the appropriate port for the environment
   */
  getPort(): number {
    // Cloud Run provides PORT environment variable
    if (this.isCloudRun() && process.env.PORT) {
      return parseInt(process.env.PORT, 10);
    }
    
    // Default to 5000 for other environments
    return parseInt(process.env.PORT || '5000', 10);
  }

  /**
   * Check system dependencies and log warnings for missing ones
   */
  async checkSystemDependencies(): Promise<void> {
    const dependencies = [
      { name: 'ImageMagick', command: 'convert --version' },
      { name: 'FFmpeg', command: 'ffmpeg -version' },
      { name: 'Python', command: 'python3 --version' }
    ];

    for (const dep of dependencies) {
      try {
        const { exec } = await import('child_process');
        const { promisify } = await import('util');
        const execAsync = promisify(exec);
        
        await execAsync(dep.command);
        console.log(`✓ ${dep.name} is available`);
      } catch (error) {
        console.warn(`⚠ ${dep.name} is not available - some features may be limited`);
        if (this.isProduction()) {
          console.log(`Production mode: Using fallback implementation for ${dep.name}`);
        }
      }
    }
  }

  /**
   * Initialize deployment-specific configurations
   */
  async initialize(): Promise<void> {
    console.log('Initializing deployment compatibility checks...');
    
    if (this.isCloudRun()) {
      console.log('Detected Cloud Run environment - using production optimizations');
    }
    
    if (this.isProduction()) {
      console.log('Production mode - system dependency checks disabled for stability');
    } else {
      await this.checkSystemDependencies();
    }
    
    const port = this.getPort();
    console.log(`Using port: ${port}`);
  }

  /**
   * Handle graceful degradation when system dependencies are missing
   */
  handleMissingDependency(dependency: string, fallbackMessage: string): string {
    if (this.isProduction()) {
      console.log(`Production fallback for ${dependency}: ${fallbackMessage}`);
    } else {
      console.warn(`Development warning: ${dependency} not available, using fallback`);
    }
    return fallbackMessage;
  }
}

export const deploymentChecker = DeploymentChecker.getInstance();