/**
 * Comprehensive error handling for deployment compatibility
 */

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

  /**
   * Handle image processing errors gracefully
   */
  handleImageProcessingError(error: any, fallbackMessage = "Image processing unavailable"): string {
    console.warn('Image processing error handled:', error?.message || error);
    
    if (process.env.NODE_ENV === 'production') {
      return fallbackMessage;
    }
    
    return `${fallbackMessage}: ${error?.message || 'Unknown error'}`;
  }

  /**
   * Handle transcription errors gracefully
   */
  handleTranscriptionError(error: any, fallbackMessage = "Audio transcription unavailable"): string {
    console.warn('Transcription error handled:', error?.message || error);
    
    if (process.env.NODE_ENV === 'production') {
      return fallbackMessage;
    }
    
    return `${fallbackMessage}: ${error?.message || 'Unknown error'}`;
  }

  /**
   * Handle system dependency errors
   */
  handleSystemDependencyError(dependency: string, error: any): void {
    const message = `System dependency '${dependency}' not available: ${error?.message || error}`;
    
    if (process.env.NODE_ENV === 'production') {
      console.log(`Production fallback activated for ${dependency}`);
    } else {
      console.warn(message);
    }
  }

  /**
   * Handle file system errors
   */
  handleFileSystemError(operation: string, path: string, error: any): void {
    const message = `File system error during ${operation} at ${path}: ${error?.message || error}`;
    console.error(message);
    
    if (process.env.NODE_ENV === 'production') {
      // In production, create directory if it doesn't exist
      if (error?.code === 'ENOENT') {
        try {
          const fs = require('fs');
          const pathModule = require('path');
          const dir = pathModule.dirname(path);
          fs.mkdirSync(dir, { recursive: true });
          console.log(`Created missing directory: ${dir}`);
        } catch (createError) {
          console.error(`Failed to create directory: ${createError}`);
        }
      }
    }
  }

  /**
   * Handle network/API errors
   */
  handleNetworkError(service: string, error: any): string {
    const message = `Network error with ${service}: ${error?.message || error}`;
    console.warn(message);
    
    return `${service} temporarily unavailable`;
  }

  /**
   * Global error handler for unhandled errors
   */
  setupGlobalErrorHandlers(): void {
    process.on('uncaughtException', (error) => {
      console.error('Uncaught Exception:', error);
      
      if (process.env.NODE_ENV === 'production') {
        // In production, log the error but don't crash
        console.error('Production error logged, continuing operation...');
      } else {
        // In development, crash to expose the issue
        process.exit(1);
      }
    });

    process.on('unhandledRejection', (reason, promise) => {
      console.error('Unhandled Rejection at:', promise, 'reason:', reason);
      
      if (process.env.NODE_ENV === 'production') {
        console.error('Production promise rejection logged, continuing operation...');
      }
    });
  }
}

export const errorHandler = ErrorHandler.getInstance();