// ignore_for_file: avoid_print
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:travel_mate/firebase_options.dart';

/// Script de diagnostic pour analyser les images dans Firebase Storage
void main() async {
  try {
    // Initialiser Firebase
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );

    final storage = FirebaseStorage.instance;

    final listResult = await storage.ref('trip_images').listAll();

    if (listResult.items.isEmpty) {
      return;
    }

    final Map<String, List<Map<String, dynamic>>> locationGroups = {};

    for (int i = 0; i < listResult.items.length; i++) {
      final item = listResult.items[i];
      final fileName = item.name;

      try {
        // Récupérer les métadonnées
        final metadata = await item.getMetadata();
        final customMeta = metadata.customMetadata ?? {};

        final location = customMeta['location'] ?? 'Inconnue';
        final normalizedLocation =
            customMeta['normalizedLocation'] ?? 'Non définie';

        final uploadedAt = customMeta['uploadedAt'] ?? 'Inconnue';

        // Récupérer l'URL de téléchargement
        final downloadUrl = await item.getDownloadURL();

        // Grouper par location normalisée
        final groupKey = normalizedLocation != 'Non définie'
            ? normalizedLocation
            : location.toLowerCase();
        if (!locationGroups.containsKey(groupKey)) {
          locationGroups[groupKey] = [];
        }
        locationGroups[groupKey]!.add({
          'fileName': fileName,
          'location': location,
          'normalizedLocation': normalizedLocation,
          'uploadedAt': uploadedAt,
          'downloadUrl': downloadUrl,
        });
      } catch (e) {
        // Essayer de deviner la location depuis le nom du fichier
        final parts = fileName.split('_');
        if (parts.length >= 2) {
          final guessedLocation = parts.take(parts.length - 1).join('_');

          if (!locationGroups.containsKey(guessedLocation)) {
            locationGroups[guessedLocation] = [];
          }
          locationGroups[guessedLocation]!.add({
            'fileName': fileName,
            'location': 'Devinée: $guessedLocation',
            'normalizedLocation': 'Non définie',
            'uploadedAt': 'Inconnue',
            'downloadUrl': 'Non récupérée',
          });
        }
      }
    }

    // Analyser les doublons

    int totalDuplicates = 0;
    for (final entry in locationGroups.entries) {
      final images = entry.value;

      if (images.length > 1) {
        totalDuplicates += images.length - 1;

        for (int i = 0; i < images.length; i++) {}
      } else {}
    }

    if (totalDuplicates > 0) {}
  } catch (e) {
    print('Erreur globale: $e');
  }
}
