package com.example.ui.planning import android.app.Application import android.net.Uri import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.example.data.model.CustomFoodEntry import com.example.data.model.FoodCategory import com.example.data.model.FoodUnit import com.example.data.model.InventoryItem import com.example.data.model.ManualShoppingItem import com.example.data.model.MealFoodItem import com.example.data.model.PlannedMealEntry import com.example.data.model.PredictedMealProposal import com.example.data.model.PredictionMealScope import com.example.data.model.ReceiptScanUiState import com.example.data.model.RecipeEntry import com.example.data.model.ScannedReceiptItem import com.example.data.model.ShoppingListItem import com.example.data.model.StockDeductionProposal import com.example.data.model.StorageLocation import com.example.data.model.WeekPredictionUiState import com.example.data.preferences.PlanningPreferencesManager import com.example.data.repository.MealRepository import com.example.domain.IngredientMatcher import com.example.domain.ReceiptScannerAnalyzer import com.example.domain.ShoppingListCalculator import com.example.domain.WeeklyMealPredictor import com.example.ui.common.UiEvent import com.example.util.ImageUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import java.time.DayOfWeek import java.time.LocalDate import java.time.temporal.TemporalAdjusters import java.util.UUID @OptIn(ExperimentalCoroutinesApi::class) class PlanningViewModel(application: Application) : AndroidViewModel(application) { private val repository = MealRepository(application) private val planningPrefs = PlanningPreferencesManager.getInstance(application) private val receiptAnalyzer by lazy { ReceiptScannerAnalyzer() } private val weeklyMealPredictor by lazy { WeeklyMealPredictor() } private val _uiEvents = Channel(Channel.BUFFERED) val uiEvents: Flow = _uiEvents.receiveAsFlow() private val _weekStartDate = MutableStateFlow(currentMonday()) val weekStartDate: StateFlow = _weekStartDate.asStateFlow() val weekPlannedMeals: StateFlow> = _weekStartDate .flatMapLatest { startDate -> val startEpoch = startDate.toEpochDay() val endEpoch = startDate.plusDays(6).toEpochDay() repository.observePlannedMealsForWeek(startEpoch, endEpoch) } .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList() ) val inventoryItems: StateFlow> = repository.observeInventory() .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList() ) val manualShoppingItems: StateFlow> = repository.observeManualShoppingItems() .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList() ) private val recipesFlow: Flow> = repository.observeRecipes() private val customFoodsFlow: Flow> = repository.observeCustomFoods() private val _checkedPlanKeys = MutableStateFlow(planningPrefs.getCheckedPlanKeys()) private data class ShoppingInputs( val planned: List, val recipes: List, val inventory: List, val manual: List, val checkedKeys: Set ) val computedShoppingList: StateFlow> = combine( combine( weekPlannedMeals, recipesFlow, inventoryItems, manualShoppingItems, _checkedPlanKeys ) { planned, recipes, inventory, manual, checkedKeys -> ShoppingInputs(planned, recipes, inventory, manual, checkedKeys) }, customFoodsFlow ) { inputs, customFoods -> val recipesById = inputs.recipes.associateBy { it.id } val customLookup = CustomFoodEntry.buildCategoriesLookup(customFoods) ShoppingListCalculator.computeShoppingList( plannedMeals = inputs.planned, recipesById = recipesById, inventory = inputs.inventory, manualItems = inputs.manual, checkedPlanKeys = inputs.checkedKeys, customCategoriesLookup = customLookup ) } .flowOn(Dispatchers.Default) .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList() ) private val _receiptScanState = MutableStateFlow(ReceiptScanUiState.Idle) val receiptScanState: StateFlow = _receiptScanState.asStateFlow() private val _weekPredictionState = MutableStateFlow(WeekPredictionUiState.Idle) val weekPredictionState: StateFlow = _weekPredictionState.asStateFlow() private val _pendingStockDeductions = MutableStateFlow?>(null) val pendingStockDeductions: StateFlow?> = _pendingStockDeductions.asStateFlow() private fun updateCheckedPlanKeys(transform: (Set) -> Set) { val updated = transform(_checkedPlanKeys.value) _checkedPlanKeys.value = updated planningPrefs.setCheckedPlanKeys(updated) } // ------------------------------------------------------------------------ // Week Navigation // ------------------------------------------------------------------------ fun previousWeek() { _weekStartDate.update { it.minusWeeks(1) } } fun nextWeek() { _weekStartDate.update { it.plusWeeks(1) } } fun goToCurrentWeek() { _weekStartDate.value = currentMonday() } // ------------------------------------------------------------------------ // Weekly Meal Planning // ------------------------------------------------------------------------ fun savePlannedMeal(entry: PlannedMealEntry) { viewModelScope.launch { repository.upsertPlannedMeal(entry).fold( onSuccess = { val label = if (entry.id.isBlank()) "Repas ajouté au planning" else "Repas planifié mis à jour" emitSnackbar(label) }, onFailure = { emitSnackbar("Impossible d'enregistrer le repas planifié") } ) } } fun deletePlannedMeal(id: String) { viewModelScope.launch { repository.deletePlannedMeal(id) emitSnackbar("Repas retiré du planning") } } fun togglePlannedMealConsumed(id: String, consumed: Boolean) { viewModelScope.launch { repository.markPlannedMealConsumed(id, consumed) } } /** * Marks an optional planned meal as consumed and computes stock deduction proposals * for the eaten foods that match current inventory items. */ fun onMealLoggedCheckStock( eatenItems: List, plannedMealId: String? = null ) { viewModelScope.launch { if (!plannedMealId.isNullOrBlank()) { repository.markPlannedMealConsumed(plannedMealId, consumed = true) } val currentStock = repository.getInventorySnapshot() val proposals = ShoppingListCalculator.computeStockDeductionProposals( eatenItems = eatenItems, inventory = currentStock ) if (proposals.isNotEmpty()) { _pendingStockDeductions.value = proposals } } } fun confirmStockDeductions(selectedProposals: List) { viewModelScope.launch { val active = selectedProposals.filter { it.selected && it.deductAmount > 0.0 } active.forEach { proposal -> repository.adjustInventoryQuantity( itemId = proposal.inventoryItem.id, delta = -proposal.deductAmount ) } _pendingStockDeductions.value = null if (active.isNotEmpty()) { emitSnackbar( "Stock mis à jour (${active.size} article${if (active.size > 1) "s" else ""} déduit${if (active.size > 1) "s" else ""})" ) } } } fun dismissStockDeductions() { _pendingStockDeductions.value = null } // ------------------------------------------------------------------------ // Kitchen Inventory (Stock) // ------------------------------------------------------------------------ fun saveInventoryItem(item: InventoryItem) { viewModelScope.launch { val result = if (item.id.isBlank()) { repository.addOrMergeInventoryItem( name = item.name, quantityToAdd = item.quantity, unit = item.unit, category = item.category, location = item.location ) } else { repository.upsertInventoryItem(item) } result.fold( onSuccess = { val message = if (item.id.isBlank()) { "${item.name.trim()} ajouté au stock" } else { "${item.name.trim()} mis à jour" } emitSnackbar(message) }, onFailure = { emitSnackbar("Veuillez renseigner un nom et une quantité valide") } ) } } fun adjustInventoryQuantity(itemId: String, delta: Double) { viewModelScope.launch { repository.adjustInventoryQuantity(itemId, delta) } } fun deleteInventoryItem(itemId: String) { viewModelScope.launch { repository.deleteInventoryItem(itemId) emitSnackbar("Article retiré du stock") } } // ------------------------------------------------------------------------ // Shopping List (Courses) // ------------------------------------------------------------------------ fun addManualShoppingItem( name: String, quantity: Double?, unit: FoodUnit, category: FoodCategory ) { val cleanName = name.trim() if (cleanName.isBlank()) return viewModelScope.launch { repository.upsertManualShoppingItem( ManualShoppingItem( name = cleanName, quantity = quantity?.takeIf { it > 0.0 }, unit = unit, category = category, isChecked = false ) ).fold( onSuccess = { emitSnackbar("$cleanName ajouté à la liste de courses") }, onFailure = { emitSnackbar("Impossible d'ajouter cet article") } ) } } fun toggleShoppingItemChecked(item: ShoppingListItem, checked: Boolean) { viewModelScope.launch { if (item.manualItemId != null) { repository.setManualShoppingItemChecked(item.manualItemId, checked) } if (item.key.startsWith("plan_")) { updateCheckedPlanKeys { current -> if (checked) current + item.key else current - item.key } } } } fun addShoppingItemToStock( item: ShoppingListItem, quantity: Double, unit: FoodUnit, location: StorageLocation ) { viewModelScope.launch { val safeQty = quantity.takeIf { it > 0.0 } ?: 1.0 repository.addOrMergeInventoryItem( name = item.name, quantityToAdd = safeQty, unit = unit, category = item.category, location = location ).fold( onSuccess = { if (item.manualItemId != null) { repository.setManualShoppingItemChecked(item.manualItemId, true) } if (item.key.startsWith("plan_")) { updateCheckedPlanKeys { it - item.key } } emitSnackbar("${item.name} ajouté au stock (${IngredientMatcher.formatQuantity(safeQty, unit)})") }, onFailure = { emitSnackbar("Impossible d'ajouter ${item.name} au stock") } ) } } /** * Batch-transfers all checked shopping items into kitchen inventory at the end of a shopping trip, * clears checked manual items, and removes processed plan-derived checked keys. */ fun finishShoppingAndAddToStock( checkedItems: List, locationsByKey: Map ) { if (checkedItems.isEmpty()) return viewModelScope.launch { var addedCount = 0 val processedPlanKeys = mutableSetOf() checkedItems.forEach { item -> val qtyToAdd = item.missingQuantity?.takeIf { it > 0.0 } ?: 1.0 val location = locationsByKey[item.key] ?: StorageLocation.defaultForCategory(item.category) val result = repository.addOrMergeInventoryItem( name = item.name, quantityToAdd = qtyToAdd, unit = item.unit, category = item.category, location = location ) if (result.isSuccess) { addedCount++ } if (item.key.startsWith("plan_")) { processedPlanKeys.add(item.key) } } repository.clearCheckedManualShoppingItems() if (processedPlanKeys.isNotEmpty()) { updateCheckedPlanKeys { it - processedPlanKeys } } if (addedCount > 0) { emitSnackbar( "$addedCount article${if (addedCount > 1) "s" else ""} ajouté${if (addedCount > 1) "s" else ""} au stock" ) } } } fun deleteManualShoppingItem(manualItemId: String) { viewModelScope.launch { repository.deleteManualShoppingItem(manualItemId) } } fun clearCheckedShoppingItems() { viewModelScope.launch { repository.clearCheckedManualShoppingItems() updateCheckedPlanKeys { emptySet() } emitSnackbar("Articles cochés nettoyés") } } // ------------------------------------------------------------------------ // Weekly Meal Prediction (Firebase AI Logic) // ------------------------------------------------------------------------ fun predictEmptyWeekMeals( scope: PredictionMealScope, defaultServings: Double ) { viewModelScope.launch { val start = _weekStartDate.value val existingMeals = weekPlannedMeals.value val occupiedSlots = existingMeals.map { it.dateEpochDay to it.mealType }.toSet() val emptySlots = (0L..6L).flatMap { offset -> val day = start.plusDays(offset) val epochDay = day.toEpochDay() scope.mealTypes.mapNotNull { mealType -> if ((epochDay to mealType) !in occupiedSlots) { day to mealType } else { null } } } if (emptySlots.isEmpty()) { _weekPredictionState.value = WeekPredictionUiState.Error( message = "Tous les créneaux de cette semaine pour « ${scope.displayName} » sont déjà planifiés.", scope = scope, defaultServings = defaultServings ) return@launch } _weekPredictionState.value = WeekPredictionUiState.Loading val inventory = repository.getInventorySnapshot() val recipes = repository.getAllRecipesSnapshot() val preferences = repository.getAllFoodPreferencesSnapshot().map { it.toDomain() } val recentMeals = repository.getAllMealsSnapshot() val result = weeklyMealPredictor.predictEmptySlots( emptySlots = emptySlots, existingWeekMeals = existingMeals, inventory = inventory, recipes = recipes, preferences = preferences, recentJournalMeals = recentMeals, defaultServings = defaultServings ) result.fold( onSuccess = { proposals -> _weekPredictionState.value = WeekPredictionUiState.Preview( proposals = proposals, scope = scope, defaultServings = defaultServings ) }, onFailure = { error -> _weekPredictionState.value = WeekPredictionUiState.Error( message = error.message ?: "Impossible de générer des suggestions pour le moment.", scope = scope, defaultServings = defaultServings ) } ) } } fun togglePredictedMeal(proposalId: String) { _weekPredictionState.update { state -> if (state is WeekPredictionUiState.Preview) { state.copy( proposals = state.proposals.map { proposal -> if (proposal.id == proposalId) proposal.copy(selected = !proposal.selected) else proposal } ) } else { state } } } fun updatePredictedMealServings(proposalId: String, newServings: Double) { val clamped = newServings.coerceIn(0.5, 20.0) _weekPredictionState.update { state -> if (state is WeekPredictionUiState.Preview) { state.copy( proposals = state.proposals.map { proposal -> if (proposal.id == proposalId) { val ratio = if (proposal.servings > 0.0) clamped / proposal.servings else 1.0 val scaledItems = proposal.items.map { item -> val scaledWeight = item.weight?.let { w -> Math.round(w * ratio * 10.0) / 10.0 } item.copy(weight = scaledWeight) } proposal.copy(servings = clamped, items = scaledItems) } else { proposal } } ) } else { state } } } fun confirmPredictedMeals() { val preview = _weekPredictionState.value as? WeekPredictionUiState.Preview ?: return val selectedProposals = preview.proposals.filter { it.selected } if (selectedProposals.isEmpty()) { emitSnackbar("Sélectionnez au moins un repas à ajouter au planning") return } viewModelScope.launch { selectedProposals.forEach { proposal -> repository.upsertPlannedMeal(proposal.toPlannedMealEntry()) } _weekPredictionState.value = WeekPredictionUiState.Idle emitSnackbar( "${selectedProposals.size} repas ajouté${if (selectedProposals.size > 1) "s" else ""} au planning • courses mises à jour" ) } } fun dismissWeekPrediction() { _weekPredictionState.value = WeekPredictionUiState.Idle } // ------------------------------------------------------------------------ // Receipt Scanning (Firebase AI Logic Multimodal) // ------------------------------------------------------------------------ fun scanReceiptFromUri(uri: Uri) { viewModelScope.launch { _receiptScanState.value = ReceiptScanUiState.Scanning val bitmap = ImageUtils.loadResizedBitmapForAi(getApplication(), uri, maxDimension = 1440) if (bitmap == null) { _receiptScanState.value = ReceiptScanUiState.Error( "Impossible de lire cette image. Essayez de reprendre la photo du ticket." ) return@launch } try { val result = receiptAnalyzer.analyzeReceipt(bitmap) result.fold( onSuccess = { items -> _receiptScanState.value = ReceiptScanUiState.Preview(items) }, onFailure = { error -> _receiptScanState.value = ReceiptScanUiState.Error( error.message ?: "Impossible d'analyser ce ticket pour le moment." ) } ) } finally { if (!bitmap.isRecycled) { bitmap.recycle() } } } } fun updateScannedItem(updated: ScannedReceiptItem) { _receiptScanState.update { state -> if (state is ReceiptScanUiState.Preview) { state.copy( items = state.items.map { if (it.id == updated.id) updated else it } ) } else { state } } } fun removeScannedItem(itemId: String) { _receiptScanState.update { state -> if (state is ReceiptScanUiState.Preview) { state.copy(items = state.items.filterNot { it.id == itemId }) } else { state } } } fun addBlankScannedItem() { val newItem = ScannedReceiptItem( id = "manual_${UUID.randomUUID().toString().take(6)}", rawLabel = "Ajout manuel", name = "", quantity = 1.0, unit = FoodUnit.PORTION, category = FoodCategory.OTHER, location = StorageLocation.PANTRY, selected = true ) _receiptScanState.update { state -> if (state is ReceiptScanUiState.Preview) { state.copy(items = state.items + newItem) } else { state } } } fun confirmScannedReceiptImport( items: List, alsoCheckShoppingList: Boolean ) { viewModelScope.launch { val selectedValid = items.filter { it.selected && it.name.isNotBlank() && it.quantity > 0.0 } if (selectedValid.isEmpty()) { emitSnackbar("Sélectionnez au moins un article valide à ajouter") return@launch } selectedValid.forEach { scanned -> repository.addOrMergeInventoryItem( name = scanned.name.trim(), quantityToAdd = scanned.quantity, unit = scanned.unit, category = scanned.category, location = scanned.location ) } if (alsoCheckShoppingList) { val scannedNorms = selectedValid.map { IngredientMatcher.normalize(it.name) }.toSet() val manualItems = repository.getManualShoppingItemsSnapshot() manualItems.forEach { manual -> val manualNorm = IngredientMatcher.normalize(manual.name) if (!manual.isChecked && scannedNorms.any { IngredientMatcher.matches(it, manualNorm) }) { repository.setManualShoppingItemChecked(manual.id, true) } } } _receiptScanState.value = ReceiptScanUiState.Idle emitSnackbar( "${selectedValid.size} article${if (selectedValid.size > 1) "s" else ""} ajouté${if (selectedValid.size > 1) "s" else ""} au stock" ) } } fun dismissReceiptScan() { _receiptScanState.value = ReceiptScanUiState.Idle } private fun emitSnackbar(message: String) { _uiEvents.trySend(UiEvent.ShowSnackbar(message)) } companion object { fun currentMonday(): LocalDate { return LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) } } }