package com.example.util import android.content.Context import android.net.Uri import com.example.data.model.FoodUnit import com.example.data.model.MealEntry import com.example.data.model.MealFoodItem import com.example.data.model.MealType import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.BufferedReader import java.io.InputStream import java.io.InputStreamReader import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale import java.util.UUID data class CsvImportResult( val importedMeals: List, val skippedDuplicatesCount: Int, val newFoodItems: List ) object CsvImporter { private val supportedDatePatterns = listOf( "dd/MM/yyyy", "yyyy-MM-dd", "dd-MM-yyyy", "d/M/yyyy" ) private val supportedTimePatterns = listOf( "HH:mm", "H:mm", "HH:mm:ss", "H:mm:ss" ) suspend fun importFromUri( context: Context, uri: Uri, existingMeals: List ): Result = withContext(Dispatchers.IO) { try { context.contentResolver.openInputStream(uri)?.use { inputStream -> parseCsvStream(inputStream, existingMeals) } ?: Result.failure(IllegalStateException("Impossible d'ouvrir le fichier CSV")) } catch (e: Exception) { Result.failure(e) } } fun parseCsvStream( inputStream: InputStream, existingMeals: List ): Result { return try { val reader = BufferedReader(InputStreamReader(inputStream, Charsets.UTF_8)) val lines = parseCsvRecords(reader) if (lines.isEmpty()) { return Result.failure(IllegalArgumentException("Le fichier CSV est vide")) } val headerRow = lines[0] val colIndexMap = mapHeaders(headerRow) val parsedMeals = mutableListOf() var skippedDuplicates = 0 val discoveredFoodItems = mutableListOf() // Index existing meals by (minuteTimestamp, mealType) val existingFingerprints = existingMeals.map { meal -> buildFingerprint(meal.mealTimestamp, meal.mealType) }.toMutableSet() for (rowIndex in 1 until lines.size) { val row = lines[rowIndex] if (row.all { it.isBlank() }) continue val dateStr = getColValue(row, colIndexMap["date"]) val timeStr = getColValue(row, colIndexMap["time"]) val mealTypeRaw = getColValue(row, colIndexMap["meal_type"]) val hungerRaw = getColValue(row, colIndexMap["hunger"]) val satietyRaw = getColValue(row, colIndexMap["satiety"]) val foodsRaw = getColValue(row, colIndexMap["foods"]) val note = getColValue(row, colIndexMap["note"]) val timestamp = parseTimestamp(dateStr, timeStr) ?: System.currentTimeMillis() val mealType = parseMealType(mealTypeRaw) val hunger = hungerRaw.toIntOrNull()?.coerceIn(1, 10) ?: 5 val satiety = satietyRaw.toIntOrNull()?.coerceIn(1, 10) ?: 7 val fingerprint = buildFingerprint(timestamp, mealType.name) if (existingFingerprints.contains(fingerprint)) { skippedDuplicates++ continue } val foodItems = parseFoodItems(foodsRaw) discoveredFoodItems.addAll(foodItems) val newMeal = MealEntry( id = "local_imp_${UUID.randomUUID().toString().take(8)}", userId = "", mealType = mealType.name, mealTimestamp = timestamp, hungerBefore = hunger, satietyAfter = satiety, note = note, foodItemsSerialized = foodItems.map { it.serialize() }, photosBase64 = emptyList() ) parsedMeals.add(newMeal) existingFingerprints.add(fingerprint) } Result.success( CsvImportResult( importedMeals = parsedMeals, skippedDuplicatesCount = skippedDuplicates, newFoodItems = discoveredFoodItems.distinctBy { it.name.lowercase().trim() } ) ) } catch (e: Exception) { Result.failure(e) } } private fun buildFingerprint(timestamp: Long, mealType: String): String { val minute = timestamp / 60_000 return "${mealType.uppercase()}_$minute" } private fun mapHeaders(headerRow: List): Map { val map = mutableMapOf() for ((index, rawCol) in headerRow.withIndex()) { val col = java.text.Normalizer.normalize(rawCol.trim().lowercase(Locale.FRENCH), java.text.Normalizer.Form.NFD) .replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "") when { col == "date" -> map["date"] = index col.contains("heure") || col == "time" -> map["time"] = index col.contains("type") -> map["meal_type"] = index col.contains("faim") && !col.contains("ressenti") -> map["hunger"] = index col.contains("satiete") && !col.contains("ressenti") -> map["satiety"] = index col.contains("aliment") || col.contains("plat") -> map["foods"] = index col.contains("note") || col.contains("commentaire") -> map["note"] = index } } return map } private fun getColValue(row: List, colIndex: Int?): String { return if (colIndex != null && colIndex in row.indices) row[colIndex].trim() else "" } private fun parseTimestamp(dateStr: String, timeStr: String, zoneId: ZoneId = ZoneId.systemDefault()): Long? { if (dateStr.isBlank()) return null var parsedLocalDate: LocalDate? = null for (pattern in supportedDatePatterns) { try { parsedLocalDate = LocalDate.parse(dateStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH)) if (parsedLocalDate != null) break } catch (_: Exception) {} } if (parsedLocalDate == null) return null var parsedLocalTime = LocalTime.NOON if (timeStr.isNotBlank()) { for (pattern in supportedTimePatterns) { try { parsedLocalTime = LocalTime.parse(timeStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH)) break } catch (_: Exception) {} } } return LocalDateTime.of(parsedLocalDate, parsedLocalTime) .atZone(zoneId) .toInstant() .toEpochMilli() } private fun parseMealType(raw: String): MealType { val clean = java.text.Normalizer.normalize(raw.trim().lowercase(Locale.FRENCH), java.text.Normalizer.Form.NFD) .replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "") return when { clean.contains("petit") || clean.contains("breakfast") -> MealType.BREAKFAST clean.contains("dej") || clean.contains("lunch") || clean.contains("midi") -> MealType.LUNCH clean.contains("collat") || clean.contains("gout") || clean.contains("snack") -> MealType.SNACK clean.contains("din") || clean.contains("dinner") || clean.contains("soir") || clean.contains("souper") -> MealType.DINNER else -> MealType.LUNCH } } fun parseFoodItems(raw: String): List { val trimmed = raw.trim() if (trimmed.isEmpty()) return emptyList() // Delimiters between items can be ';' or '|' (or ',' if not surrounded by parenthesis) val tokens = if (trimmed.contains(";")) { trimmed.split(";").map { it.trim() } } else if (trimmed.contains("|") && !trimmed.contains("•")) { // Check if serialized pipe format (name|weight|unit) or multi items if (trimmed.count { it == '|' } in 1..2 && !trimmed.contains("g") && !trimmed.contains("ml")) { listOf(trimmed) } else { trimmed.split("|").map { it.trim() } } } else { listOf(trimmed) } val items = mutableListOf() for (token in tokens) { val itemStr = token.trim() if (itemStr.isEmpty()) continue // 1. Try serialized format "name|weight|unit" val deserialized = MealFoodItem.deserialize(itemStr) if (deserialized != null && deserialized.name != itemStr) { items.add(deserialized) continue } // 2. Parse formatted string like "Saumon grillé (150 g)" or "Riz basmati • 200 g" or "Pomme (1 portion)" val regex = Regex("""^(.*?)(?:\s*(?:\(|\•|-)\s*(\d+(?:[.,]\d+)?)\s*(g|ml|portions?|portion)?\s*\)?)?$""", RegexOption.IGNORE_CASE) val match = regex.find(itemStr) if (match != null) { val name = match.groupValues[1].trim() val weightStr = match.groupValues.getOrNull(2)?.replace(",", ".")?.trim() val weight = weightStr?.toDoubleOrNull() val unitRaw = match.groupValues.getOrNull(3)?.lowercase(Locale.FRENCH)?.trim().orEmpty() val unit = when { unitRaw.startsWith("ml") -> FoodUnit.ML unitRaw.startsWith("portion") -> FoodUnit.PORTION else -> FoodUnit.G } if (name.isNotEmpty()) { items.add(MealFoodItem(name = name, weight = weight, unit = unit)) } } else { items.add(MealFoodItem(name = itemStr, weight = null, unit = FoodUnit.G)) } } return items } /** * Robust CSV record splitter supporting quotes, commas, semicolons, and UTF-8 BOM. */ fun parseCsvRecords(reader: BufferedReader): List> { val records = mutableListOf>() var detectedDelimiter = ',' var firstLine: String? = reader.readLine() ?: return emptyList() // Strip BOM if present if (firstLine != null && firstLine.startsWith("\uFEFF")) { firstLine = firstLine.substring(1) } // Auto-detect delimiter from the first line (count ; vs , outside quotes) val semicolonCount = firstLine?.count { it == ';' } ?: 0 val commaCount = firstLine?.count { it == ',' } ?: 0 if (semicolonCount > commaCount) { detectedDelimiter = ';' } val fullText = StringBuilder() if (firstLine != null) { fullText.append(firstLine).append('\n') } var line: String? = reader.readLine() while (line != null) { fullText.append(line).append('\n') line = reader.readLine() } val text = fullText.toString() val currentField = StringBuilder() val currentRecord = mutableListOf() var inQuotes = false var i = 0 while (i < text.length) { val c = text[i] if (c == '"') { if (inQuotes && i + 1 < text.length && text[i + 1] == '"') { // Escaped quote ("") currentField.append('"') i++ } else { inQuotes = !inQuotes } } else if (c == detectedDelimiter && !inQuotes) { currentRecord.add(currentField.toString().trim()) currentField.clear() } else if ((c == '\r' || c == '\n') && !inQuotes) { if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') { i++ } currentRecord.add(currentField.toString().trim()) currentField.clear() if (currentRecord.any { it.isNotEmpty() }) { records.add(currentRecord.toList()) } currentRecord.clear() } else { currentField.append(c) } i++ } if (currentField.isNotEmpty() || currentRecord.isNotEmpty()) { currentRecord.add(currentField.toString().trim()) if (currentRecord.any { it.isNotEmpty() }) { records.add(currentRecord.toList()) } } return records } }