import { existsSync, mkdirSync, copyFileSync } from 'fs';
import path from 'path';

/**
 * Simple Image Processor - Deployment Compatible
 * 
 * Simplified image processing for Cloud Run deployment
 * Avoids native binary dependencies that cause deployment failures
 */
export class SimpleImageProcessor {
  private readonly allowedFormats = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];

  constructor() {
    // Ensure output directory exists
    const outputDir = path.join(process.cwd(), 'public', 'lendable_items');
    if (!existsSync(outputDir)) {
      mkdirSync(outputDir, { recursive: true });
    }
  }

  /**
   * Process images by copying them to the correct location
   * @param inputPath - Path to the source image
   * @param outputFilename - Desired output filename (without extension)
   * @returns Promise<string> - The processed image filename
   */
  async processImage(inputPath: string, outputFilename: string): Promise<string> {
    try {
      console.log(`Processing image: ${inputPath} -> ${outputFilename}`);
      
      if (!existsSync(inputPath)) {
        throw new Error(`Input image file not found: ${inputPath}`);
      }
      
      const originalExt = path.extname(inputPath).toLowerCase() || '.jpg';
      const finalFilename = `${outputFilename}${originalExt}`;
      const thumbnailFilename = `${outputFilename}_thumb${originalExt}`;
      
      const outputPath = path.join(process.cwd(), 'public', 'lendable_items', finalFilename);
      const thumbnailPath = path.join(process.cwd(), 'public', 'lendable_items', thumbnailFilename);

      // Copy original as main image
      copyFileSync(inputPath, outputPath);
      console.log(`Copied main image to: ${outputPath}`);
      
      // Copy original as thumbnail (simplified approach)
      copyFileSync(inputPath, thumbnailPath);
      console.log(`Copied thumbnail to: ${thumbnailPath}`);

      // Verify both files exist
      if (!existsSync(outputPath)) {
        throw new Error(`Failed to create processed image: ${outputPath}`);
      }
      if (!existsSync(thumbnailPath)) {
        throw new Error(`Failed to create thumbnail: ${thumbnailPath}`);
      }

      console.log(`Image processed successfully: ${finalFilename} and ${thumbnailFilename}`);
      return finalFilename;

    } catch (error) {
      console.error('Error processing image:', error);
      throw new Error(`Image processing failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * Get basic image information
   * @param imagePath - Path to the image file
   * @returns Promise<ImageInfo> - Basic image info
   */
  async getImageInfo(imagePath: string): Promise<{ width: number; height: number; format: string }> {
    try {
      const ext = path.extname(imagePath).toLowerCase().slice(1) || 'jpg';
      
      return {
        width: 400, // Default standard width
        height: 300, // Default height
        format: ext
      };
    } catch (error) {
      console.error('Error getting image info:', error);
      throw new Error(`Failed to get image information: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * Validate if a file is a supported image format
   * @param filename - Name of the file to check
   * @returns boolean - True if the format is supported
   */
  isValidImageFormat(filename: string): boolean {
    if (!filename) return false;
    const ext = path.extname(filename).toLowerCase().slice(1);
    return this.allowedFormats.includes(ext);
  }

  /**
   * Validate if a file is a supported image format
   * @param filePath - Path to the file to check
   * @returns Promise<boolean> - True if the format is supported
   */
  async isValidImageFile(filePath: string): Promise<boolean> {
    try {
      const ext = path.extname(filePath).toLowerCase().slice(1);
      const validFormats = ['jpeg', 'jpg', 'png', 'gif', 'webp', 'bmp'];
      return validFormats.includes(ext) || ext === '';
    } catch (error) {
      console.warn(`Could not identify image format for ${filePath}:`, error);
      return false;
    }
  }

  /**
   * Generate a unique filename for processed images
   * @param originalName - Original filename
   * @param userId - User ID for uniqueness
   * @returns string - Unique filename without extension
   */
  generateUniqueFilename(originalName: string, userId: number, index: number = 0): string {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000);
    const baseName = path.basename(originalName, path.extname(originalName))
      .replace(/[^a-zA-Z0-9]/g, '_')
      .substring(0, 20);
    
    // CRITICAL FIX: Add index and random number to prevent timestamp collisions
    return `${userId}_${timestamp}_${random}_${baseName}_${index}`;
  }

  /**
   * Process multiple images for a single item (primary + extras)
   * @param images - Array of image paths to process
   * @param userId - User ID for filename generation
   * @returns Promise<{primaryLogo: string, extraImages: string[]}> - Processed image filenames
   */
  async processItemImages(images: string[], userId: number): Promise<{ primaryLogo: string; extraImages: string[] }> {
    if (images.length === 0) {
      throw new Error('No images provided for processing');
    }

    const processedImages: string[] = [];
    
    for (let i = 0; i < images.length; i++) {
      const imagePath = images[i];
      
      if (!existsSync(imagePath)) {
        console.warn(`Image not found: ${imagePath}`);
        continue;
      }

      // For files without extensions (like mobile uploads), check basic validation
      const hasExtension = path.extname(imagePath).length > 0;
      if (hasExtension && !this.isValidImageFormat(imagePath)) {
        console.warn(`Unsupported image format: ${imagePath}`);
        continue;
      }
      
      // If no extension, check using basic validation
      if (!hasExtension) {
        const isValidImage = await this.isValidImageFile(imagePath);
        if (!isValidImage) {
          console.warn(`Unsupported image format (no extension): ${imagePath}`);
          continue;
        }
      }

      try {
        // Enhanced unique filename generation with index and random component
        const filename = this.generateUniqueFilename(path.basename(imagePath), userId, i);
        const processedFilename = await this.processImage(imagePath, filename);
        
        processedImages.push(processedFilename);
      } catch (error) {
        console.error(`Failed to process image ${imagePath}:`, error);
        // Continue with other images rather than failing completely
      }
    }

    if (processedImages.length === 0) {
      throw new Error('No images could be processed successfully');
    }

    return {
      primaryLogo: processedImages[0],
      extraImages: processedImages.slice(1)
    };
  }
}

export const simpleImageProcessor = new SimpleImageProcessor();