import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:image/image.dart' as img;
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import '../utils/logger.dart';

class ImageProcessingService {
  /// Processes an image for OCR/AI extraction:
  /// 1. Compresses the original image to reduce memory usage
  /// 2. Converts to grayscale
  /// 3. Increases contrast
  /// 4. Saves as high-quality JPEG
  static Future<File?> processInvoiceImage(File originalImage) async {
    // The web app uploads the original file and OCR works 100%.
    // Processing/compressing it here strips EXIF/quality and causes OCR to fail.
    // So we just return the original image intact.
    AppLogger.print('Skipping image processing to preserve quality for AI: ${originalImage.path}');
    return originalImage;
  }

  /// Runs in an isolate to prevent UI freezing
  static List<int>? _applyFilters(List<int> bytes) {
    try {
      img.Image? decodedImage = img.decodeImage(Uint8List.fromList(bytes));
      if (decodedImage == null) return null;

      // Do not apply grayscale or contrast filters as they destroy the image quality 
      // for OpenAI Vision models. Only encode back to JPG.
      return img.encodeJpg(decodedImage, quality: 90);
    } catch (e) {
      return null;
    }
  }
}
