diff --git a/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt b/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt index 900c680c..5bcac08a 100644 --- a/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt +++ b/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt @@ -24,6 +24,7 @@ Core behavior: - If a tool fails, explain the limitation gracefully and offer the next best answer. - Goals: when the context packet's `primaryGoal` is null, ask the user — once per conversation, early, and never instead of answering what they asked — what they want to achieve and by when. Offer the common ones briefly: lose weight, get stronger / build muscle, lose fat and keep muscle, sleep better, get fitter, move more, reduce stress, eat better. Map what they say to the closest kind ("get stronger" → build_muscle, "run a 5k" → get_fitter) and keep their own words in the description. When they answer, call set_goal, then tell them in one line what it changed in their Settings (its `settings_goals`), and that they can edit those numbers. If a weight goal needs more than 1% of body weight a week, say so plainly, propose a realistic date or target, and only save once they agree. - When a goal exists, tie advice to it. Call get_goal for anything about progress, calories or what to eat or do; start from its `levers` marked short, and use its numbers as given: the scale's trend, the suggested intake against what they burn and log, protein, sleep and steps. Name the one or two levers that matter most this week (e.g. "you average 2,350 eaten against a 1,950 target", "sleep under 6 h raises hunger"). Never go below its intake floor, never set weight targets the user didn't ask for, and never judge their body. +- Meal suggestions: the Nutrition screen shows a next-meal idea (call suggest_next_meal to see the same one). When the user wants alternatives, offer two or three everyday Brazilian options or common fruits that fit the calories left and the protein gap, with rough kcal. When they push back with something they prefer, check it against the goal (get_goal) and the calories left: if it fits, agree and call save_food_preference so future suggestions use it; if it doesn't, say why and offer a version that fits (a smaller portion, a different time). Don't save a preference the user didn't agree to. - When the context packet includes an `environment` block (the user's city + current weather), use it to ground practical suggestions — outdoor vs indoor workouts, hydration on hot days, planning around rain. Never reference the user's location more precisely than the city. Data limitations: diff --git a/app/src/main/java/com/pulseloop/coach/tools/MealSuggestionTools.kt b/app/src/main/java/com/pulseloop/coach/tools/MealSuggestionTools.kt new file mode 100644 index 00000000..7274cc34 --- /dev/null +++ b/app/src/main/java/com/pulseloop/coach/tools/MealSuggestionTools.kt @@ -0,0 +1,120 @@ +package com.pulseloop.coach.tools + +import com.pulseloop.service.MealSuggester +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.doubleOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put + +/** + * The next-meal idea, discussed in chat. `suggest_next_meal` returns the same suggestion the + * Nutrition screen shows (Brazilian everyday food and fruit, sized to what is left of the day); + * `save_food_preference` records an alternative the user and coach agreed on, so later + * suggestions use it whenever it still fits the budget. + */ +object MealSuggestionTools { + + val all: List get() = listOf(makeSuggest(), makeSavePreference(), makeListPreferences()) + + private val json = Json { encodeDefaults = true } + private val SLOTS = listOf("breakfast", "lunch", "snack", "dinner", "any") + + private fun makeSuggest() = CoachToolDef( + name = "suggest_next_meal", + publicLabel = "Planning your next meal", + description = "The next-meal suggestion for right now: everyday Brazilian food and common fruit, sized to the " + + "calories left today and the protein gap, using the user's agreed food preferences. Returns the slot, the " + + "items with portion, kcal and protein, the total, the kcal it leaves, and which preferences it used.", + parameters = JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(emptyMap()), + "required" to JsonArray(emptyList()), + "additionalProperties" to JsonPrimitive(false), + )), + ) { _, ctx -> + val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true) + val s = kotlinx.coroutines.runBlocking { MealSuggester.load(db) } + ?: return@CoachToolDef ToolResult("""{"error":"no suggestion"}""", isError = true) + ToolResult(json.encodeToString(MealSuggester.Suggestion.serializer(), s)) + } + + private fun makeSavePreference() = CoachToolDef( + name = "save_food_preference", + publicLabel = "Remembering your preference", + description = "Record a food preference the user and you agreed on while discussing a meal suggestion, e.g. " + + "banana instead of vegetables at dinner. Only save it once you have checked it still fits their goal " + + "(calories left, protein) and the user agreed. slot: breakfast, lunch, snack, dinner or any. action: prefer " + + "or avoid. instead_of: the food or role it replaces (e.g. \"vegetables\"). For a food that isn't common " + + "Brazilian fare or fruit, give portion, kcal and protein_g for one portion. Saving the same preference " + + "again strengthens it.", + parameters = JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(mapOf( + "slot" to JsonObject(mapOf("type" to JsonPrimitive("string"), "enum" to JsonArray(SLOTS.map { JsonPrimitive(it) }))), + "item" to JsonObject(mapOf("type" to JsonPrimitive("string"))), + "action" to JsonObject(mapOf("type" to JsonPrimitive("string"), "enum" to JsonArray(listOf(JsonPrimitive("prefer"), JsonPrimitive("avoid"))))), + "instead_of" to JsonObject(mapOf("type" to JsonPrimitive("string"))), + "portion" to JsonObject(mapOf("type" to JsonPrimitive("string"))), + "kcal" to JsonObject(mapOf("type" to JsonPrimitive("number"))), + "protein_g" to JsonObject(mapOf("type" to JsonPrimitive("number"))), + "reason" to JsonObject(mapOf("type" to JsonPrimitive("string"))), + )), + "required" to JsonArray(listOf(JsonPrimitive("slot"), JsonPrimitive("item"), JsonPrimitive("action"))), + "additionalProperties" to JsonPrimitive(false), + )), + strict = false, + ) { args, ctx -> + val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true) + val p = runCatching { Json.parseToJsonElement(args).jsonObject }.getOrNull() + ?: return@CoachToolDef ToolResult("""{"error":"invalid arguments"}""", isError = true) + fun str(k: String) = p[k]?.jsonPrimitive?.contentOrNull?.trim()?.takeIf { it.isNotEmpty() } + val slot = str("slot")?.takeIf { it in SLOTS } + ?: return@CoachToolDef ToolResult("""{"error":"slot must be one of $SLOTS"}""", isError = true) + val item = str("item")?.take(60) ?: return@CoachToolDef ToolResult("""{"error":"item is required"}""", isError = true) + val action = str("action")?.takeIf { it == "prefer" || it == "avoid" } + ?: return@CoachToolDef ToolResult("""{"error":"action must be prefer or avoid"}""", isError = true) + val kcal = p["kcal"]?.jsonPrimitive?.doubleOrNull?.takeIf { it in 1.0..2000.0 } + val row = kotlinx.coroutines.runBlocking { + MealSuggester.agree( + db, slot, item, action, str("instead_of")?.take(60), str("portion")?.take(40), + kcal, p["protein_g"]?.jsonPrimitive?.doubleOrNull?.takeIf { it in 0.0..200.0 }, str("reason")?.take(140), + ) + } + ToolResult(buildJsonObject { + put("ok", true) + put("slot", row.slot) + put("item", row.item) + put("action", row.action) + row.insteadOf?.let { put("instead_of", it) } + put("times_agreed", row.timesAgreed) + }.toString()) + } + + private fun makeListPreferences() = CoachToolDef( + name = "get_food_preferences", + publicLabel = "Checking your food preferences", + description = "List the food preferences already agreed with the user (slot, item, prefer/avoid, what it replaces, times agreed).", + parameters = JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(emptyMap()), + "required" to JsonArray(emptyList()), + "additionalProperties" to JsonPrimitive(false), + )), + ) { _, ctx -> + val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true) + val rows = kotlinx.coroutines.runBlocking { db.foodPreferenceDao().all() } + ToolResult(JsonArray(rows.map { r -> + buildJsonObject { + put("slot", r.slot); put("item", r.item); put("action", r.action) + r.insteadOf?.let { put("instead_of", it) } + put("times_agreed", r.timesAgreed) + } + }).toString()) + } +} diff --git a/app/src/main/java/com/pulseloop/coach/tools/ToolRegistry.kt b/app/src/main/java/com/pulseloop/coach/tools/ToolRegistry.kt index f594db5b..e0562cf1 100644 --- a/app/src/main/java/com/pulseloop/coach/tools/ToolRegistry.kt +++ b/app/src/main/java/com/pulseloop/coach/tools/ToolRegistry.kt @@ -13,7 +13,7 @@ class ToolRegistry(private val flags: CoachFeatureFlags) { // Nutrition read tools are grounding (always available, like the other read tools); // the write tools are gated on flags.writeToolsEnabled, mirroring iOS's // enableWriteTools split in NutritionTools.swift (iOS PR #96). - val all = RetrievalTools.all + AnalysisTools.all + ChartTools.all + NutritionTools.all + GoalTools.all + val all = RetrievalTools.all + AnalysisTools.all + ChartTools.all + NutritionTools.all + GoalTools.all + MealSuggestionTools.all val writable = if (flags.writeToolsEnabled) MemoryTools.all + ActionTools.writeTools + NutritionTools.writeTools else emptyList() val live = if (flags.liveMeasurementsEnabled) ActionTools.measurementTools else emptyList() tools = (all + writable + live).associateBy { it.name } diff --git a/app/src/main/java/com/pulseloop/data/DataArchive.kt b/app/src/main/java/com/pulseloop/data/DataArchive.kt index 6a52bb31..0d1765fc 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchive.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchive.kt @@ -45,6 +45,15 @@ data class PulseArchive( val journalEntries: List = emptyList(), /** The goals set with the coach (v30). */ val coachGoals: List = emptyList(), + /** Food preferences agreed with the coach (v31). */ + val foodPreferences: List = emptyList(), +) + +@Serializable data class FoodPreferenceDTO( + val id: String, val slot: String, val item: String, val action: String, + val insteadOf: String? = null, val portion: String? = null, + val kcal: Double? = null, val proteinG: Double? = null, val reason: String? = null, + val timesAgreed: Int = 1, val createdAt: Long, val updatedAt: Long, ) @Serializable data class CoachGoalDTO( diff --git a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt index b4d5b721..cf05ddfa 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt @@ -321,6 +321,14 @@ object DataArchiveService { timestamp = c.long("timestamp"), deletedAt = c.long("deletedAt"), ) }, + foodPreferences = collect("food_preferences") { c -> + FoodPreferenceDTO( + id = c.str("id"), slot = c.str("slot"), item = c.str("item"), action = c.str("action"), + insteadOf = c.strOrNull("insteadOf"), portion = c.strOrNull("portion"), + kcal = c.dblOrNull("kcal"), proteinG = c.dblOrNull("proteinG"), reason = c.strOrNull("reason"), + timesAgreed = c.intOrNull("timesAgreed") ?: 1, createdAt = c.long("createdAt"), updatedAt = c.long("updatedAt"), + ) + }, coachGoals = collect("coach_goals") { c -> CoachGoalDTO( id = c.str("id"), kind = c.str("kind"), description = c.str("description"), @@ -404,6 +412,13 @@ object DataArchiveService { } ) } + for (f in archive.foodPreferences) { + db.foodPreferenceDao().upsert(FoodPreferenceEntity( + id = f.id, slot = f.slot, item = f.item, action = f.action, insteadOf = f.insteadOf, + portion = f.portion, kcal = f.kcal, proteinG = f.proteinG, reason = f.reason, + timesAgreed = f.timesAgreed, createdAt = f.createdAt, updatedAt = f.updatedAt, + )) + } for (g in archive.coachGoals) { db.coachGoalDao().upsert(CoachGoalEntity( id = g.id, kind = g.kind, description = g.description, diff --git a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt index c1d0b6c1..496e4abb 100644 --- a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt +++ b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt @@ -46,8 +46,9 @@ import com.pulseloop.data.entity.* JournalEntryEntity::class, BodyMeasurementEntity::class, CoachGoalEntity::class, + FoodPreferenceEntity::class, ], - version = 30, + version = 31, exportSchema = false, ) abstract class PulseLoopDatabase : RoomDatabase() { @@ -73,6 +74,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { abstract fun userGoalDao(): UserGoalDao abstract fun bodyMeasurementDao(): BodyMeasurementDao abstract fun coachGoalDao(): CoachGoalDao + abstract fun foodPreferenceDao(): FoodPreferenceDao abstract fun coachSummaryDao(): CoachSummaryDao abstract fun wearableLogDao(): WearableLogDao abstract fun rawPacketDao(): RawPacketDao @@ -122,6 +124,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { "journal_entries", "body_measurements", "coach_goals", + "food_preferences", ) @Volatile private var INSTANCE: PulseLoopDatabase? = null @@ -565,6 +568,18 @@ abstract class PulseLoopDatabase : RoomDatabase() { } } + /** v30 → v31: food preferences agreed with the coach (next-meal suggestions). */ + private val MIGRATION_30_31 = object : Migration(30, 31) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `food_preferences` (`id` TEXT NOT NULL, `slot` TEXT NOT NULL, " + + "`item` TEXT NOT NULL, `action` TEXT NOT NULL, `insteadOf` TEXT, `portion` TEXT, " + + "`kcal` REAL, `proteinG` REAL, `reason` TEXT, `timesAgreed` INTEGER NOT NULL, " + + "`createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))" + ) + } + } + private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) { db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`") db.execSQL( @@ -661,6 +676,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { MIGRATION_27_28, MIGRATION_28_29, MIGRATION_29_30, + MIGRATION_30_31, ) // Downgrades only (sideloading an older APK). A blanket destructive // fallback would silently wipe every measurement, sleep session, and diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index 297194da..b594d8f9 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -919,3 +919,18 @@ interface CoachGoalDao { suspend fun upsert(goal: CoachGoalEntity) } + +@Dao +interface FoodPreferenceDao { + @Query("SELECT * FROM food_preferences ORDER BY timesAgreed DESC, updatedAt DESC") + suspend fun all(): List + + @Query("SELECT * FROM food_preferences WHERE id = :id LIMIT 1") + suspend fun byId(id: String): FoodPreferenceEntity? + + @Upsert + suspend fun upsert(pref: FoodPreferenceEntity) + + @Query("DELETE FROM food_preferences WHERE id = :id") + suspend fun delete(id: String) +} diff --git a/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt b/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt index a32eff25..3e70bee5 100644 --- a/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt +++ b/app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt @@ -385,3 +385,34 @@ data class CoachGoalEntity( val createdAt: Long = System.currentTimeMillis(), val updatedAt: Long = System.currentTimeMillis(), ) + +/** + * v31: a food preference the user and the coach agreed on ("banana instead of vegetables at + * night"). Meal suggestions use it whenever it still fits the day's budget. [timesAgreed] grows + * each time the same preference is agreed again, so a repeated choice weighs more. + */ +@Entity(tableName = "food_preferences") +data class FoodPreferenceEntity( + @PrimaryKey val id: String, + /** breakfast, lunch, snack, dinner, or any. */ + val slot: String, + /** The food, in the user's words or a catalog name. */ + val item: String, + /** prefer or avoid. */ + val action: String, + /** What it replaces in a suggestion (a food or a role like "vegetables"), if anything. */ + val insteadOf: String? = null, + /** Portion and its nutrition when the food isn't in the catalog. */ + val portion: String? = null, + val kcal: Double? = null, + val proteinG: Double? = null, + val reason: String? = null, + val timesAgreed: Int = 1, + val createdAt: Long = System.currentTimeMillis(), + val updatedAt: Long = System.currentTimeMillis(), +) { + companion object { + /** One row per slot + item + action, so agreeing again counts up instead of duplicating. */ + fun idFor(slot: String, item: String, action: String) = "$slot:${item.trim().lowercase()}:$action" + } +} diff --git a/app/src/main/java/com/pulseloop/service/MealSuggester.kt b/app/src/main/java/com/pulseloop/service/MealSuggester.kt new file mode 100644 index 00000000..1256f605 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/MealSuggester.kt @@ -0,0 +1,251 @@ +package com.pulseloop.service + +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.FoodPreferenceEntity +import kotlinx.serialization.Serializable +import java.time.Instant +import java.time.LocalTime +import java.time.ZoneId +import kotlin.math.roundToInt + +/** + * The next-meal idea on the Nutrition screen: a plate of everyday Brazilian food and common fruit + * that fits what is left of the day's calories, and closes the protein gap where it can. + * + * Rules, not a model, so the numbers always add up and the card works without an AI key. The + * coach discusses it in chat and records what the user agrees to instead ([FoodPreferenceEntity]); + * an agreed preference is used next time whenever it still fits the budget, so a choice the user + * keeps making ("banana at night, not vegetables") becomes the default. + */ +object MealSuggester { + + enum class Role { PROTEIN, CARB, LEGUME, VEG, FRUIT, DAIRY, EXTRA } + + data class Food( + val id: String, + /** Portuguese name, as the user knows the dish. */ + val name: String, + val english: String, + val portion: String, + val kcal: Double, + val proteinG: Double, + val carbsG: Double, + val fatG: Double, + val role: Role, + val slots: Set, + ) + + private val B = "breakfast"; private val L = "lunch"; private val S = "snack"; private val D = "dinner" + + /** Typical portions, TACO-style values, rounded. */ + val CATALOG: List = listOf( + // Fruit + Food("banana", "Banana", "banana", "1 medium", 105.0, 1.3, 27.0, 0.4, Role.FRUIT, setOf(B, S, D)), + Food("maca", "Maçã", "apple", "1 medium", 95.0, 0.5, 25.0, 0.3, Role.FRUIT, setOf(B, S, D)), + Food("mamao", "Mamão papaia", "papaya", "½ fruit", 60.0, 1.0, 15.0, 0.2, Role.FRUIT, setOf(B, S)), + Food("laranja", "Laranja", "orange", "1 medium", 62.0, 1.2, 15.0, 0.2, Role.FRUIT, setOf(B, S)), + Food("melancia", "Melancia", "watermelon", "2 slices", 60.0, 1.2, 15.0, 0.3, Role.FRUIT, setOf(S)), + // Breakfast and snacks + Food("pao_queijo_minas", "Pão francês com queijo minas", "bread roll with fresh cheese", "1 roll + 30 g", 220.0, 9.0, 30.0, 6.0, Role.CARB, setOf(B, S)), + Food("tapioca_ovo", "Tapioca com ovo", "tapioca with egg", "1 medium", 230.0, 8.0, 32.0, 6.0, Role.CARB, setOf(B, S, D)), + Food("cuscuz_ovo", "Cuscuz com ovo", "corn couscous with egg", "1 plate", 250.0, 9.0, 35.0, 7.0, Role.CARB, setOf(B, D)), + Food("ovos_mexidos", "Ovos mexidos", "scrambled eggs", "2 eggs", 180.0, 12.0, 2.0, 14.0, Role.PROTEIN, setOf(B, D)), + Food("iogurte", "Iogurte natural", "plain yogurt", "1 pot (170 g)", 100.0, 6.0, 8.0, 5.0, Role.DAIRY, setOf(B, S, D)), + Food("cafe_leite", "Café com leite", "coffee with milk", "1 cup", 90.0, 6.0, 9.0, 3.0, Role.DAIRY, setOf(B, S)), + Food("castanhas", "Castanhas", "brazil or cashew nuts", "30 g", 180.0, 4.0, 6.0, 16.0, Role.EXTRA, setOf(S)), + Food("pao_de_queijo", "Pão de queijo", "cheese bread", "2 small", 180.0, 3.0, 18.0, 10.0, Role.EXTRA, setOf(B, S)), + // Lunch and dinner + Food("arroz", "Arroz branco", "white rice", "4 tbsp (100 g)", 130.0, 2.5, 28.0, 0.3, Role.CARB, setOf(L, D)), + Food("feijao", "Feijão", "beans", "1 ladle (100 g)", 76.0, 4.8, 14.0, 0.5, Role.LEGUME, setOf(L, D)), + Food("batata_doce", "Batata-doce", "sweet potato", "150 g", 130.0, 2.0, 30.0, 0.2, Role.CARB, setOf(L, D)), + Food("mandioca", "Mandioca cozida", "boiled cassava", "100 g", 125.0, 1.0, 30.0, 0.3, Role.CARB, setOf(L, D)), + Food("frango", "Frango grelhado", "grilled chicken", "120 g", 195.0, 37.0, 0.0, 4.0, Role.PROTEIN, setOf(L, D)), + Food("tilapia", "Tilápia grelhada", "grilled tilapia", "120 g", 155.0, 31.0, 0.0, 3.0, Role.PROTEIN, setOf(L, D)), + Food("patinho", "Patinho moído", "lean ground beef", "100 g", 220.0, 27.0, 0.0, 12.0, Role.PROTEIN, setOf(L, D)), + Food("omelete", "Omelete de 2 ovos com queijo", "2-egg cheese omelette", "1", 250.0, 17.0, 2.0, 19.0, Role.PROTEIN, setOf(D)), + Food("salada", "Salada verde com tomate", "green salad with tomato", "1 plate, 1 tsp olive oil", 60.0, 1.0, 5.0, 4.0, Role.VEG, setOf(L, D)), + Food("legumes", "Legumes cozidos", "steamed vegetables (zucchini, carrot, broccoli)", "150 g", 60.0, 3.0, 10.0, 0.5, Role.VEG, setOf(L, D)), + Food("sopa_legumes", "Sopa de legumes com frango", "vegetable and chicken soup", "1 bowl", 220.0, 18.0, 22.0, 6.0, Role.PROTEIN, setOf(D)), + ) + + /** The meal slot for a local time of day. */ + fun slotAt(time: LocalTime): String = when (time.hour) { + in 4..9 -> B + in 10..14 -> L + in 15..17 -> S + else -> D + } + + /** Share of the day's calories a slot normally takes, for sizing one meal. */ + private val SLOT_SHARE = mapOf(B to 0.25, L to 0.35, S to 0.12, D to 0.30) + + @Serializable + data class Item(val name: String, val english: String, val portion: String, val kcal: Int, val proteinG: Int, val carbsG: Int = 0, val fatG: Int = 0) + + @Serializable + data class Suggestion( + val slot: String, + val items: List, + val totalKcal: Int, + val totalProteinG: Int, + /** Calories left after this meal, against the day's target. */ + val leavesKcal: Int, + /** Preferences this suggestion used, in words ("banana at dinner"). */ + val fromPreferences: List = emptyList(), + val note: String? = null, + ) + + data class Inputs( + val slot: String, + val targetKcal: Double, + val eatenKcal: Double, + val proteinTargetG: Double?, + val proteinEatenG: Double, + val preferences: List = emptyList(), + /** Varies the pick from day to day (day of year). */ + val seed: Int = 0, + ) + + private fun matches(food: Food, text: String): Boolean { + val t = text.trim().lowercase() + if (t.isEmpty()) return false + return food.id == t || food.name.lowercase().contains(t) || food.english.lowercase().contains(t) || + t.contains(food.name.lowercase()) || t.contains(food.english.lowercase()) + } + + private fun roleOf(text: String): Role? = when (text.trim().lowercase()) { + "vegetables", "veg", "veggies", "legumes", "verduras", "salad", "salada" -> Role.VEG + "fruit", "fruta", "frutas" -> Role.FRUIT + "carbs", "carb", "rice", "arroz", "carboidrato" -> Role.CARB + "beans", "feijão", "feijao" -> Role.LEGUME + "protein", "proteína", "proteina", "meat", "carne" -> Role.PROTEIN + else -> null + } + + /** The food a preference names: a catalog entry, or the user's own food with its nutrition. */ + private fun foodFor(p: FoodPreferenceEntity): Food? = + CATALOG.firstOrNull { matches(it, p.item) } + ?: if (p.kcal != null) Food("pref:${p.item}", p.item.replaceFirstChar { it.uppercase() }, p.item, + p.portion ?: "1 portion", p.kcal, p.proteinG ?: 0.0, 0.0, 0.0, Role.EXTRA, setOf(B, L, S, D)) else null + + fun suggest(i: Inputs): Suggestion { + val remaining = i.targetKcal - i.eatenKcal + val slot = i.slot + val slotPrefs = i.preferences.filter { it.slot == slot || it.slot == "any" } + val avoided = slotPrefs.filter { it.action == "avoid" } + val preferred = slotPrefs.filter { it.action == "prefer" }.sortedByDescending { it.timesAgreed } + + // An avoid names a food ("tapioca") or a whole role ("vegetables"). + fun allowed(f: Food) = slot in f.slots && avoided.none { matches(f, it.item) || roleOf(it.item) == f.role } + fun pool(role: Role) = CATALOG.filter { it.role == role && allowed(it) } + .let { list -> if (list.isEmpty()) list else list.indices.map { list[(it + i.seed) % list.size] } } + + if (remaining < 120) { + val fruit = pool(Role.FRUIT).firstOrNull() + return Suggestion( + slot = slot, items = emptyList(), totalKcal = 0, totalProteinG = 0, leavesKcal = remaining.roundToInt(), + note = if (remaining <= 0) "You've reached today's target. Water or tea if you're hungry" + + (fruit?.let { ", or a ${it.english} if you need something (${it.kcal.roundToInt()} kcal)." } ?: ".") + else "Only ${remaining.roundToInt()} kcal left: " + (fruit?.let { "a ${it.english} fits." } ?: "keep it light."), + ) + } + + val budget = minOf(remaining, i.targetKcal * (SLOT_SHARE[slot] ?: 0.3)).coerceAtLeast(120.0) + val proteinGap = ((i.proteinTargetG ?: 0.0) - i.proteinEatenG).coerceAtLeast(0.0) + + // The plate's roles for this meal. + val template = when (slot) { + B -> listOf(Role.CARB, Role.DAIRY, Role.FRUIT) + L -> listOf(Role.PROTEIN, Role.CARB, Role.LEGUME, Role.VEG) + S -> listOf(Role.FRUIT, Role.DAIRY) + else -> listOf(Role.PROTEIN, Role.VEG, Role.CARB) + }.toMutableList() + + val plate = mutableListOf() + val used = mutableListOf() + // Agreed preferences first, while they fit: replace what they stand in for. + for (p in preferred) { + val food = foodFor(p) ?: continue + if (plate.sumOf { it.kcal } + food.kcal > budget) continue + val replaces = p.insteadOf?.let { roleOf(it) ?: CATALOG.firstOrNull { f -> matches(f, it) }?.role } + replaces?.let { template.remove(it) } + template.remove(food.role) + plate += food + used += "${p.item} at ${if (p.slot == "any") "any meal" else p.slot}" + (p.insteadOf?.let { " instead of $it" } ?: "") + } + // Then fill the template, protein first when there's a gap, each within what's left. + val order = if (proteinGap > 15) template.sortedBy { if (it == Role.PROTEIN || it == Role.DAIRY) 0 else 1 } else template + for (role in order) { + val left = budget - plate.sumOf { it.kcal } + val pick = pool(role).filter { it.kcal <= left && plate.none { p -> p.id == it.id } } + .maxByOrNull { if (role == Role.PROTEIN) it.proteinG else 0.0 } ?: continue + plate += pick + } + + val total = plate.sumOf { it.kcal } + return Suggestion( + slot = slot, + items = plate.map { Item(it.name, it.english, it.portion, it.kcal.roundToInt(), it.proteinG.roundToInt(), it.carbsG.roundToInt(), it.fatG.roundToInt()) }, + totalKcal = total.roundToInt(), + totalProteinG = plate.sumOf { it.proteinG }.roundToInt(), + leavesKcal = (remaining - total).roundToInt(), + fromPreferences = used, + note = if (proteinGap > 30) "You're ${proteinGap.roundToInt()} g short of today's protein, so this leans on protein." else null, + ) + } + + /** Whether the Nutrition screen offers the idea: once a third of the day's target is eaten. */ + const val SHOW_FROM_SHARE = 0.33 + fun shouldShow(targetKcal: Double, eatenKcal: Double): Boolean = targetKcal > 0 && eatenKcal >= targetKcal * SHOW_FROM_SHARE + + // ── Loading ────────────────────────────────────────────────────────── + + suspend fun load(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): Suggestion? { + val local = Instant.ofEpochMilli(now).atZone(zone) + val todayStart = local.toLocalDate().atStartOfDay(zone).toInstant().toEpochMilli() + val meals = db.mealEntryDao().byDay(todayStart) + val goal = db.userGoalDao().get() + val target = goal?.intakeCalories ?: 2000.0 + return suggest( + Inputs( + slot = slotAt(local.toLocalTime()), + targetKcal = target, + eatenKcal = meals.sumOf { it.calories }, + proteinTargetG = goal?.intakeProteinG, + proteinEatenG = meals.sumOf { it.proteinG }, + preferences = db.foodPreferenceDao().all(), + seed = local.dayOfYear, + ), + ) + } + + /** + * Records a preference the user and coach agreed on; agreeing to the same one again counts up. + * Returns the stored row. + */ + suspend fun agree( + db: PulseLoopDatabase, + slot: String, + item: String, + action: String, + insteadOf: String?, + portion: String?, + kcal: Double?, + proteinG: Double?, + reason: String?, + ): FoodPreferenceEntity { + val id = FoodPreferenceEntity.idFor(slot, item, action) + val existing = db.foodPreferenceDao().byId(id) + val row = existing?.copy( + insteadOf = insteadOf ?: existing.insteadOf, + portion = portion ?: existing.portion, + kcal = kcal ?: existing.kcal, + proteinG = proteinG ?: existing.proteinG, + reason = reason ?: existing.reason, + timesAgreed = existing.timesAgreed + 1, + updatedAt = System.currentTimeMillis(), + ) ?: FoodPreferenceEntity(id, slot, item.trim(), action, insteadOf, portion, kcal, proteinG, reason) + db.foodPreferenceDao().upsert(row) + return row + } +} diff --git a/app/src/main/java/com/pulseloop/ui/LaunchRequests.kt b/app/src/main/java/com/pulseloop/ui/LaunchRequests.kt index d311c597..0491dd8b 100644 --- a/app/src/main/java/com/pulseloop/ui/LaunchRequests.kt +++ b/app/src/main/java/com/pulseloop/ui/LaunchRequests.kt @@ -11,6 +11,9 @@ import kotlinx.coroutines.flow.MutableStateFlow object LaunchRequests { val route = MutableStateFlow(null) + /** A message to send to the coach when its screen opens (e.g. discussing a meal suggestion). */ + val coachMessage = MutableStateFlow(null) + /** Today's Workout chip: open the Activity tab with the workout-type picker up. */ val openWorkoutPicker = MutableStateFlow(false) } diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index c66d7c9c..c90d707c 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -634,13 +634,18 @@ fun PulseLoopApp() { onNavigateToNutrition = { navController.navigate("nutrition") }, ) } + // "Other ideas" on the next-meal card hands the suggestion to the coach chat. + val discussMeal: ((String) -> Unit)? = if (apiKeyStore.coachEnabled) { msg -> + com.pulseloop.ui.LaunchRequests.coachMessage.value = msg + navController.navigate("coach") { launchSingleTop = true } + } else null paddedComposable("nutrition") { - NutritionScreen(onBack = { navController.popBackStack() }) + NutritionScreen(onBack = { navController.popBackStack() }, onDiscuss = discussMeal) } // Straight into a way of logging (Today's food card, the "Log meal" shortcut). listOf("photo", "barcode", "add").forEach { start -> paddedComposable("nutrition/$start") { - NutritionScreen(onBack = { navController.popBackStack() }, start = start) + NutritionScreen(onBack = { navController.popBackStack() }, start = start, onDiscuss = discussMeal) } } paddedComposable("settings/about") { diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt index d44f02ae..ed973f6f 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt @@ -72,6 +72,15 @@ fun CoachScreen( val isLandscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE + // A message handed over from another screen (the Nutrition screen's "Discuss with coach"). + LaunchedEffect(viewModel) { + com.pulseloop.ui.LaunchRequests.coachMessage.collect { msg -> + if (msg != null && viewModel != null) { + com.pulseloop.ui.LaunchRequests.coachMessage.value = null + viewModel.sendMessage(msg) + } + } + } // +1: the goal banner is the list's first item. LaunchedEffect(state.messages.size) { if (state.messages.isNotEmpty()) listState.animateScrollToItem(state.messages.size) diff --git a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt index 9d0fc8a1..bf0fce1e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -42,6 +42,8 @@ fun NutritionScreen( onBack: () -> Unit, /** Open straight into a way of logging: "photo", "barcode" or "add" (Today card, icon shortcut). */ start: String? = null, + /** Opens the coach with a message, to discuss the next-meal idea. Null hides that button. */ + onDiscuss: ((String) -> Unit)? = null, ) { val context = androidx.compose.ui.platform.LocalContext.current val scope = rememberCoroutineScope() @@ -63,10 +65,13 @@ fun NutritionScreen( var totals by remember { mutableStateOf>(emptyList()) } var goal by remember { mutableStateOf(null) } + var suggestion by remember { mutableStateOf(null) } + fun reload() { scope.launch { meals = db.mealEntryDao().byDay(todayStart) totals = db.mealEntryDao().dayTotals(todayStart) + suggestion = runCatching { com.pulseloop.service.MealSuggester.load(db) }.getOrNull() } } LaunchedEffect(Unit) { goal = db.userGoalDao().get() } @@ -149,6 +154,45 @@ fun NutritionScreen( } } + // Next-meal idea, once a third of the day's target is eaten (today only). + val eatenToday = totals.sumOf { it.totalCal } + val targetToday = goal?.intakeCalories ?: 2000.0 + val idea = suggestion + if (dayOffset == 0 && idea != null && com.pulseloop.service.MealSuggester.shouldShow(targetToday, eatenToday)) { + item { + NextMealCard( + idea = idea, + onLog = { + scope.launch { + val entry = MealEntryEntity( + date = todayStart, timestamp = System.currentTimeMillis(), + name = idea.items.joinToString(" + ") { it.name }, + mealTypeRaw = idea.slot, + calories = idea.totalKcal.toDouble(), + proteinG = idea.items.sumOf { it.proteinG }.toDouble(), + carbsG = idea.items.sumOf { it.carbsG }.toDouble(), + fatG = idea.items.sumOf { it.fatG }.toDouble(), + sourceRaw = NutritionTools.sourceRawManual, + notes = "From the next-meal suggestion", + ) + db.mealEntryDao().upsert(entry) + com.pulseloop.service.MealJournal.afterLog(db, entry) + reload() + } + }, + onDiscuss = onDiscuss?.let { discuss -> + { + discuss( + "For my next meal (${idea.slot}) you suggested: " + + idea.items.joinToString(", ") { "${it.name} (${it.portion})" } + + ", about ${idea.totalKcal} kcal. Can we look at alternatives?" + ) + } + }, + ) + } + } + // Meals grouped by type val mealTypes = listOf("breakfast", "lunch", "dinner", "snack") for (type in mealTypes) { @@ -481,3 +525,49 @@ private data class PendingBarcodeProduct( val fat: Double, val servingDescription: String?, ) + +/** The next-meal idea: a plate that fits what's left of today, to log as is or discuss with the coach. */ +@Composable +private fun NextMealCard( + idea: com.pulseloop.service.MealSuggester.Suggestion, + onLog: () -> Unit, + onDiscuss: (() -> Unit)?, +) { + Card( + Modifier.fillMaxWidth(), + shape = RoundedCornerShape(8.dp), + colors = CardDefaults.cardColors(containerColor = PulseColors.card), + border = androidx.compose.foundation.BorderStroke(1.dp, PulseColors.accent), + ) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text("NEXT MEAL IDEA · ${idea.slot.uppercase()}", fontSize = 11.sp, letterSpacing = 1.4.sp, color = PulseColors.accent) + if (idea.items.isEmpty()) { + Text(idea.note ?: "", fontSize = 14.sp, color = PulseColors.textPrimary) + } else { + idea.items.forEach { item -> + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(item.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + Text("${item.english} · ${item.portion}", fontSize = 12.sp, color = PulseColors.textMuted) + } + Text("${item.kcal} kcal", fontSize = 13.sp, color = PulseColors.textSecondary) + } + } + Text( + "≈ ${idea.totalKcal} kcal · ${idea.totalProteinG} g protein · leaves ${idea.leavesKcal} kcal", + fontSize = 13.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary, + ) + if (idea.fromPreferences.isNotEmpty()) { + Text("Your preference: " + idea.fromPreferences.joinToString("; "), fontSize = 12.sp, color = PulseColors.accent) + } + idea.note?.let { Text(it, fontSize = 12.sp, color = PulseColors.textSecondary) } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = onLog, modifier = Modifier.weight(1f)) { Text("Log this") } + if (onDiscuss != null) { + OutlinedButton(onClick = onDiscuss, modifier = Modifier.weight(1f)) { Text("Other ideas") } + } + } + } + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt index 5e7839c7..e516bacd 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -4,6 +4,7 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* +import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add @@ -221,3 +222,54 @@ private fun SheetOption(title: String, subtitle: String, icon: ImageVector, onCl } } } + +/** The whole coach brief (the Today line shows only its first lines), with a way into the chat. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CoachBriefSheet( + title: String, + body: String, + chips: List, + askCoach: Boolean, + onDismiss: () -> Unit, + onAsk: () -> Unit, +) { + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + containerColor = PulseColors.secondaryBackground, + ) { + Column( + Modifier + .fillMaxWidth() + .verticalScroll(androidx.compose.foundation.rememberScrollState()) + .padding(horizontal = 20.dp) + .padding(bottom = 32.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text("TODAY'S BRIEF", fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.accent) + Text(title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(body, fontSize = 15.sp, lineHeight = 22.sp, color = PulseColors.textSecondary) + if (chips.isNotEmpty()) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + chips.take(3).forEach { + Text( + it, fontSize = 12.sp, color = PulseColors.textPrimary, maxLines = 1, + modifier = Modifier + .clip(RoundedCornerShape(16.dp)) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, RoundedCornerShape(16.dp)) + .padding(horizontal = 10.dp, vertical = 5.dp), + ) + } + } + } + if (askCoach) { + androidx.compose.material3.Button( + onClick = onAsk, + modifier = Modifier.fillMaxWidth(), + ) { Text("Ask the coach about it") } + } + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt index fae7c5de..fb1cb3e7 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -96,6 +96,7 @@ fun TodayScreen( val activityScore = rememberActivityScore(db, listOf(state.lastUpdated, state.steps)) val guidance = rememberGuidance(db, listOf(state.lastUpdated, sleep.lastNight?.id, sleep.lastNight?.updatedAt)) var mealSheet by remember { mutableStateOf(false) } + var briefSheet by remember { mutableStateOf(false) } var tagSheet by remember { mutableStateOf(false) } // Today's food log, for the Nutrition tile and the midday food moment. val food by produceState(null, state.lastUpdated, mealSheet) { @@ -195,7 +196,8 @@ fun TodayScreen( alert = alert, insight = insight, onAlert = { navController?.navigate("readiness") }, - onInsight = if (coachEnabled) ({ navController?.navigate("coach") }) else null, + // The line is cut at three lines; tapping opens the whole brief. + onInsight = { briefSheet = true }, ) } @@ -300,6 +302,22 @@ fun TodayScreen( navController?.navigate("nutrition/$start") } } + if (briefSheet) { + val summary = state.coachSummary + val fromCoach = coachEnabled && summary != null + CoachBriefSheet( + title = if (fromCoach) summary!!.title else (readiness?.let { "Today" } ?: hero.title), + body = if (fromCoach) summary!!.body + else listOfNotNull(readiness?.let { com.pulseloop.service.ReadinessCopy.headline(it) }, hero.summary).joinToString("\n\n"), + chips = if (fromCoach) parseChips(summary!!.chipsJSON) else hero.chips.map { it.label }, + askCoach = coachEnabled, + onDismiss = { briefSheet = false }, + onAsk = { + briefSheet = false + navController?.navigate("coach") + }, + ) + } if (tagSheet) { TagDaySheet(db, onDismiss = { tagSheet = false }) { tagSheet = false diff --git a/app/src/test/java/com/pulseloop/service/MealSuggesterTest.kt b/app/src/test/java/com/pulseloop/service/MealSuggesterTest.kt new file mode 100644 index 00000000..db7c14b1 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/MealSuggesterTest.kt @@ -0,0 +1,72 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.FoodPreferenceEntity +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalTime + +/** The next-meal idea: within budget, Brazilian staples, and agreed preferences winning when they fit. */ +class MealSuggesterTest { + + private fun inputs(slot: String, eaten: Double, prefs: List = emptyList(), protein: Double = 0.0) = + MealSuggester.Inputs(slot = slot, targetKcal = 2000.0, eatenKcal = eaten, proteinTargetG = 130.0, proteinEatenG = protein, preferences = prefs) + + @Test + fun `lunch is a rice-and-beans plate inside the slot budget`() { + val s = MealSuggester.suggest(inputs("lunch", eaten = 500.0)) + val names = s.items.map { it.name } + assertTrue(names.toString(), names.contains("Arroz branco") && names.contains("Feijão")) + assertTrue(s.items.any { it.proteinG >= 25 }) + assertTrue(s.totalKcal <= 700) // 35% of 2,000 + assertEquals(1500 - s.totalKcal, s.leavesKcal) + } + + @Test + fun `little left means a fruit, not a plate`() { + val s = MealSuggester.suggest(inputs("dinner", eaten = 1950.0)) + assertTrue(s.items.isEmpty()) + assertTrue(s.note!!.contains("50 kcal left")) + } + + @Test + fun `an agreed banana replaces vegetables at dinner when it fits`() { + val pref = FoodPreferenceEntity( + id = FoodPreferenceEntity.idFor("dinner", "banana", "prefer"), slot = "dinner", item = "banana", + action = "prefer", insteadOf = "vegetables", timesAgreed = 3, + ) + val s = MealSuggester.suggest(inputs("dinner", eaten = 1200.0, prefs = listOf(pref))) + val names = s.items.map { it.name } + assertTrue(names.contains("Banana")) + assertFalse(names.toString(), names.any { it == "Legumes cozidos" || it == "Salada verde com tomate" }) + assertEquals(listOf("banana at dinner instead of vegetables"), s.fromPreferences) + } + + @Test + fun `a preference that doesn't fit the budget is skipped`() { + val pref = FoodPreferenceEntity( + id = "x", slot = "snack", item = "açaí bowl", action = "prefer", kcal = 500.0, proteinG = 5.0, + ) + val s = MealSuggester.suggest(inputs("snack", eaten = 1500.0, prefs = listOf(pref))) + assertTrue(s.fromPreferences.isEmpty()) + assertTrue(s.totalKcal <= 240) // 12% of 2,000 + } + + @Test + fun `an avoided role never appears`() { + val avoid = FoodPreferenceEntity(id = "y", slot = "lunch", item = "beans", action = "avoid") + val s = MealSuggester.suggest(inputs("lunch", eaten = 400.0, prefs = listOf(avoid))) + assertFalse(s.items.any { it.name == "Feijão" }) + } + + @Test + fun `slots follow the clock and the card waits for a third of the day`() { + assertEquals("breakfast", MealSuggester.slotAt(LocalTime.of(7, 30))) + assertEquals("lunch", MealSuggester.slotAt(LocalTime.of(12, 0))) + assertEquals("snack", MealSuggester.slotAt(LocalTime.of(16, 0))) + assertEquals("dinner", MealSuggester.slotAt(LocalTime.of(20, 0))) + assertFalse(MealSuggester.shouldShow(2000.0, 500.0)) + assertTrue(MealSuggester.shouldShow(2000.0, 700.0)) + } +}