// lib/services/zipping_service.dart

import 'dart:io';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:archive/archive_io.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;

class ZippingService {
  /// Creates multiple JSON files from a map of data and zips them into a single archive.
  Future<File?> createDataZip({
    required Map<String, String> jsonDataMap,
    required String baseFileName,
    Directory? destinationDir,
  }) async {
    try {
      final targetDir = destinationDir ?? await getTemporaryDirectory();
      if (!await targetDir.exists()) {
        await targetDir.create(recursive: true);
      }
      final zipFilePath = p.join(targetDir.path, '$baseFileName.zip');
      final encoder = ZipFileEncoder();
      encoder.create(zipFilePath);

      debugPrint("Creating data ZIP at: $zipFilePath");

      for (var entry in jsonDataMap.entries) {
        final fileName = entry.key;
        final jsonContent = entry.value;
        final utf8Bytes = utf8.encode(jsonContent);
        final archiveFile = ArchiveFile(fileName, utf8Bytes.length, utf8Bytes);
        encoder.addArchiveFile(archiveFile);
        debugPrint("Added $fileName to data ZIP.");
      }

      encoder.close();
      debugPrint("Data ZIP creation complete.");
      return File(zipFilePath);
    } catch (e) {
      debugPrint("Error creating data ZIP file: $e");
      return null;
    }
  }

  /// [ORIGINAL FUNCTION RESTORED]
  /// Creates a ZIP file from a list of image files.
  /// Used by Marine, Air, etc. that do not need renaming.
  Future<File?> createImageZip({
    required List<File> imageFiles,
    required String baseFileName,
    Directory? destinationDir,
  }) async {
    if (imageFiles.isEmpty) {
      debugPrint("No images provided to create an image ZIP.");
      return null;
    }

    try {
      final targetDir = destinationDir ?? await getTemporaryDirectory();
      if (!await targetDir.exists()) {
        await targetDir.create(recursive: true);
      }
      final zipFilePath = p.join(targetDir.path, '${baseFileName}_img.zip');
      final encoder = ZipFileEncoder();
      encoder.create(zipFilePath);

      debugPrint("Creating image ZIP at: $zipFilePath");

      for (var imageFile in imageFiles) {
        if (await imageFile.exists()) {
          await encoder.addFile(imageFile);
          debugPrint("Added ${p.basename(imageFile.path)} to image ZIP.");
        } else {
          debugPrint("Skipping non-existent file: ${imageFile.path}");
        }
      }

      encoder.close();
      debugPrint("Image ZIP creation complete.");
      return File(zipFilePath);
    } catch (e) {
      debugPrint("Error creating image ZIP file: $e");
      return null;
    }
  }

  /// [NEW FUNCTION FOR RIVER]
  /// Creates a ZIP file from a Map of image files to allow specific renaming inside the ZIP.
  /// Key: The filename to be used INSIDE the zip (e.g., 'background_20231213.jpg')
  /// Value: The actual File object on the device.
  Future<File?> createRenamedImageZip({
    required Map<String, File> imageFiles,
    required String baseFileName,
    Directory? destinationDir,
  }) async {
    if (imageFiles.isEmpty) {
      debugPrint("No images provided to create an image ZIP.");
      return null;
    }

    try {
      final targetDir = destinationDir ?? await getTemporaryDirectory();
      if (!await targetDir.exists()) {
        await targetDir.create(recursive: true);
      }
      final zipFilePath = p.join(targetDir.path, '${baseFileName}_img.zip');
      final encoder = ZipFileEncoder();
      encoder.create(zipFilePath);

      debugPrint("Creating renamed image ZIP at: $zipFilePath");

      for (var entry in imageFiles.entries) {
        final String targetName = entry.key;
        final File sourceFile = entry.value;

        if (await sourceFile.exists()) {
          final bytes = await sourceFile.readAsBytes();
          final archiveFile = ArchiveFile(targetName, bytes.length, bytes);
          encoder.addArchiveFile(archiveFile);
          debugPrint("Added ${p.basename(sourceFile.path)} as $targetName");
        } else {
          debugPrint("Skipping non-existent file: ${sourceFile.path}");
        }
      }

      encoder.close();
      debugPrint("Renamed Image ZIP creation complete.");
      return File(zipFilePath);
    } catch (e) {
      debugPrint("Error creating renamed image ZIP file: $e");
      return null;
    }
  }
}