package com.example.domain import android.util.Log import com.example.data.model.DietaryReferenceGuide import com.example.data.model.DiscoverySuggestion import com.example.data.model.FoodCategory import com.example.data.model.FoodPreferenceEntry import com.example.data.model.FoodPreferenceStatus import com.example.data.model.FoodUnit import com.example.data.model.MealFoodItem import com.example.data.model.MealType import com.example.data.model.RecipeCategoryTag import com.example.data.model.RecipeSuggestion import com.google.firebase.Firebase import com.google.firebase.ai.ai import com.google.firebase.ai.type.Schema import com.google.firebase.ai.type.generationConfig import kotlinx.coroutines.CancellationException import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.withTimeout import org.json.JSONObject import java.util.UUID data class GeneratedCulinaryBundle( val contextSummary: String, val recipes: List, val discoveries: List ) /** * Generates personalized recipe ideas and new food discoveries using Firebase AI Logic * (gemini-3.8-flash with strict JSON responseSchema) grounded in the user's liked/disliked foods * and today's missing dietary benchmark categories. */ class CulinaryIdeasGenerator { private val allowedCategoryCodes = FoodCategory.entries.map { it.code } private val allowedUnitCodes = listOf("g", "ml", "portion") private val allowedRecipeTags = RecipeCategoryTag.entries.map { it.name } private val responseSchema by lazy { val ingredientSchema = Schema.obj( properties = mapOf( "name" to Schema.string(description = "Nom simple de l'ingrédient en français"), "weight" to Schema.double(description = "Quantité numérique pour le nombre total de portions"), "unit" to Schema.enumeration( values = allowedUnitCodes, description = "Unité : g, ml ou portion" ), "category" to Schema.enumeration( values = allowedCategoryCodes, description = "Catégorie alimentaire exacte parmi les codes fournis" ) ) ) val recipeSchema = Schema.obj( properties = mapOf( "title" to Schema.string(description = "Titre appétissant et clair en français"), "categoryTag" to Schema.enumeration( values = allowedRecipeTags, description = "Type de recette" ), "prepTimeMinutes" to Schema.integer(description = "Temps de préparation en minutes"), "servings" to Schema.integer(description = "Nombre de portions (généralement 1 ou 2)"), "whyItFits" to Schema.string(description = "Courte phrase bienveillante expliquant comment la recette s'appuie sur les goûts aimés et complète les repères du jour"), "completedCategories" to Schema.array( items = Schema.enumeration(values = allowedCategoryCodes), description = "Codes des catégories de repères alimentaires apportées par cette recette" ), "ingredients" to Schema.array( items = ingredientSchema, description = "Liste structurée des ingrédients avec quantités réalistes" ), "steps" to Schema.array( items = Schema.string(), description = "3 à 5 étapes simples, concrètes et rapides" ) ) ) val discoverySchema = Schema.obj( properties = mapOf( "foodName" to Schema.string(description = "Nom d'un nouvel aliment ou ingrédient simple à découvrir"), "category" to Schema.enumeration( values = allowedCategoryCodes, description = "Catégorie de repère alimentaire de cet aliment" ), "benchmarkReason" to Schema.string(description = "Courte explication bienveillante du repère alimentaire qu'il aide à remplir"), "pairingIdea" to Schema.string(description = "Idée très simple pour l'associer à un aliment déjà aimé") ) ) Schema.obj( properties = mapOf( "contextSummary" to Schema.string(description = "Phrase courte et chaleureuse résumant les repères ciblés pour ce repas"), "recipes" to Schema.array( items = recipeSchema, description = "2 à 3 idées de recettes variées et réalistes" ), "discoveries" to Schema.array( items = discoverySchema, description = "3 à 4 suggestions de nouveaux aliments à tester pour enrichir les repères alimentaires" ) ) ) } private val model by lazy { val config = generationConfig { responseMimeType = "application/json" responseSchema = this@CulinaryIdeasGenerator.responseSchema temperature = 0.7f } Firebase.ai.generativeModel( modelName = "gemini-3.8-flash", generationConfig = config ) } suspend fun generateIdeas( preferences: List, benchmarkGap: DailyBenchmarkGap, cravingNote: String, existingRecipeTitles: List ): Result { val prompt = buildPrompt( preferences = preferences, benchmarkGap = benchmarkGap, cravingNote = cravingNote, existingRecipeTitles = existingRecipeTitles ) return try { val response = withTimeout(60_000L) { model.generateContent(prompt) } val jsonText = response.text if (jsonText.isNullOrBlank()) { Result.failure(IllegalStateException("Le service d'idées a renvoyé une réponse vide. Réessayez.")) } else { val parsed = parseSuggestionsJson(jsonText) if (parsed.recipes.isEmpty() && parsed.discoveries.isEmpty()) { Result.failure(IllegalStateException("Aucune idée exploitable n'a pu être générée. Réessayez.")) } else { Result.success(parsed) } } } catch (e: TimeoutCancellationException) { Log.e(TAG, "AI culinary suggestion generation timed out", e) Result.failure( IllegalStateException("La génération a pris trop de temps (60 s). Vérifiez votre connexion et réessayez.") ) } catch (e: CancellationException) { throw e } catch (e: Exception) { Log.e(TAG, "Firebase AI culinary suggestion failed", e) Result.failure( IllegalStateException( e.localizedMessage ?: "Impossible de générer des idées pour le moment." ) ) } } private fun buildPrompt( preferences: List, benchmarkGap: DailyBenchmarkGap, cravingNote: String, existingRecipeTitles: List ): String { val liked = preferences.filter { it.status == FoodPreferenceStatus.LIKED } val disliked = preferences.filter { it.status == FoodPreferenceStatus.DISLIKED } val toTry = preferences.filter { it.status == FoodPreferenceStatus.TO_TRY } val likedText = if (liked.isEmpty()) { "Aucun aliment encore renseigné (propose des ingrédients simples, accessibles et variés)" } else { liked.joinToString(", ") { "${it.name} [${it.category.code}]" } } val dislikedText = if (disliked.isEmpty()) { "Aucun" } else { disliked.joinToString(", ") { it.name } } val toTryText = if (toTry.isEmpty()) { "Aucun" } else { toTry.joinToString(", ") { "${it.name} [${it.category.code}]" } } val presentTodayText = if (benchmarkGap.presentTodayCounts.isEmpty()) { "Aucun repas enregistré aujourd'hui" } else { benchmarkGap.presentTodayCounts.entries.joinToString(", ") { (cat, count) -> "${cat.displayName} (${cat.code}): $count fois" } } val priorityMissingText = if (benchmarkGap.priorityMissingCategories.isEmpty()) { "Tous les principaux repères du jour sont déjà présents ; proposer de la variété en douceur" } else { benchmarkGap.priorityMissingCategories.joinToString(", ") { "${it.displayName} (${it.code} — ${it.dailyGuide})" } } val categoriesCatalog = FoodCategory.benchmarkCategories.joinToString("\n") { cat -> "- ${cat.code}: ${cat.displayName} (${cat.dailyGuide})" } val avoidDuplicates = existingRecipeTitles.take(15).joinToString(", ") return """ Tu es un compagnon culinaire bienveillant intégré à l'application Satiéa (alimentation intuitive, zéro calcul de calories, zéro culpabilité). Réponds exclusivement en français naturel et chaleureux, conformément au schéma JSON demandé. OBJECTIF : 1. Proposer 3 idées de recettes simples, savoureuses et réalistes adaptées au moment du repas : ${benchmarkGap.targetMealType.displayName}. 2. Proposer 4 nouvelles découvertes d'aliments à tester (qui ne sont PAS déjà dans les listes Aimés, Évités ou À tester) pour aider à remplir les repères alimentaires manquants du jour. PROFIL GUSTATIF DE L'UTILISATEUR : - Aliments aimés (à utiliser en priorité dans les recettes) : $likedText - Aliments évités / allergies (INTERDICTION ABSOLUE dans les recettes ET les découvertes) : $dislikedText - Découvertes déjà notées « À tester » (tu peux en glisser 1 dans une recette si pertinent) : $toTryText - Envie du moment : ${cravingNote.ifBlank { "Aucune contrainte particulière, cuisine du quotidien" }} REPÈRES ALIMENTAIRES DU JOUR : - Déjà consommé aujourd'hui : $presentTodayText - Repères prioritaires à compléter pour ce ${benchmarkGap.targetMealType.displayName} : $priorityMissingText - Rappel philosophie : ${DietaryReferenceGuide.PLEASURE_REMINDER} CODES DE CATÉGORIES VALIDES ET REPÈRES QUOTIDIENS : $categoriesCatalog RÈGLES STRICTES : - N'inclus JAMAIS un aliment évité ni ses dérivés évidents. - Ne mentionne jamais de calories, de régime, ni de restriction. - Donne des quantités cohérentes avec la fiche repères (ex. ~125-150 g de protéine par portion, ~200 g de légumes, ~90 g de féculents crus / ~240 g cuits, ~30 g de fromage ou fruits à coque). - Utilise servings = 2 (ou 1 pour petit-déjeuner / collation) et adapte les poids des ingrédients au nombre total de servings. - Évite de répéter ces recettes déjà présentes dans le recueil : ${avoidDuplicates.ifBlank { "aucune" }}. """.trimIndent() } companion object { private const val TAG = "CulinaryIdeasGenerator" fun parseSuggestionsJson(jsonString: String): GeneratedCulinaryBundle { val root = JSONObject(jsonString) val contextSummary = root.optString("contextSummary", "").trim() val recipesArray = root.optJSONArray("recipes") val recipes = mutableListOf() if (recipesArray != null) { for (i in 0 until recipesArray.length()) { val obj = recipesArray.optJSONObject(i) ?: continue val title = obj.optString("title", "").trim() if (title.isBlank()) continue val tag = RecipeCategoryTag.fromString(obj.optString("categoryTag", "MAIN")) val prepTime = obj.optInt("prepTimeMinutes", 20).coerceIn(5, 240) val servings = obj.optInt("servings", 2).coerceIn(1, 12) val whyItFits = obj.optString("whyItFits", "").trim() val completedCats = mutableListOf() val catsArr = obj.optJSONArray("completedCategories") if (catsArr != null) { for (j in 0 until catsArr.length()) { FoodCategory.fromCode(catsArr.optString(j))?.let { cat -> if (cat != FoodCategory.OTHER && !completedCats.contains(cat)) { completedCats.add(cat) } } } } val ingredients = mutableListOf() val ingArr = obj.optJSONArray("ingredients") if (ingArr != null) { for (j in 0 until ingArr.length()) { val ingObj = ingArr.optJSONObject(j) ?: continue val ingName = ingObj.optString("name", "").trim() if (ingName.isBlank()) continue val weightRaw = ingObj.optDouble("weight", Double.NaN) val weight = if (!weightRaw.isNaN() && weightRaw > 0.0) weightRaw else null val unit = FoodUnit.fromCode(ingObj.optString("unit", "g")) val explicitCat = FoodCategory.fromCode(ingObj.optString("category")) ?: FoodCategory.inferFromName(ingName) ingredients.add( MealFoodItem( name = ingName, weight = weight, unit = unit, category = explicitCat ) ) } } val steps = mutableListOf() val stepsArr = obj.optJSONArray("steps") if (stepsArr != null) { for (j in 0 until stepsArr.length()) { val step = stepsArr.optString(j, "").trim() if (step.isNotBlank()) steps.add(step) } } val effectiveCompleted = completedCats.ifEmpty { ingredients.map { it.resolvedCategory() } .filter { it.showInBenchmarks } .distinct() .take(4) } recipes.add( RecipeSuggestion( id = "idea_rec_${i}_${UUID.randomUUID().toString().take(6)}", title = title, categoryTag = tag, prepTimeMinutes = prepTime, servings = servings, whyItFits = whyItFits, completedCategories = effectiveCompleted, ingredients = ingredients, steps = steps ) ) } } val discoveriesArray = root.optJSONArray("discoveries") val discoveries = mutableListOf() if (discoveriesArray != null) { for (i in 0 until discoveriesArray.length()) { val obj = discoveriesArray.optJSONObject(i) ?: continue val foodName = obj.optString("foodName", "").trim() if (foodName.isBlank()) continue val category = FoodCategory.fromCode(obj.optString("category")) ?: FoodCategory.inferFromName(foodName) val reason = obj.optString("benchmarkReason", "").trim() val pairing = obj.optString("pairingIdea", "").trim() discoveries.add( DiscoverySuggestion( id = "idea_disc_${i}_${UUID.randomUUID().toString().take(6)}", foodName = foodName, category = category, benchmarkReason = reason, pairingIdea = pairing ) ) } } return GeneratedCulinaryBundle( contextSummary = contextSummary, recipes = recipes, discoveries = discoveries ) } } }