Modern Apps git

← Modern-Apps.git

health: add new tab for food logging

Commit
b091920a9c09fc2e22aec5ac5753ba5e3a615485
Author
Vayun Mathur <[email protected]>
When
2026-05-04 02:02 UTC (7 months ago)
Parents
fb9b309

Diff

health/build.gradle.kts
diff --git a/health/build.gradle.kts b/health/build.gradle.ktsindex 636b140118..a8610c0f9a 100644--- a/health/build.gradle.kts+++ b/health/build.gradle.kts@@ -19,4 +19,7 @@ dependencies {      // room     implementRoom(libs)++    // ktor+    implementKtor(libs) }\ No newline at end of file
health/src/main/AndroidManifest.xml
diff --git a/health/src/main/AndroidManifest.xml b/health/src/main/AndroidManifest.xmlindex c2612e7a8d..8bedb9cc50 100644--- a/health/src/main/AndroidManifest.xml+++ b/health/src/main/AndroidManifest.xml@@ -35,6 +35,8 @@     <uses-permission android:name="android.permission.health.READ_MINDFULNESS" />     <uses-permission android:name="android.permission.health.READ_HYDRATION" />     <uses-permission android:name="android.permission.health.READ_NUTRITION" />+    <uses-permission android:name="android.permission.health.WRITE_HYDRATION" />+    <uses-permission android:name="android.permission.health.WRITE_NUTRITION" />     <uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />      <!-- Medical Data -->
health/src/main/java/com/vayunmathur/health/MainActivity.kt
diff --git a/health/src/main/java/com/vayunmathur/health/MainActivity.kt b/health/src/main/java/com/vayunmathur/health/MainActivity.ktindex b6032a6ed3..232dfa13d9 100644--- a/health/src/main/java/com/vayunmathur/health/MainActivity.kt+++ b/health/src/main/java/com/vayunmathur/health/MainActivity.kt@@ -59,6 +59,8 @@ import com.vayunmathur.health.ui.MainPage import com.vayunmathur.health.ui.ImmunizationsPage import com.vayunmathur.health.ui.LabResultsPage import com.vayunmathur.health.ui.NutritionDetailsPage+import com.vayunmathur.health.ui.RecipeEditorPage+import com.vayunmathur.health.ui.RecipeManagementPage import com.vayunmathur.health.util.HealthAPI import com.vayunmathur.health.util.HealthSyncWorker import com.vayunmathur.library.ui.DynamicTheme@@ -83,7 +85,11 @@ val CLASSES = setOf(     MindfulnessSessionRecord::class, HydrationRecord::class, NutritionRecord::class, // TODO: readd these: SleepSessionRecord::class ) -val PERMISSIONS = CLASSES.map { HealthPermission.getReadPermission(it) }.toSet() + if (SdkExtensions.getExtensionVersion(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) >= 16) {setOf(+val PERMISSIONS = CLASSES.map { HealthPermission.getReadPermission(it) }.toSet() + +    setOf(+        HealthPermission.getWritePermission(NutritionRecord::class),+        HealthPermission.getWritePermission(HydrationRecord::class)+    ) + if (SdkExtensions.getExtensionVersion(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) >= 16) {setOf(     HealthPermissions.READ_MEDICAL_DATA_ALLERGIES_INTOLERANCES,     HealthPermissions.READ_MEDICAL_DATA_CONDITIONS,     HealthPermissions.READ_MEDICAL_DATA_LABORATORY_RESULTS,@@ -159,6 +165,12 @@ sealed interface Route: NavKey {     @Serializable     data object NutritionDetails: Route +    @Serializable+    data object RecipeManagement: Route++    @Serializable+    data class RecipeEditor(val recipeId: String? = null): Route+     @Serializable     data class BarChartDetails(val healthMetric: HealthMetricConfig): Route }@@ -172,8 +184,8 @@ fun Navigation() {             com.vayunmathur.library.util.BottomNavBar(                 backStack = backStack,                 pages = listOf(-                    com.vayunmathur.library.util.BottomBarItem("Home", Route.MainPage, R.drawable.baseline_favorite_24),-                    com.vayunmathur.library.util.BottomBarItem("Nutrition", Route.NutritionDetails, R.drawable.baseline_local_fire_department_24)+                    com.vayunmathur.library.util.BottomBarItem("Home", Route.MainPage, com.vayunmathur.library.R.drawable.favorite_24px),+                    com.vayunmathur.library.util.BottomBarItem("Nutrition", Route.NutritionDetails, com.vayunmathur.library.R.drawable.fire_24px)                 ),                 currentPage = backStack.last()             )@@ -191,6 +203,12 @@ fun Navigation() {         entry<Route.NutritionDetails> {             NutritionDetailsPage(backStack)         }+        entry<Route.RecipeManagement> {+            RecipeManagementPage(backStack)+        }+        entry<Route.RecipeEditor> {+            RecipeEditorPage(backStack, it.recipeId)+        }         entry<Route.BarChartDetails> {             BarChartDetails(backStack, it.healthMetric)         }
health/src/main/java/com/vayunmathur/health/data/FoodModels.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/FoodModels.kt b/health/src/main/java/com/vayunmathur/health/data/FoodModels.ktnew file mode 100644index 0000000000..f3a899f1a1--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/data/FoodModels.kt@@ -0,0 +1,91 @@+package com.vayunmathur.health.data++import androidx.room.Embedded+import androidx.room.Entity+import androidx.room.ForeignKey+import androidx.room.Index+import androidx.room.PrimaryKey+import java.util.UUID++@Entity+data class Ingredient(+    @PrimaryKey val id: String, // Unique identifier, possibly from API+    val originalName: String,+    val customName: String? = null,+    val isRecipe: Boolean = false,+    // Nutrition data is stored *per 100g* of the ingredient.+    @Embedded(prefix = "nutrition_") val nutritionData: NutritionData+) {+    val displayName: String+        get() = customName ?: originalName+}++@Entity+data class Recipe(+    @PrimaryKey val id: String = UUID.randomUUID().toString(),+    val name: String+)++@Entity(+    foreignKeys = [+        ForeignKey(+            entity = Ingredient::class,+            parentColumns = ["id"],+            childColumns = ["ingredientId"],+            onDelete = ForeignKey.CASCADE+        ),+        ForeignKey(+            entity = Recipe::class,+            parentColumns = ["id"],+            childColumns = ["recipeId"],+            onDelete = ForeignKey.CASCADE+        )+    ],+    indices = [+        Index("ingredientId"),+        Index("recipeId")+    ]+)+data class ServingUnit(+    @PrimaryKey val id: String = UUID.randomUUID().toString(),+    val ingredientId: String? = null,+    val recipeId: String? = null,+    val name: String, // e.g., "Cup", "Slice", "Serving", "Gram"+    val grams: Double // Equivalent amount in grams+)++@Entity(+    foreignKeys = [+        ForeignKey(+            entity = Recipe::class,+            parentColumns = ["id"],+            childColumns = ["recipeId"],+            onDelete = ForeignKey.CASCADE+        ),+        ForeignKey(+            entity = Ingredient::class,+            parentColumns = ["id"],+            childColumns = ["ingredientId"],+            // Restrict deletion of an ingredient if a recipe uses it.+            onDelete = ForeignKey.RESTRICT+        ),+        ForeignKey(+            entity = ServingUnit::class,+            parentColumns = ["id"],+            childColumns = ["unitId"],+            onDelete = ForeignKey.RESTRICT+        )+    ],+    indices = [+        Index("recipeId"),+        Index("ingredientId"),+        Index("unitId")+    ]+)+data class RecipeIngredient(+    @PrimaryKey val id: String = UUID.randomUUID().toString(),+    val recipeId: String,+    val ingredientId: String,+    val quantity: Double,+    val unitId: String+)
health/src/main/java/com/vayunmathur/health/data/Record.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/Record.kt b/health/src/main/java/com/vayunmathur/health/data/Record.ktindex 109aedd95b..d50adc0208 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -11,6 +11,9 @@ import androidx.room.Query import androidx.room.RoomDatabase import androidx.room.TypeConverter import androidx.room.TypeConverters+import androidx.room.Update+import androidx.room.Delete+import kotlinx.serialization.Serializable import kotlinx.coroutines.flow.Flow import java.time.Instant @@ -22,6 +25,7 @@ enum class RecordType {     Sleep, Mindfulness, Hydration, Nutrition } +@Serializable data class NutritionData(     val protein: Double = 0.0,     val carbohydrates: Double = 0.0,@@ -62,7 +66,8 @@ data class NutritionData(     val vitaminD: Double = 0.0,     val vitaminE: Double = 0.0,     val vitaminK: Double = 0.0,-    val zinc: Double = 0.0+    val zinc: Double = 0.0,+    val calories: Double = 0.0 )  @Entity(indices = [Index(value = ["type", "startTime", "endTime"])])@@ -75,6 +80,7 @@ data class Record(     val value: Double,     val secondaryValue: Double = 0.0,     @Embedded(prefix = "nutrition_") val nutritionData: NutritionData? = null,+    val metadata: String? = null,     @PrimaryKey val primaryKey: String = "$id-$index", ) @@ -95,7 +101,7 @@ interface HealthDao {     @Query("SELECT * FROM Record WHERE type = :type ORDER BY startTime DESC LIMIT 1")     suspend fun getLastRecord(type: RecordType): Record? -    @Query("SELECT COALESCE(SUM(value), 0.0) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    @Query("SELECT COALESCE(SUM(CASE WHEN :type = 'Nutrition' THEN nutrition_calories ELSE value END), 0.0) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")     fun sumInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double>          @Query("SELECT COALESCE(SUM(nutrition_protein), 0.0) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")@@ -316,11 +322,75 @@ interface HealthDao {         val totalValue: Double,         val totalValue2: Double     )++    // Food Logger Methods+    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun insertIngredient(ingredient: Ingredient)++    @Update+    suspend fun updateIngredient(ingredient: Ingredient)++    @Delete+    suspend fun deleteIngredient(ingredient: Ingredient)++    @Query("SELECT * FROM Ingredient ORDER BY originalName ASC")+    suspend fun getAllIngredients(): List<Ingredient>++    @Query("SELECT * FROM Ingredient ORDER BY originalName ASC")+    fun getAllIngredientsFlow(): Flow<List<Ingredient>>++    @Query("SELECT * FROM Ingredient WHERE isRecipe = 1 ORDER BY originalName ASC")+    fun getIngredientsAsRecipesFlow(): Flow<List<Ingredient>>++    @Query("SELECT * FROM Ingredient WHERE id = :id")+    suspend fun getIngredient(id: String): Ingredient?++    @Query("SELECT * FROM Ingredient WHERE originalName LIKE '%' || :query || '%' OR customName LIKE '%' || :query || '%'")+    suspend fun searchIngredients(query: String): List<Ingredient>++    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun insertRecipe(recipe: Recipe)++    @Update+    suspend fun updateRecipe(recipe: Recipe)++    @Delete+    suspend fun deleteRecipe(recipe: Recipe)++    @Query("SELECT * FROM Recipe ORDER BY name ASC")+    fun getAllRecipesFlow(): Flow<List<Recipe>>++    @Query("SELECT * FROM Recipe WHERE id = :id")+    suspend fun getRecipe(id: String): Recipe?++    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun insertServingUnit(unit: ServingUnit)++    @Delete+    suspend fun deleteServingUnit(unit: ServingUnit)++    @Query("SELECT * FROM ServingUnit WHERE ingredientId = :ingredientId")+    suspend fun getUnitsForIngredient(ingredientId: String): List<ServingUnit>++    @Query("SELECT * FROM ServingUnit WHERE recipeId = :recipeId")+    suspend fun getUnitsForRecipe(recipeId: String): List<ServingUnit>++    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun insertRecipeIngredient(recipeIngredient: RecipeIngredient)++    @Delete+    suspend fun deleteRecipeIngredient(recipeIngredient: RecipeIngredient)++    @Query("SELECT * FROM RecipeIngredient WHERE recipeId = :recipeId")+    suspend fun getIngredientsForRecipe(recipeId: String): List<RecipeIngredient>+    +    @Query("SELECT * FROM RecipeIngredient WHERE recipeId = :recipeId")+    fun getIngredientsForRecipeFlow(recipeId: String): Flow<List<RecipeIngredient>> }  @Database(-    entities = [Record::class],-    version = 1,+    entities = [Record::class, Ingredient::class, Recipe::class, ServingUnit::class, RecipeIngredient::class],+    version = 3,     exportSchema = false ) @TypeConverters(Converters::class)
health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt b/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.ktnew file mode 100644index 0000000000..6ce5db5848--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt@@ -0,0 +1,369 @@+package com.vayunmathur.health.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Button+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ExposedDropdownMenuBox+import androidx.compose.material3.ExposedDropdownMenuDefaults+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import com.vayunmathur.health.data.Ingredient+import com.vayunmathur.health.data.NutritionData+import com.vayunmathur.health.data.Recipe+import com.vayunmathur.health.data.Record+import com.vayunmathur.health.data.RecordType+import com.vayunmathur.health.util.HealthAPI+import java.time.Instant+import java.util.UUID+import kotlinx.coroutines.launch++enum class HydrationUnit(val displayName: String, val toLiters: Double) {+    Liters("Liters", 1.0),+    Milliliters("Milliliters", 0.001),+    Ounces("Ounces", 0.0295735),+    Cups("Cups", 0.236588)+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun LogHydrationDialog(initialTime: Instant? = null, onDismiss: () -> Unit) {+    var quantityStr by remember { mutableStateOf("") }+    var selectedUnit by remember { mutableStateOf(HydrationUnit.Liters) }+    var unitExpanded by remember { mutableStateOf(false) }+    val scope = rememberCoroutineScope()++    val quantity = quantityStr.toDoubleOrNull()+    val isValid = quantity != null && quantity > 0++    AlertDialog(+            onDismissRequest = onDismiss,+            title = { Text("Log Hydration") },+            text = {+                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+                    OutlinedTextField(+                            value = quantityStr,+                            onValueChange = { quantityStr = it },+                            label = { Text("Quantity") },+                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+                            modifier = Modifier.fillMaxWidth(),+                            trailingIcon = {+                                ExposedDropdownMenuBox(+                                        expanded = unitExpanded,+                                        onExpandedChange = { unitExpanded = !unitExpanded }+                                ) {+                                    Row(+                                            modifier =+                                                    Modifier.menuAnchor()+                                                            .clickable { unitExpanded = true }+                                                            .padding(end = 8.dp),+                                            verticalAlignment = Alignment.CenterVertically+                                    ) {+                                        Text(+                                                selectedUnit.displayName,+                                                style = MaterialTheme.typography.bodyMedium+                                        )+                                        ExposedDropdownMenuDefaults.TrailingIcon(+                                                expanded = unitExpanded+                                        )+                                    }+                                    ExposedDropdownMenu(+                                            expanded = unitExpanded,+                                            onDismissRequest = { unitExpanded = false }+                                    ) {+                                        HydrationUnit.entries.forEach { unit ->+                                            DropdownMenuItem(+                                                    text = { Text(unit.displayName) },+                                                    onClick = {+                                                        selectedUnit = unit+                                                        unitExpanded = false+                                                    }+                                            )+                                        }+                                    }+                                }+                            }+                    )+                }+            },+            confirmButton = {+                Button(+                        enabled = isValid,+                        onClick = {+                            if (quantity != null) {+                                scope.launch {+                                    val time = initialTime ?: Instant.now()+                                    val record =+                                            Record(+                                                    id = UUID.randomUUID().toString(),+                                                    index = 0,+                                                    type = RecordType.Hydration,+                                                    startTime = time,+                                                    endTime = time,+                                                    value =+                                                            quantity *+                                                                    selectedUnit+                                                                            .toLiters, // Convert to+                                                    // Liters+                                                    metadata = "Hydration"+                                            )+                                    HealthAPI.db.healthDao().upsert(listOf(record))+                                    HealthAPI.writeHealthRecord(record)+                                    onDismiss()+                                }+                            }+                        }+                ) { Text("Save") }+            },+            dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }+    )+}++sealed class Loggable {+    abstract val id: String+    abstract val name: String++    data class RecipeWrapper(val recipe: Recipe) : Loggable() {+        override val id = recipe.id+        override val name = recipe.name+    }++    data class IngredientWrapper(val ingredient: Ingredient) : Loggable() {+        override val id = ingredient.id+        override val name = ingredient.displayName+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun LogMealDialog(initialTime: Instant? = null, onDismiss: () -> Unit) {+    val recipes by HealthAPI.db.healthDao().getAllRecipesFlow().collectAsState(emptyList())+    val ingredientRecipes by+            HealthAPI.db.healthDao().getIngredientsAsRecipesFlow().collectAsState(emptyList())++    val allLoggables =+            remember(recipes, ingredientRecipes) {+                recipes.map { Loggable.RecipeWrapper(it) } ++                        ingredientRecipes.map { Loggable.IngredientWrapper(it) }+            }++    var selectedLoggable by remember { mutableStateOf<Loggable?>(null) }+    var quantityStr by remember { mutableStateOf("1") }+    var expanded by remember { mutableStateOf(false) }+    val scope = rememberCoroutineScope()++    val quantity = quantityStr.toDoubleOrNull()+    val isValid = selectedLoggable != null && quantity != null && quantity > 0++    AlertDialog(+            onDismissRequest = onDismiss,+            title = { Text("Log Meal") },+            text = {+                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+                    ExposedDropdownMenuBox(+                            expanded = expanded,+                            onExpandedChange = { expanded = !expanded }+                    ) {+                        OutlinedTextField(+                                value = selectedLoggable?.name ?: "Select Recipe",+                                onValueChange = {},+                                readOnly = true,+                                trailingIcon = {+                                    ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)+                                },+                                modifier = Modifier.menuAnchor().fillMaxWidth()+                        )+                        ExposedDropdownMenu(+                                expanded = expanded,+                                onDismissRequest = { expanded = false }+                        ) {+                            allLoggables.sortedBy { it.name }.forEach { loggable ->+                                DropdownMenuItem(+                                        text = {+                                            Row(verticalAlignment = Alignment.CenterVertically) {+                                                Text(loggable.name)+                                                if (loggable is Loggable.IngredientWrapper) {+                                                    Spacer(Modifier.width(4.dp))+                                                    Text(+                                                            "(Ingredient)",+                                                            style =+                                                                    MaterialTheme.typography+                                                                            .bodySmall,+                                                            color =+                                                                    MaterialTheme.colorScheme+                                                                            .outline+                                                    )+                                                }+                                            }+                                        },+                                        onClick = {+                                            selectedLoggable = loggable+                                            expanded = false+                                        }+                                )+                            }+                        }+                    }++                    OutlinedTextField(+                            value = quantityStr,+                            onValueChange = { quantityStr = it },+                            label = { Text("Quantity (Servings / 100g)") },+                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+                            modifier = Modifier.fillMaxWidth()+                    )+                }+            },+            confirmButton = {+                Button(+                        enabled = isValid,+                        onClick = {+                            if (quantity != null && selectedLoggable != null) {+                                scope.launch {+                                    val time = initialTime ?: Instant.now()+                                    val nutrition: NutritionData =+                                            when (val loggable = selectedLoggable!!) {+                                                is Loggable.RecipeWrapper -> {+                                                    val ingredients =+                                                            HealthAPI.db+                                                                    .healthDao()+                                                                    .getIngredientsForRecipe(+                                                                            loggable.id+                                                                    )+                                                    var protein = 0.0+                                                    var carbs = 0.0+                                                    var fat = 0.0+                                                    var fiber = 0.0+                                                    var sugar = 0.0+                                                    var sodium = 0.0+                                                    var kcal = 0.0++                                                    ingredients.forEach { ri ->+                                                        val ing =+                                                                HealthAPI.db+                                                                        .healthDao()+                                                                        .getIngredient(+                                                                                ri.ingredientId+                                                                        )+                                                        if (ing != null) {+                                                            val units =+                                                                    HealthAPI.db+                                                                            .healthDao()+                                                                            .getUnitsForIngredient(+                                                                                    ing.id+                                                                            )+                                                            val unit =+                                                                    units.find {+                                                                        it.id == ri.unitId+                                                                    }+                                                            val grams = unit?.grams ?: 1.0+                                                            val totalGrams =+                                                                    ri.quantity * grams * quantity++                                                            protein +=+                                                                    (ing.nutritionData.protein /+                                                                            100.0) * totalGrams+                                                            carbs +=+                                                                    (ing.nutritionData+                                                                            .carbohydrates /+                                                                            100.0) * totalGrams+                                                            fat +=+                                                                    (ing.nutritionData.fat /+                                                                            100.0) * totalGrams+                                                            fiber +=+                                                                    (ing.nutritionData.fiber /+                                                                            100.0) * totalGrams+                                                            sugar +=+                                                                    (ing.nutritionData.sugar /+                                                                            100.0) * totalGrams+                                                            sodium +=+                                                                    (ing.nutritionData.sodium /+                                                                            100.0) * totalGrams+                                                            kcal +=+                                                                    (ing.nutritionData.calories /+                                                                            100.0) * totalGrams+                                                        }+                                                    }+                                                    NutritionData(+                                                            protein,+                                                            carbs,+                                                            fat,+                                                            fiber,+                                                            sugar,+                                                            sodium,+                                                            calories = kcal+                                                    )+                                                }+                                                is Loggable.IngredientWrapper -> {+                                                    // For single ingredients marked as recipe,+                                                    // quantity is treated as 100g servings+                                                    val ing = loggable.ingredient+                                                    NutritionData(+                                                            protein =+                                                                    ing.nutritionData.protein *+                                                                            quantity,+                                                            carbohydrates =+                                                                    ing.nutritionData+                                                                            .carbohydrates *+                                                                            quantity,+                                                            fat = ing.nutritionData.fat * quantity,+                                                            fiber =+                                                                    ing.nutritionData.fiber *+                                                                            quantity,+                                                            sugar =+                                                                    ing.nutritionData.sugar *+                                                                            quantity,+                                                            sodium =+                                                                    ing.nutritionData.sodium *+                                                                            quantity,+                                                            calories =+                                                                    ing.nutritionData.calories *+                                                                            quantity+                                                    )+                                                }+                                            }++                                    val record =+                                            Record(+                                                    id = UUID.randomUUID().toString(),+                                                    index = 0,+                                                    type = RecordType.Nutrition,+                                                    startTime = time,+                                                    endTime = time,+                                                    value = 0.0,+                                                    nutritionData = nutrition,+                                                    metadata = selectedLoggable?.name+                                            )+                                    HealthAPI.db.healthDao().upsert(listOf(record))+                                    HealthAPI.writeHealthRecord(record)+                                    onDismiss()+                                }+                            }+                        }+                ) { Text("Save") }+            },+            dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }+    )+}
health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.kt b/health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.ktindex 8d42a4e7f4..5df5772004 100644--- a/health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.kt@@ -9,10 +9,12 @@ import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp@@ -23,10 +25,12 @@ import com.vayunmathur.health.util.HealthAPI import com.vayunmathur.health.util.displayString import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.round+import com.vayunmathur.library.ui.* import kotlin.time.Clock import kotlin.time.Duration.Companion.hours import kotlin.time.Instant import kotlinx.datetime.*+import kotlinx.coroutines.launch  data class NutrientDV(         val name: String,@@ -162,11 +166,66 @@ fun NutritionDetailsPage(backStack: NavBackStack<Route>) {         )     } +    var showFabMenu by remember { androidx.compose.runtime.mutableStateOf(false) }+    var showHydrationDialog by remember { androidx.compose.runtime.mutableStateOf(false) }+    var showMealDialog by remember { androidx.compose.runtime.mutableStateOf(false) }++    val selectedDay = remember(pagerState.currentPage) {+        today.minus(initialPage - pagerState.currentPage, DateTimeUnit.DAY)+    }+    val selectedDayInstant = remember(selectedDay) {+        if (selectedDay == today) null+        else java.time.Instant.ofEpochMilli(selectedDay.atStartOfDayIn(tz).toEpochMilliseconds())+    }++    if (showHydrationDialog) {+        LogHydrationDialog(initialTime = selectedDayInstant, onDismiss = { showHydrationDialog = false })+    }+    if (showMealDialog) {+        LogMealDialog(initialTime = selectedDayInstant, onDismiss = { showMealDialog = false })+    }+     Scaffold(             topBar = {                 TopAppBar(                         title = { Text(stringResource(R.string.label_nutrition_details)) },                 )+            },+            floatingActionButton = {+                Column(horizontalAlignment = Alignment.End) {+                    if (showFabMenu) {+                        ExtendedFloatingActionButton(+                            onClick = {+                                showFabMenu = false+                                showHydrationDialog = true+                            },+                            icon = { IconFire() },+                            text = { Text("Log Hydration") },+                            modifier = Modifier.padding(bottom = 8.dp)+                        )+                        ExtendedFloatingActionButton(+                            onClick = {+                                showFabMenu = false+                                showMealDialog = true+                            },+                            icon = { IconFire() },+                            text = { Text("Log Meal") },+                            modifier = Modifier.padding(bottom = 8.dp)+                        )+                        ExtendedFloatingActionButton(+                            onClick = {+                                showFabMenu = false+                                backStack.add(Route.RecipeManagement)+                            },+                            icon = { IconAdd() },+                            text = { Text("Create/Edit Recipes") },+                            modifier = Modifier.padding(bottom = 8.dp)+                        )+                    }+                    FloatingActionButton(onClick = { showFabMenu = !showFabMenu }) {+                        IconAdd()+                    }+                }             }     ) { padding ->         HorizontalPager(state = pagerState, modifier = Modifier.fillMaxSize()) { page ->@@ -174,8 +233,16 @@ fun NutritionDetailsPage(backStack: NavBackStack<Route>) {             val dayStart = day.atStartOfDayIn(tz)             val dayEnd = dayStart.plus(24.hours) -            val totalCalories by-                    HealthAPI.sumInRange(RecordType.Nutrition, dayStart, dayEnd).collectAsState(0.0)+            val totalCalories by HealthAPI.sumInRange(RecordType.Nutrition, dayStart, dayEnd).collectAsState(0.0)+            val totalProtein by HealthAPI.sumProteinInRange(RecordType.Nutrition, dayStart, dayEnd).collectAsState(0.0)+            val totalCarbs by HealthAPI.sumCarbsInRange(RecordType.Nutrition, dayStart, dayEnd).collectAsState(0.0)+            val totalFat by HealthAPI.sumFatInRange(RecordType.Nutrition, dayStart, dayEnd).collectAsState(0.0)++            val loggedMeals by HealthAPI.getAllRecordsInRange(RecordType.Nutrition, dayStart, dayEnd).collectAsState(emptyList())+            val loggedHydration by HealthAPI.getAllRecordsInRange(RecordType.Hydration, dayStart, dayEnd).collectAsState(emptyList())+            val allLogs = (loggedMeals + loggedHydration).sortedByDescending { it.startTime }+            +            val scope = androidx.compose.runtime.rememberCoroutineScope()              LazyColumn(                     modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),@@ -188,29 +255,120 @@ fun NutritionDetailsPage(backStack: NavBackStack<Route>) {                             horizontalAlignment = Alignment.CenterHorizontally                     ) {                         Text(-                                text =-                                        if (day == today) stringResource(R.string.label_today)-                                        else day.displayString(),+                                text = if (day == today) stringResource(R.string.label_today) else day.displayString(),                                 style = MaterialTheme.typography.titleMedium,                                 color = MaterialTheme.colorScheme.secondary                         )+                        Spacer(modifier = Modifier.height(16.dp))+                        +                        // Compact Summary Grid+                        Card(+                            modifier = Modifier.fillMaxWidth(),+                            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)+                        ) {+                            Row(+                                modifier = Modifier.fillMaxWidth().padding(16.dp),+                                horizontalArrangement = Arrangement.SpaceEvenly,+                                verticalAlignment = Alignment.CenterVertically+                            ) {+                                Column(horizontalAlignment = Alignment.CenterHorizontally) {+                                    Text("Calories", style = MaterialTheme.typography.labelMedium)+                                    Text("${totalCalories.round(0).toInt()}/2000", style = MaterialTheme.typography.titleMedium)+                                }+                                Column(horizontalAlignment = Alignment.CenterHorizontally) {+                                    Text("Protein", style = MaterialTheme.typography.labelMedium)+                                    Text("${totalProtein.round(0).toInt()}/50g", style = MaterialTheme.typography.titleSmall)+                                }+                                Column(horizontalAlignment = Alignment.CenterHorizontally) {+                                    Text("Carbs", style = MaterialTheme.typography.labelMedium)+                                    Text("${totalCarbs.round(0).toInt()}/275g", style = MaterialTheme.typography.titleSmall)+                                }+                                Column(horizontalAlignment = Alignment.CenterHorizontally) {+                                    Text("Fat", style = MaterialTheme.typography.labelMedium)+                                    Text("${totalFat.round(0).toInt()}/78g", style = MaterialTheme.typography.titleSmall)+                                }+                            }+                        }+                    }+                }+++                if (allLogs.isNotEmpty()) {+                    item {                         Text(-                                text =-                                        stringResource(-                                                R.string.unit_kcal_format,-                                                totalCalories.round(0).toLong().toString()-                                        ),-                                style = MaterialTheme.typography.displayMedium,-                                fontWeight = FontWeight.Light-                        )-                        Text(-                                text = stringResource(R.string.total_energy_intake),-                                style = MaterialTheme.typography.labelMedium,-                                color = MaterialTheme.colorScheme.outline+                            text = "Logged Items",+                            style = MaterialTheme.typography.titleSmall,+                            modifier = Modifier.padding(top = 8.dp, bottom = 4.dp)                         )                     }+                    items(allLogs) { log ->+                        Card(+                            modifier = Modifier.fillMaxWidth(),+                            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)+                        ) {+                            Row(+                                modifier = Modifier.fillMaxWidth().padding(12.dp),+                                horizontalArrangement = Arrangement.SpaceBetween,+                                verticalAlignment = Alignment.CenterVertically+                            ) {+                                Column(modifier = Modifier.weight(1f)) {+                                    Text(+                                        text = log.metadata ?: (if (log.type == RecordType.Hydration) "Hydration" else "Meal"),+                                        style = MaterialTheme.typography.bodyLarge,+                                        fontWeight = FontWeight.Bold+                                    )+                                    if (log.type == RecordType.Nutrition) {+                                        Text(+                                            text = "${log.nutritionData?.calories?.round(0)?.toInt() ?: 0} kcal โ€ข ${log.nutritionData?.protein?.round(1) ?: 0}g P โ€ข ${log.nutritionData?.carbohydrates?.round(1) ?: 0}g C โ€ข ${log.nutritionData?.fat?.round(1) ?: 0}g F",+                                            style = MaterialTheme.typography.bodySmall,+                                            color = MaterialTheme.colorScheme.outline+                                        )+                                    } else {+                                        Text(+                                            text = "${log.value.round(2)} L",+                                            style = MaterialTheme.typography.bodySmall,+                                            color = MaterialTheme.colorScheme.outline+                                        )+                                    }+                                }+                                IconButton(onClick = { scope.launch { HealthAPI.deleteRecord(log) } }) {+                                    Icon(+                                        painter = painterResource(R.drawable.baseline_delete_24),+                                        contentDescription = "Unlog",+                                        tint = MaterialTheme.colorScheme.error+                                    )+                                }+                            }+                        }+                    }+                }++                item {+                    Text(+                        text = "Nutrient Breakdown",+                        style = MaterialTheme.typography.titleSmall,+                        modifier = Modifier.padding(top = 16.dp, bottom = 4.dp)+                    )+                }+                +                // Other nutrients (excluding Protein, Carbs, Fat since they are in the summary)+                val otherNutrients = nutrients.filter { it.name !in listOf("Protein", "Carbohydrates", "Fat") }+                items(otherNutrients.chunked(2)) { rowNutrients ->+                    Row(+                        modifier = Modifier.fillMaxWidth(),+                        horizontalArrangement = Arrangement.spacedBy(8.dp)+                    ) {+                        rowNutrients.forEach { nutrient ->+                            Box(modifier = Modifier.weight(1f)) {+                                NutrientProgressCard(nutrient, dayStart, dayEnd)+                            }+                        }+                        // Fill remaining space if row has less than 2 items+                        repeat(2 - rowNutrients.size) {+                            Spacer(modifier = Modifier.weight(1f))+                        }+                    }                 }-                items(nutrients) { nutrient -> NutrientProgressCard(nutrient, dayStart, dayEnd) }             }         }     }@@ -229,7 +387,7 @@ fun NutrientProgressCard(nutrient: NutrientDV, start: Instant, end: Instant) {                                     MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)                     )     ) {-        Column(modifier = Modifier.padding(12.dp)) {+        Column(modifier = Modifier.padding(8.dp)) {             Row(                     modifier = Modifier.fillMaxWidth(),                     horizontalArrangement = Arrangement.SpaceBetween,@@ -237,24 +395,19 @@ fun NutrientProgressCard(nutrient: NutrientDV, start: Instant, end: Instant) {             ) {                 Text(                         text = nutrient.name,-                        style = MaterialTheme.typography.bodyMedium,-                        fontWeight = FontWeight.SemiBold+                        style = MaterialTheme.typography.bodySmall,+                        fontWeight = FontWeight.SemiBold,+                        modifier = Modifier.weight(1f)                 )                 Text(-                        text =-                                stringResource(-                                        R.string.nutrient_progress_format,-                                        currentAmount.round(1).toString(),-                                        nutrient.dailyValue.round(0).toLong(),-                                        nutrient.unit-                                ),-                        style = MaterialTheme.typography.bodySmall+                        text = "${currentAmount.round(1)}/${nutrient.dailyValue.round(0).toInt()}${nutrient.unit}",+                        style = MaterialTheme.typography.labelSmall                 )             }-            Spacer(modifier = Modifier.height(6.dp))+            Spacer(modifier = Modifier.height(4.dp))             LinearProgressIndicator(                     progress = { progress },-                    modifier = Modifier.fillMaxWidth().height(6.dp),+                    modifier = Modifier.fillMaxWidth().height(4.dp),                     color =                             if (progress >= 1f) Color(0xFF4CAF50)                             else MaterialTheme.colorScheme.primary,
health/src/main/java/com/vayunmathur/health/ui/RecipeManagementPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/RecipeManagementPage.kt b/health/src/main/java/com/vayunmathur/health/ui/RecipeManagementPage.ktnew file mode 100644index 0000000000..79acadb63c--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/ui/RecipeManagementPage.kt@@ -0,0 +1,428 @@+package com.vayunmathur.health.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material3.*+import androidx.compose.runtime.*+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.health.R+import com.vayunmathur.health.Route+import com.vayunmathur.health.data.*+import com.vayunmathur.health.util.FoodSearchAPI+import com.vayunmathur.health.util.HealthAPI+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ui.*+import kotlinx.coroutines.launch+import java.util.UUID++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun RecipeManagementPage(backStack: NavBackStack<Route>) {+    var selectedTab by remember { mutableIntStateOf(0) }+    val scope = rememberCoroutineScope()+    var showIngredientSearch by remember { mutableStateOf(false) }++    val recipes by HealthAPI.db.healthDao().getAllRecipesFlow().collectAsState(emptyList())+    val ingredients by HealthAPI.db.healthDao().getAllIngredientsFlow().collectAsState(emptyList())++    val isListEmpty = if (selectedTab == 0) recipes.isEmpty() else ingredients.isEmpty()++    if (showIngredientSearch) {+        IngredientSearchDialog(+            onDismiss = { showIngredientSearch = false },+            onIngredientSelected = { ingredient ->+                scope.launch {+                    HealthAPI.db.healthDao().insertIngredient(ingredient)+                    showIngredientSearch = false+                }+            }+        )+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("Recipe & Ingredients") }+            )+        },+        floatingActionButton = {+            if (!isListEmpty) {+                FloatingActionButton(onClick = { +                    if (selectedTab == 0) {+                        backStack.add(Route.RecipeEditor()) +                    } else {+                        showIngredientSearch = true+                    }+                }) {+                    IconAdd()+                }+            }+        }+    ) { padding ->+        Column(modifier = Modifier.padding(padding).fillMaxSize()) {+            TabRow(selectedTabIndex = selectedTab) {+                Tab(selected = selectedTab == 0, onClick = { selectedTab = 0 }, text = { Text("Recipes") })+                Tab(selected = selectedTab == 1, onClick = { selectedTab = 1 }, text = { Text("Ingredients") })+            }++            if (isListEmpty) {+                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+                    Button(onClick = {+                        if (selectedTab == 0) {+                            backStack.add(Route.RecipeEditor())+                        } else {+                            showIngredientSearch = true+                        }+                    }) {+                        IconAdd()+                        Spacer(Modifier.width(8.dp))+                        Text(if (selectedTab == 0) "Create your first recipe" else "Add your first ingredient")+                    }+                }+            } else {+                if (selectedTab == 0) {+                    RecipesList(recipes) { recipeId -> backStack.add(Route.RecipeEditor(recipeId)) }+                } else {+                    IngredientsList(ingredients)+                }+            }+        }+    }+}++@Composable+fun RecipesList(recipes: List<Recipe>, onRecipeClick: (String) -> Unit) {+    val scope = rememberCoroutineScope()++    LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+        items(recipes) { recipe ->+            Card(+                modifier = Modifier.fillMaxWidth().clickable { onRecipeClick(recipe.id) }+            ) {+                Row(modifier = Modifier.padding(16.dp).fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+                    Text(recipe.name, style = MaterialTheme.typography.titleMedium)+                    IconButton(onClick = {+                        scope.launch {+                            HealthAPI.db.healthDao().deleteRecipe(recipe)+                        }+                    }) {+                        IconDelete()+                    }+                }+            }+        }+    }+}++@Composable+fun IngredientsList(ingredients: List<Ingredient>) {+    val scope = rememberCoroutineScope()+    var editingIngredient by remember { mutableStateOf<Ingredient?>(null) }+    +    if (editingIngredient != null) {+        var customName by remember { mutableStateOf(editingIngredient!!.customName ?: "") }+        AlertDialog(+            onDismissRequest = { editingIngredient = null },+            title = { Text("Rename Ingredient") },+            text = {+                Column {+                    Text("Original: ${editingIngredient!!.originalName}", style = MaterialTheme.typography.bodySmall)+                    Spacer(Modifier.height(8.dp))+                    OutlinedTextField(+                        value = customName,+                        onValueChange = { customName = it },+                        label = { Text("Custom Name") }+                    )+                }+            },+            confirmButton = {+                Button(onClick = {+                    scope.launch {+                        val newIng = editingIngredient!!.copy(customName = customName.ifBlank { null })+                        HealthAPI.db.healthDao().updateIngredient(newIng)+                        editingIngredient = null+                    }+                }) { Text("Save") }+            },+            dismissButton = {+                TextButton(onClick = { editingIngredient = null }) { Text("Cancel") }+            }+        )+    }++    LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+        items(ingredients) { ingredient ->+            Card(modifier = Modifier.fillMaxWidth().clickable { editingIngredient = ingredient }) {+                Row(modifier = Modifier.padding(16.dp).fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+                    Column(modifier = Modifier.weight(1f)) {+                        Text(ingredient.displayName, style = MaterialTheme.typography.titleMedium)+                        if (ingredient.customName != null) {+                            Text("Original: ${ingredient.originalName}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)+                        }+                    }+                    Row(verticalAlignment = Alignment.CenterVertically) {+                        IconButton(onClick = {+                            scope.launch {+                                val newIng = ingredient.copy(isRecipe = !ingredient.isRecipe)+                                HealthAPI.db.healthDao().updateIngredient(newIng)+                            }+                        }) {+                            if (ingredient.isRecipe) IconFire() else Icon(painterResource(R.drawable.baseline_local_fire_department_24), "Mark as Recipe", tint = MaterialTheme.colorScheme.outline)+                        }+                        IconButton(onClick = {+                            scope.launch {+                                try {+                                    HealthAPI.db.healthDao().deleteIngredient(ingredient)+                                } catch (e: Exception) {+                                    // SQLiteConstraintException if used in recipe+                                }+                            }+                        }) {+                            IconDelete()+                        }+                    }+                }+            }+        }+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun RecipeEditorPage(backStack: NavBackStack<Route>, recipeId: String? = null) {+    var recipeName by remember { mutableStateOf("") }+    var recipeIngredients by remember { mutableStateOf(listOf<RecipeIngredientData>()) }+    var showSearch by remember { mutableStateOf(false) }+    val scope = rememberCoroutineScope()++    // Load existing recipe if editing+    LaunchedEffect(recipeId) {+        if (recipeId != null) {+            val recipe = HealthAPI.db.healthDao().getRecipe(recipeId)+            if (recipe != null) {+                recipeName = recipe.name+                val ingredients = HealthAPI.db.healthDao().getIngredientsForRecipe(recipeId)+                recipeIngredients = ingredients.mapNotNull { ri ->+                    val ing = HealthAPI.db.healthDao().getIngredient(ri.ingredientId)+                    val units = HealthAPI.db.healthDao().getUnitsForIngredient(ri.ingredientId)+                    val unit = units.find { it.id == ri.unitId }+                    if (ing != null && unit != null) {+                        RecipeIngredientData(ing, unit, ri.quantity)+                    } else null+                }+            }+        }+    }++    if (showSearch) {+        IngredientSearchDialog(+            includeLocal = true,+            onDismiss = { showSearch = false },+            onIngredientSelected = { ingredient ->+                // Add default 100g unit+                val unit = ServingUnit(id = UUID.randomUUID().toString(), ingredientId = ingredient.id, name = "g", grams = 1.0)+                recipeIngredients = recipeIngredients + RecipeIngredientData(ingredient, unit, 100.0)+                showSearch = false+            }+        )+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text(if (recipeId == null) "Create Recipe" else "Edit Recipe") },+                navigationIcon = {+                    IconNavigation(backStack)+                }+            )+        }+    ) { padding ->+        Column(modifier = Modifier.padding(padding).padding(16.dp).fillMaxSize(), verticalArrangement = Arrangement.spacedBy(16.dp)) {+            OutlinedTextField(+                value = recipeName,+                onValueChange = { recipeName = it },+                label = { Text("Recipe Name") },+                modifier = Modifier.fillMaxWidth()+            )+            +            Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+                Text("Ingredients", style = MaterialTheme.typography.titleMedium)+                TextButton(onClick = { showSearch = true }) {+                    IconAdd()+                    Spacer(Modifier.width(4.dp))+                    Text("Add")+                }+            }++            LazyColumn(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                items(recipeIngredients) { riData ->+                    Card(modifier = Modifier.fillMaxWidth()) {+                        Row(modifier = Modifier.padding(8.dp).fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+                            Column(modifier = Modifier.weight(1f)) {+                                Text(riData.ingredient.displayName, style = MaterialTheme.typography.bodyLarge)+                                Text("${riData.quantity} ${riData.unit.name}", style = MaterialTheme.typography.bodySmall)+                            }+                            IconButton(onClick = {+                                recipeIngredients = recipeIngredients - riData+                            }) {+                                IconDelete()+                            }+                        }+                    }+                }+            }++            Button(+                onClick = {+                    scope.launch {+                        val id = recipeId ?: UUID.randomUUID().toString()+                        val recipe = Recipe(id = id, name = recipeName)+                        HealthAPI.db.healthDao().insertRecipe(recipe)+                        +                        // Clear old ingredients if editing+                        if (recipeId != null) {+                            val oldIngredients = HealthAPI.db.healthDao().getIngredientsForRecipe(recipeId)+                            oldIngredients.forEach { HealthAPI.db.healthDao().deleteRecipeIngredient(it) }+                        }++                        recipeIngredients.forEach { riData ->+                            HealthAPI.db.healthDao().insertIngredient(riData.ingredient)+                            HealthAPI.db.healthDao().insertServingUnit(riData.unit)+                            val ri = RecipeIngredient(+                                id = UUID.randomUUID().toString(),+                                recipeId = id,+                                ingredientId = riData.ingredient.id,+                                quantity = riData.quantity,+                                unitId = riData.unit.id+                            )+                            HealthAPI.db.healthDao().insertRecipeIngredient(ri)+                        }+                        backStack.pop()+                    }+                },+                modifier = Modifier.fillMaxWidth(),+                enabled = recipeName.isNotBlank() && recipeIngredients.isNotEmpty()+            ) {+                Text("Save Recipe")+            }+        }+    }+}++data class RecipeIngredientData(+    val ingredient: Ingredient,+    val unit: ServingUnit,+    var quantity: Double+)++@Composable+fun IngredientSearchDialog(+    includeLocal: Boolean = false,+    onDismiss: () -> Unit,+    onIngredientSelected: (Ingredient) -> Unit+) {+    var query by remember { mutableStateOf("") }+    var remoteResults by remember { mutableStateOf(listOf<FoodSearchAPI.SearchResult>()) }+    var localResults by remember { mutableStateOf(listOf<Ingredient>()) }+    var isSearching by remember { mutableStateOf(false) }+    var isFetchingData by remember { mutableStateOf(false) }+    val scope = rememberCoroutineScope()++    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text("Search Ingredient") },+        text = {+            Column(modifier = Modifier.fillMaxWidth().height(400.dp)) {+                Row(verticalAlignment = Alignment.CenterVertically) {+                    OutlinedTextField(+                        value = query,+                        onValueChange = { query = it },+                        label = { Text("Search") },+                        modifier = Modifier.weight(1f)+                    )+                    Spacer(Modifier.width(8.dp))+                    Button(onClick = {+                        isSearching = true+                        scope.launch {+                            remoteResults = FoodSearchAPI.searchIngredients(query)+                            if (includeLocal) {+                                localResults = HealthAPI.db.healthDao().searchIngredients(query)+                            }+                            isSearching = false+                        }+                    }) {+                        Text("Search")+                    }+                }+                +                Spacer(Modifier.height(8.dp))+                +                if (isSearching || isFetchingData) {+                    CircularProgressIndicator(modifier = Modifier.align(Alignment.CenterHorizontally))+                } else {+                    LazyColumn(modifier = Modifier.fillMaxSize()) {+                        // Show Local results first if included+                        if (includeLocal && localResults.isNotEmpty()) {+                            item {+                                Text("Downloaded", style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(8.dp))+                            }+                            items(localResults) { ingredient ->+                                ListItem(+                                    headlineContent = { Text(ingredient.displayName) },+                                    supportingContent = { Text("Saved Locally", style = MaterialTheme.typography.bodySmall) },+                                    colors = ListItemDefaults.colors(containerColor = Color.Transparent),+                                    modifier = Modifier.clickable { onIngredientSelected(ingredient) }+                                )+                                HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))+                            }+                        }++                        // Show Remote results+                        if (remoteResults.isNotEmpty()) {+                            item {+                                Text("Online", style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(8.dp))+                            }+                            items(remoteResults) { result ->+                                // Skip if already in local results to avoid duplicates+                                if (includeLocal && localResults.any { it.id == result.id.toString() }) return@items++                                ListItem(+                                    headlineContent = { Text(result.display_name) },+                                    colors = ListItemDefaults.colors(containerColor = Color.Transparent),+                                    modifier = Modifier.clickable {+                                        isFetchingData = true+                                        scope.launch {+                                            val ingredient = FoodSearchAPI.getIngredientData(result.id, result.display_name)+                                            isFetchingData = false+                                            if (ingredient != null) {+                                                onIngredientSelected(ingredient)+                                            }+                                        }+                                    }+                                )+                                HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))+                            }+                        }+                        +                        if (!isSearching && !isFetchingData && remoteResults.isEmpty() && localResults.isEmpty() && query.isNotBlank()) {+                            item {+                                Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {+                                    Text("No results found", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.outline)+                                }+                            }+                        }+                    }+                }+            }+        },+        confirmButton = {+            TextButton(onClick = onDismiss) { Text("Cancel") }+        }+    )+}
health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt b/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.ktnew file mode 100644index 0000000000..1b0f86bb10--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt@@ -0,0 +1,61 @@+package com.vayunmathur.health.util++import com.vayunmathur.health.data.Ingredient+import com.vayunmathur.health.data.NutritionData+import io.ktor.client.HttpClient+import io.ktor.client.call.body+import io.ktor.client.engine.cio.CIO+import io.ktor.client.plugins.contentnegotiation.ContentNegotiation+import io.ktor.client.request.get+import io.ktor.client.request.parameter+import io.ktor.serialization.kotlinx.json.json+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++object FoodSearchAPI {+    private val client =+            HttpClient(CIO) {+                install(ContentNegotiation) {+                    json(+                            Json {+                                ignoreUnknownKeys = true+                                coerceInputValues = true+                            }+                    )+                }+            }++    @Serializable data class SearchResult(val id: Long, val display_name: String)++    suspend fun searchIngredients(query: String): List<SearchResult> {+        return try {+            val response =+                    client.get("https://api.vayunmathur.com/api/food/search") {+                        parameter("q", query)+                    }+            if (response.status.value !in 200..299) {+                android.util.Log.e("FoodSearchAPI", "API Error: ${response.status}")+            }+            response.body()+        } catch (e: Exception) {+            android.util.Log.e("FoodSearchAPI", "Search Error: ${e.message}", e)+            emptyList()+        }+    }++    suspend fun getIngredientData(id: Long, displayName: String): Ingredient? {+        return try {+            val nutritionData: NutritionData =+                    client.get("https://api.vayunmathur.com/api/food/data/$id").body()++            Ingredient(+                    id = id.toString(),+                    originalName = displayName,+                    nutritionData = nutritionData+            )+        } catch (e: Exception) {+            android.util.Log.e("FoodSearchAPI", "Fetch Data Error: ${e.message}", e)+            null+        }+    }+}
health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt b/health/src/main/java/com/vayunmathur/health/util/HealthAPI.ktindex 61afb13f52..adc1ea103a 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt@@ -1,36 +1,45 @@ package com.vayunmathur.health.util+ import android.content.Context import android.content.SharedPreferences+import android.net.Uri+import android.util.Log import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.health.connect.client.HealthConnectClient import androidx.health.connect.client.feature.ExperimentalPersonalHealthRecordApi-import androidx.health.connect.client.records.FhirResource-import androidx.health.connect.client.records.MedicalResource-import android.util.Log-import android.net.Uri import androidx.health.connect.client.records.FhirVersion+import androidx.health.connect.client.records.HydrationRecord+import androidx.health.connect.client.records.MedicalResource+import androidx.health.connect.client.records.NutritionRecord+import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.request.CreateMedicalDataSourceRequest import androidx.health.connect.client.request.GetMedicalDataSourcesRequest import androidx.health.connect.client.request.ReadMedicalResourcesInitialRequest import androidx.health.connect.client.request.ReadMedicalResourcesPageRequest import androidx.health.connect.client.request.UpsertMedicalResourceRequest+import androidx.health.connect.client.units.Energy+import androidx.health.connect.client.units.Mass+import androidx.health.connect.client.units.Volume import com.vayunmathur.health.data.HealthDatabase import com.vayunmathur.health.data.Record import com.vayunmathur.health.data.RecordType import com.vayunmathur.library.util.Tuple3-import kotlinx.coroutines.flow.Flow-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive-import kotlinx.serialization.json.jsonObject+import java.time.ZoneOffset import java.util.UUID+import kotlin.reflect.KClass+import kotlin.time.Instant+import kotlinx.coroutines.flow.Flow import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.minus import kotlinx.datetime.plus-import kotlin.time.Instant+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.jsonObject+import androidx.core.net.toUri  object HealthAPI {     lateinit var healthConnectClient: HealthConnectClient@@ -45,322 +54,738 @@ object HealthAPI {      @Composable     fun sumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember(recordType, startTime, endTime) { db.healthDao().sumInRange(recordType, startTime, endTime) }+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumProteinInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumProteinInRange(recordType, startTime, endTime) }+    fun sumProteinInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumProteinInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumCarbsInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumCarbsInRange(recordType, startTime, endTime) }+    fun sumCarbsInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumCarbsInRange(recordType, startTime, endTime)+        }     }      @Composable     fun sumFatInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumFatInRange(recordType, startTime, endTime) }+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumFatInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumFiberInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumFiberInRange(recordType, startTime, endTime) }+    fun sumFiberInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumFiberInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumSugarInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumSugarInRange(recordType, startTime, endTime) }+    fun sumSugarInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumSugarInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumSodiumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumSodiumInRange(recordType, startTime, endTime) }+    fun sumSodiumInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumSodiumInRange(recordType, startTime, endTime)+        }     }-    +     @Composable-    fun sumBiotinInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumBiotinInRange(recordType, startTime, endTime) }+    fun sumBiotinInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumBiotinInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumCaffeineInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumCaffeineInRange(recordType, startTime, endTime) }+    fun sumCaffeineInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumCaffeineInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumCalciumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumCalciumInRange(recordType, startTime, endTime) }+    fun sumCalciumInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumCalciumInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumChlorideInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumChlorideInRange(recordType, startTime, endTime) }+    fun sumChlorideInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumChlorideInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumCholesterolInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumCholesterolInRange(recordType, startTime, endTime) }+    fun sumCholesterolInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumCholesterolInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumChromiumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumChromiumInRange(recordType, startTime, endTime) }+    fun sumChromiumInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumChromiumInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumCopperInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumCopperInRange(recordType, startTime, endTime) }+    fun sumCopperInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumCopperInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumFolateInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumFolateInRange(recordType, startTime, endTime) }+    fun sumFolateInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumFolateInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumFolicAcidInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumFolicAcidInRange(recordType, startTime, endTime) }+    fun sumFolicAcidInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumFolicAcidInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumIodineInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumIodineInRange(recordType, startTime, endTime) }+    fun sumIodineInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumIodineInRange(recordType, startTime, endTime)+        }     }      @Composable     fun sumIronInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumIronInRange(recordType, startTime, endTime) }+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumIronInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumMagnesiumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumMagnesiumInRange(recordType, startTime, endTime) }+    fun sumMagnesiumInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumMagnesiumInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumManganeseInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumManganeseInRange(recordType, startTime, endTime) }+    fun sumManganeseInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumManganeseInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumMolybdenumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumMolybdenumInRange(recordType, startTime, endTime) }+    fun sumMolybdenumInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumMolybdenumInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumMonounsaturatedFatInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumMonounsaturatedFatInRange(recordType, startTime, endTime) }+    fun sumMonounsaturatedFatInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumMonounsaturatedFatInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumNiacinInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumNiacinInRange(recordType, startTime, endTime) }+    fun sumNiacinInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumNiacinInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumPantothenicAcidInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumPantothenicAcidInRange(recordType, startTime, endTime) }+    fun sumPantothenicAcidInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumPantothenicAcidInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumPhosphorusInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumPhosphorusInRange(recordType, startTime, endTime) }+    fun sumPhosphorusInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumPhosphorusInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumPolyunsaturatedFatInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumPolyunsaturatedFatInRange(recordType, startTime, endTime) }+    fun sumPolyunsaturatedFatInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumPolyunsaturatedFatInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumPotassiumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumPotassiumInRange(recordType, startTime, endTime) }+    fun sumPotassiumInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumPotassiumInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumRiboflavinInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumRiboflavinInRange(recordType, startTime, endTime) }+    fun sumRiboflavinInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumRiboflavinInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumSaturatedFatInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumSaturatedFatInRange(recordType, startTime, endTime) }+    fun sumSaturatedFatInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumSaturatedFatInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumSeleniumInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumSeleniumInRange(recordType, startTime, endTime) }+    fun sumSeleniumInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumSeleniumInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumThiaminInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumThiaminInRange(recordType, startTime, endTime) }+    fun sumThiaminInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumThiaminInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumTransFatInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumTransFatInRange(recordType, startTime, endTime) }+    fun sumTransFatInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumTransFatInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumUnsaturatedFatInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumUnsaturatedFatInRange(recordType, startTime, endTime) }+    fun sumUnsaturatedFatInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumUnsaturatedFatInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumVitaminAInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumVitaminAInRange(recordType, startTime, endTime) }+    fun sumVitaminAInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumVitaminAInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumVitaminB12InRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumVitaminB12InRange(recordType, startTime, endTime) }+    fun sumVitaminB12InRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumVitaminB12InRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumVitaminB6InRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumVitaminB6InRange(recordType, startTime, endTime) }+    fun sumVitaminB6InRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumVitaminB6InRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumVitaminCInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumVitaminCInRange(recordType, startTime, endTime) }+    fun sumVitaminCInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumVitaminCInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumVitaminDInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumVitaminDInRange(recordType, startTime, endTime) }+    fun sumVitaminDInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumVitaminDInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumVitaminEInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumVitaminEInRange(recordType, startTime, endTime) }+    fun sumVitaminEInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumVitaminEInRange(recordType, startTime, endTime)+        }     }      @Composable-    fun sumVitaminKInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumVitaminKInRange(recordType, startTime, endTime) }+    fun sumVitaminKInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<Double> {+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumVitaminKInRange(recordType, startTime, endTime)+        }     }      @Composable     fun sumZincInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double> {-        return remember { db.healthDao().sumZincInRange(recordType, startTime, endTime) }+        return remember(recordType, startTime, endTime) {+            db.healthDao().sumZincInRange(recordType, startTime, endTime)+        }     }      @Composable     fun maxInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double?> {-        return remember(recordType, startTime, endTime) { db.healthDao().maxInRange(recordType, startTime, endTime) }+        return remember(recordType, startTime, endTime) {+            db.healthDao().maxInRange(recordType, startTime, endTime)+        }     }      @Composable     fun minInRange(recordType: RecordType, startTime: Instant, endTime: Instant): Flow<Double?> {-        return remember(recordType, startTime, endTime) { db.healthDao().minInRange(recordType, startTime, endTime) }+        return remember(recordType, startTime, endTime) {+            db.healthDao().minInRange(recordType, startTime, endTime)+        }     }      suspend inline fun lastRecord(recordType: RecordType): Record? {         return db.healthDao().getLastRecord(recordType)     } -    enum class PeriodType {-        Hourly, Daily, Weekly, Monthly+    fun getAllRecordsInRange(+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant+    ): Flow<List<Record>> {+        return db.healthDao().getAllInRange(recordType, startTime, endTime)     } -    private val hourlyFormat = LocalDateTime.Format {-        year()-        chars("-")-        monthNumber()-        chars("-")-        day()-        chars(" ")-        hour()-        chars(":")-        minute()+    suspend fun deleteRecord(record: Record) {+        // Delete from local Room DB+        db.healthDao().deleteByIds(listOf(record.primaryKey))++        // Delete from Health Connect if it has a valid ID+        try {+            val recordClass: KClass<out androidx.health.connect.client.records.Record>? = when (record.type) {+                RecordType.Nutrition -> NutritionRecord::class+                RecordType.Hydration -> HydrationRecord::class+                else -> null+            }+            if (recordClass != null) {+                healthConnectClient.deleteRecords(+                        recordType = recordClass,+                        recordIdsList = listOf(record.id),+                        clientRecordIdsList = listOf(record.id)+                )+            }+        } catch (e: Exception) {+            Log.e("HealthAPI", "Failed to delete record from Health Connect", e)+        }     } +    suspend fun writeHealthRecord(record: Record) {+        Log.d("HealthAPI", "writeHealthRecord: type=${record.type}, metadata=${record.metadata}")+        val startInstant = record.startTime+        val endInstant = record.endTime++        val hcRecord: androidx.health.connect.client.records.Record =+                when (record.type) {+                    RecordType.Nutrition -> {+                        val nd = record.nutritionData ?: return+                        NutritionRecord(+                                startTime = startInstant,+                                startZoneOffset =+                                        ZoneOffset.systemDefault().rules.getOffset(startInstant),+                                endTime = endInstant,+                                endZoneOffset =+                                        ZoneOffset.systemDefault().rules.getOffset(endInstant),+                                name = record.metadata,+                                energy = Energy.kilocalories(nd.calories),+                                protein = Mass.grams(nd.protein),+                                totalCarbohydrate = Mass.grams(nd.carbohydrates),+                                totalFat = Mass.grams(nd.fat),+                                dietaryFiber = Mass.grams(nd.fiber),+                                sugar = Mass.grams(nd.sugar),+                                sodium = Mass.milligrams(nd.sodium),+                                biotin = Mass.micrograms(nd.biotin),+                                caffeine = Mass.milligrams(nd.caffeine),+                                calcium = Mass.milligrams(nd.calcium),+                                chloride = Mass.milligrams(nd.chloride),+                                cholesterol = Mass.milligrams(nd.cholesterol),+                                chromium = Mass.micrograms(nd.chromium),+                                copper = Mass.milligrams(nd.copper),+                                folate = Mass.micrograms(nd.folate),+                                folicAcid = Mass.micrograms(nd.folicAcid),+                                iodine = Mass.micrograms(nd.iodine),+                                iron = Mass.milligrams(nd.iron),+                                magnesium = Mass.milligrams(nd.magnesium),+                                manganese = Mass.milligrams(nd.manganese),+                                molybdenum = Mass.micrograms(nd.molybdenum),+                                monounsaturatedFat = Mass.grams(nd.monounsaturatedFat),+                                niacin = Mass.milligrams(nd.niacin),+                                pantothenicAcid = Mass.milligrams(nd.pantothenicAcid),+                                phosphorus = Mass.milligrams(nd.phosphorus),+                                polyunsaturatedFat = Mass.grams(nd.polyunsaturatedFat),+                                potassium = Mass.milligrams(nd.potassium),+                                riboflavin = Mass.milligrams(nd.riboflavin),+                                saturatedFat = Mass.grams(nd.saturatedFat),+                                selenium = Mass.micrograms(nd.selenium),+                                thiamin = Mass.milligrams(nd.thiamin),+                                transFat = Mass.grams(nd.transFat),+                                unsaturatedFat = Mass.grams(nd.unsaturatedFat),+                                vitaminA = Mass.micrograms(nd.vitaminA),+                                vitaminB12 = Mass.micrograms(nd.vitaminB12),+                                vitaminB6 = Mass.milligrams(nd.vitaminB6),+                                vitaminC = Mass.milligrams(nd.vitaminC),+                                vitaminD = Mass.micrograms(nd.vitaminD),+                                vitaminE = Mass.milligrams(nd.vitaminE),+                                vitaminK = Mass.micrograms(nd.vitaminK),+                                zinc = Mass.milligrams(nd.zinc),+                                metadata = Metadata.manualEntry(clientRecordId = record.id)+                        )+                    }+                    RecordType.Hydration -> {+                        HydrationRecord(+                                startTime = startInstant,+                                startZoneOffset =+                                        ZoneOffset.systemDefault().rules.getOffset(startInstant),+                                endTime = endInstant,+                                endZoneOffset =+                                        ZoneOffset.systemDefault().rules.getOffset(endInstant),+                                volume = Volume.liters(record.value),+                                metadata = Metadata.manualEntry(clientRecordId = record.id)+                        )+                    }+                    else -> return+                }++        try {+            val response = healthConnectClient.insertRecords(listOf(hcRecord))+            val newId = response.recordIdsList.firstOrNull()+            if (newId != null) {+                Log.i("HealthAPI", "Successfully wrote record to Health Connect with ID: $newId")+                // Remove old local record and replace with one containing HC ID+                db.healthDao().deleteByIds(listOf(record.primaryKey))+                val updatedRecord = record.copy(id = newId, primaryKey = "$newId-${record.index}")+                db.healthDao().upsert(listOf(updatedRecord))+            }+        } catch (e: Exception) {+            Log.e("HealthAPI", "Failed to write record to Health Connect", e)+        }+    }++    enum class PeriodType {+        Hourly,+        Daily,+        Weekly,+        Monthly+    }++    private val hourlyFormat =+            LocalDateTime.Format {+                year()+                chars("-")+                monthNumber()+                chars("-")+                day()+                chars(" ")+                hour()+                chars(":")+                minute()+            }+     suspend fun getListOfAverages(-        recordType: RecordType,-        startTime: Instant,-        endTime: Instant,-        period: PeriodType+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant,+            period: PeriodType     ): List<Tuple3<Long, Double, Double>> {-        when(period) {+        when (period) {             PeriodType.Daily -> {                 // yyyy-mm-dd-                val dailySums = db.healthDao().getDailyAvgs(recordType, startTime, endTime).sortedBy { it.day }-                return dailySums.map { Tuple3(LocalDate.parse(it.day).toEpochDays(), it.totalValue, it.totalValue2) }+                val dailySums =+                        db.healthDao().getDailyAvgs(recordType, startTime, endTime).sortedBy {+                            it.day+                        }+                return dailySums.map {+                    Tuple3(LocalDate.parse(it.day).toEpochDays(), it.totalValue, it.totalValue2)+                }             }             PeriodType.Weekly -> {-                val dailySums = db.healthDao().getDailyAvgs(recordType, startTime, endTime).sortedBy { it.day }-                    .groupBy {-                        val date = LocalDate.parse(it.day)-                        val firstDayOfWeek = date.plus((date.dayOfWeek.ordinal+1)%7, DateTimeUnit.DAY)-                        firstDayOfWeek.toEpochDays()-                    }-                    .mapValues { day -> day.value.map { it.totalValue }.average() to day.value.map { it.totalValue2 }.average() }-                    .map { Tuple3(it.key, it.value.first, it.value.second) }+                val dailySums =+                        db.healthDao()+                                .getDailyAvgs(recordType, startTime, endTime)+                                .sortedBy { it.day }+                                .groupBy {+                                    val date = LocalDate.parse(it.day)+                                    val firstDayOfWeek =+                                            date.plus(+                                                    (date.dayOfWeek.ordinal + 1) % 7,+                                                    DateTimeUnit.DAY+                                            )+                                    firstDayOfWeek.toEpochDays()+                                }+                                .mapValues { day ->+                                    day.value.map { it.totalValue }.average() to+                                            day.value.map { it.totalValue2 }.average()+                                }+                                .map { Tuple3(it.key, it.value.first, it.value.second) }                 return dailySums             }             PeriodType.Monthly -> {-                val dailySums = db.healthDao().getDailyAvgs(recordType, startTime, endTime).sortedBy { it.day }-                    .groupBy {-                        val date = LocalDate.parse(it.day)-                        val firstDayOfMonth = date.minus(date.day-1, DateTimeUnit.DAY)-                        firstDayOfMonth.toEpochDays()-                    }-                    .mapValues { day -> day.value.map { it.totalValue }.average() to day.value.map { it.totalValue2 }.average() }-                    .map { Tuple3(it.key, it.value.first, it.value.second) }+                val dailySums =+                        db.healthDao()+                                .getDailyAvgs(recordType, startTime, endTime)+                                .sortedBy { it.day }+                                .groupBy {+                                    val date = LocalDate.parse(it.day)+                                    val firstDayOfMonth = date.minus(date.day - 1, DateTimeUnit.DAY)+                                    firstDayOfMonth.toEpochDays()+                                }+                                .mapValues { day ->+                                    day.value.map { it.totalValue }.average() to+                                            day.value.map { it.totalValue2 }.average()+                                }+                                .map { Tuple3(it.key, it.value.first, it.value.second) }                 return dailySums             }             else -> {-                val hourlySums = db.healthDao().getHourlyAvgs(recordType, startTime.toEpochMilliseconds(), endTime.toEpochMilliseconds()).sortedBy { it.hourBlock }+                val hourlySums =+                        db.healthDao()+                                .getHourlyAvgs(+                                        recordType,+                                        startTime.toEpochMilliseconds(),+                                        endTime.toEpochMilliseconds()+                                )+                                .sortedBy { it.hourBlock }                 return hourlySums.map {                     val date = hourlyFormat.parse(it.hourBlock)-                    Tuple3(date.date.toEpochDays()*24 + date.hour, it.totalValue, it.totalValue2)+                    Tuple3(date.date.toEpochDays() * 24 + date.hour, it.totalValue, it.totalValue2)                 }             }         }     }      suspend fun getListOfSums(-        recordType: RecordType,-        startTime: Instant,-        endTime: Instant,-        period: PeriodType+            recordType: RecordType,+            startTime: Instant,+            endTime: Instant,+            period: PeriodType     ): List<Tuple3<Long, Double, Double>> {-        when(period) {+        when (period) {             PeriodType.Daily -> {                 // yyyy-mm-dd-                val dailySums = db.healthDao().getDailySums(recordType, startTime, endTime).sortedBy { it.day }-                return dailySums.map { Tuple3(LocalDate.parse(it.day).toEpochDays(), it.totalValue, it.totalValue2) }+                val dailySums =+                        db.healthDao().getDailySums(recordType, startTime, endTime).sortedBy {+                            it.day+                        }+                return dailySums.map {+                    Tuple3(LocalDate.parse(it.day).toEpochDays(), it.totalValue, it.totalValue2)+                }             }             PeriodType.Weekly -> {-                val dailySums = db.healthDao().getDailySums(recordType, startTime, endTime).sortedBy { it.day }-                    .groupBy {-                        val date = LocalDate.parse(it.day)-                        val firstDayOfWeek = date.plus((date.dayOfWeek.ordinal+1)%7, DateTimeUnit.DAY)-                        firstDayOfWeek.toEpochDays()-                    }-                    .mapValues { day -> day.value.map { it.totalValue }.average() to day.value.map { it.totalValue2 }.average() }-                    .map { Tuple3(it.key, it.value.first, it.value.second) }+                val dailySums =+                        db.healthDao()+                                .getDailySums(recordType, startTime, endTime)+                                .sortedBy { it.day }+                                .groupBy {+                                    val date = LocalDate.parse(it.day)+                                    val firstDayOfWeek =+                                            date.plus(+                                                    (date.dayOfWeek.ordinal + 1) % 7,+                                                    DateTimeUnit.DAY+                                            )+                                    firstDayOfWeek.toEpochDays()+                                }+                                .mapValues { day ->+                                    day.value.map { it.totalValue }.average() to+                                            day.value.map { it.totalValue2 }.average()+                                }+                                .map { Tuple3(it.key, it.value.first, it.value.second) }                 return dailySums             }             PeriodType.Monthly -> {-                val dailySums = db.healthDao().getDailySums(recordType, startTime, endTime).sortedBy { it.day }-                    .groupBy {-                        val date = LocalDate.parse(it.day)-                        val firstDayOfMonth = date.minus(date.day-1, DateTimeUnit.DAY)-                        firstDayOfMonth.toEpochDays()-                    }-                    .mapValues { day -> day.value.map { it.totalValue }.average() to day.value.map { it.totalValue2 }.average() }-                    .map { Tuple3(it.key, it.value.first, it.value.second) }+                val dailySums =+                        db.healthDao()+                                .getDailySums(recordType, startTime, endTime)+                                .sortedBy { it.day }+                                .groupBy {+                                    val date = LocalDate.parse(it.day)+                                    val firstDayOfMonth = date.minus(date.day - 1, DateTimeUnit.DAY)+                                    firstDayOfMonth.toEpochDays()+                                }+                                .mapValues { day ->+                                    day.value.map { it.totalValue }.average() to+                                            day.value.map { it.totalValue2 }.average()+                                }+                                .map { Tuple3(it.key, it.value.first, it.value.second) }                 return dailySums             }             else -> {-                val hourlySums = db.healthDao().getHourlySums(recordType, startTime.toEpochMilliseconds(), endTime.toEpochMilliseconds()).sortedBy { it.hourBlock }+                val hourlySums =+                        db.healthDao()+                                .getHourlySums(+                                        recordType,+                                        startTime.toEpochMilliseconds(),+                                        endTime.toEpochMilliseconds()+                                )+                                .sortedBy { it.hourBlock }                 return hourlySums.map {                     val date = hourlyFormat.parse(it.hourBlock)-                    Tuple3(date.date.toEpochDays()*24 + date.hour, it.totalValue, it.totalValue2)+                    Tuple3(date.date.toEpochDays() * 24 + date.hour, it.totalValue, it.totalValue2)                 }             }         }@@ -371,8 +796,9 @@ object HealthAPI {         val allRecords = mutableListOf<MedicalResource>()         var pageToken: String? = null         do {-            val request = if (pageToken == null) ReadMedicalResourcesInitialRequest(type, setOf())-            else ReadMedicalResourcesPageRequest(pageToken)+            val request =+                    if (pageToken == null) ReadMedicalResourcesInitialRequest(type, setOf())+                    else ReadMedicalResourcesPageRequest(pageToken)             val response = healthConnectClient.readMedicalResources(request)             allRecords += response.medicalResources             pageToken = response.nextPageToken@@ -383,7 +809,8 @@ object HealthAPI {     @OptIn(ExperimentalPersonalHealthRecordApi::class)     suspend fun getOrCreateDataSource(): String {         Log.d("HealthAPI", "getOrCreateDataSource")-        val dataSources = healthConnectClient.getMedicalDataSources(GetMedicalDataSourcesRequest(emptyList()))+        val dataSources =+                healthConnectClient.getMedicalDataSources(GetMedicalDataSourcesRequest(emptyList()))         val existing = dataSources.find { it.displayName == "OpenAssistant Extraction" }         if (existing != null) {             Log.d("HealthAPI", "Found existing data source: ${existing.id}")@@ -392,38 +819,43 @@ object HealthAPI {          Log.i("HealthAPI", "Creating new data source for OpenAssistant Extraction")         return healthConnectClient.createMedicalDataSource(-            CreateMedicalDataSourceRequest(-                fhirBaseUri = Uri.parse("https://com.vayunmathur.openassistant/extraction"),-                displayName = "OpenAssistant Extraction",-                fhirVersion = FhirVersion(4, 0, 1)-            )-        ).id+                        CreateMedicalDataSourceRequest(+                                fhirBaseUri =+                                    "https://com.vayunmathur.openassistant/extraction".toUri(),+                                displayName = "OpenAssistant Extraction",+                                fhirVersion = FhirVersion(4, 0, 1)+                        )+                )+                .id     }      @OptIn(ExperimentalPersonalHealthRecordApi::class)     suspend fun writeMedicalRecord(fhirData: String) {-        val json = try {-            Json.parseToJsonElement(fhirData).jsonObject.toMutableMap()-        } catch (e: Exception) {-            Log.e("HealthAPI", "Failed to parse FHIR data as JSON", e)-            return-        }-        +        val json =+                try {+                    Json.parseToJsonElement(fhirData).jsonObject.toMutableMap()+                } catch (e: Exception) {+                    Log.e("HealthAPI", "Failed to parse FHIR data as JSON", e)+                    return+                }+         // Always ensure a random ID is present as requested         json["id"] = JsonPrimitive(UUID.randomUUID().toString())-        +         val finalData = JsonObject(json).toString()          Log.d("HealthAPI", "writeMedicalRecord (sanitized): $finalData")         val dataSourceId = getOrCreateDataSource()         try {-            healthConnectClient.upsertMedicalResources(listOf(-                UpsertMedicalResourceRequest(-                    dataSourceId = dataSourceId,-                    fhirVersion = FhirVersion(4, 0, 1),-                    data = finalData-                )-            ))+            healthConnectClient.upsertMedicalResources(+                    listOf(+                            UpsertMedicalResourceRequest(+                                    dataSourceId = dataSourceId,+                                    fhirVersion = FhirVersion(4, 0, 1),+                                    data = finalData+                            )+                    )+            )             Log.i("HealthAPI", "Medical record written successfully")         } catch (e: Exception) {             Log.e("HealthAPI", "Failed to write medical record to Health Connect", e)
health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt b/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.ktindex da9d781323..b78b2fa361 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt@@ -135,38 +135,38 @@ class HealthSyncWorker( fun androidx.health.connect.client.records.Record.toRecord(): List<Record> =     when (this) {         // --- Activity ----        is StepsRecord -> listOf(Record(this.metadata.id, 0, RecordType.Steps, this.startTime, this.endTime, this.count.toDouble()))-        is WheelchairPushesRecord -> listOf(Record(this.metadata.id, 0, RecordType.Wheelchair, this.startTime, this.endTime, this.count.toDouble()))-        is DistanceRecord -> listOf(Record(this.metadata.id, 0, RecordType.Distance, this.startTime, this.endTime, this.distance.inKilometers))-        is TotalCaloriesBurnedRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesTotal, this.startTime, this.endTime, this.energy.inKilocalories))-        is ActiveCaloriesBurnedRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesActive, this.startTime, this.endTime, this.energy.inKilocalories))-        is BasalMetabolicRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesBasal, this.time, this.time, this.basalMetabolicRate.inKilocaloriesPerDay))-        is FloorsClimbedRecord -> listOf(Record(this.metadata.id, 0, RecordType.Floors, this.startTime, this.endTime, this.floors))-        is ElevationGainedRecord -> listOf(Record(this.metadata.id, 0, RecordType.Elevation, this.startTime, this.endTime, this.elevation.inMeters))+        is StepsRecord -> listOf(Record(this.metadata.id, 0, RecordType.Steps, this.startTime, this.endTime, this.count.toDouble(), metadata = "Steps"))+        is WheelchairPushesRecord -> listOf(Record(this.metadata.id, 0, RecordType.Wheelchair, this.startTime, this.endTime, this.count.toDouble(), metadata = "Wheelchair Pushes"))+        is DistanceRecord -> listOf(Record(this.metadata.id, 0, RecordType.Distance, this.startTime, this.endTime, this.distance.inKilometers, metadata = "Distance"))+        is TotalCaloriesBurnedRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesTotal, this.startTime, this.endTime, this.energy.inKilocalories, metadata = "Total Calories"))+        is ActiveCaloriesBurnedRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesActive, this.startTime, this.endTime, this.energy.inKilocalories, metadata = "Active Calories"))+        is BasalMetabolicRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.CaloriesBasal, this.time, this.time, this.basalMetabolicRate.inKilocaloriesPerDay, metadata = "Basal Metabolic Rate"))+        is FloorsClimbedRecord -> listOf(Record(this.metadata.id, 0, RecordType.Floors, this.startTime, this.endTime, this.floors, metadata = "Floors Climbed"))+        is ElevationGainedRecord -> listOf(Record(this.metadata.id, 0, RecordType.Elevation, this.startTime, this.endTime, this.elevation.inMeters, metadata = "Elevation Gained"))          // --- Vitals ----        is HeartRateRecord -> this.samples.mapIndexed { idx, sample -> Record(this.metadata.id, idx, RecordType.HeartRate, sample.time, sample.time, sample.beatsPerMinute.toDouble()) }-        is RestingHeartRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.RestingHeartRate, this.time, this.time, this.beatsPerMinute.toDouble()))-        is HeartRateVariabilityRmssdRecord -> listOf(Record(this.metadata.id, 0, RecordType.HeartRateVariabilityRmssd, this.time, this.time, this.heartRateVariabilityMillis))-        is RespiratoryRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.RespiratoryRate, this.time, this.time, this.rate))-        is OxygenSaturationRecord -> listOf(Record(this.metadata.id, 0, RecordType.OxygenSaturation, this.time, this.time, this.percentage.value))-        is BloodPressureRecord -> listOf(Record(this.metadata.id, 0, RecordType.BloodPressure, this.time, this.time, this.systolic.inMillimetersOfMercury, this.diastolic.inMillimetersOfMercury))-        is BloodGlucoseRecord -> listOf(Record(this.metadata.id, 0, RecordType.BloodGlucose, this.time, this.time, this.level.inMilligramsPerDeciliter))-        is Vo2MaxRecord -> listOf(Record(this.metadata.id, 0, RecordType.Vo2Max, this.time, this.time, this.vo2MillilitersPerMinuteKilogram))-        is SkinTemperatureRecord -> this.deltas.mapIndexed { idx, delta -> Record(this.metadata.id, idx, RecordType.SkinTemperature, delta.time, delta.time, delta.delta.inCelsius) }+        is HeartRateRecord -> this.samples.mapIndexed { idx, sample -> Record(this.metadata.id, idx, RecordType.HeartRate, sample.time, sample.time, sample.beatsPerMinute.toDouble(), metadata = "Heart Rate") }+        is RestingHeartRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.RestingHeartRate, this.time, this.time, this.beatsPerMinute.toDouble(), metadata = "Resting Heart Rate"))+        is HeartRateVariabilityRmssdRecord -> listOf(Record(this.metadata.id, 0, RecordType.HeartRateVariabilityRmssd, this.time, this.time, this.heartRateVariabilityMillis, metadata = "HRV"))+        is RespiratoryRateRecord -> listOf(Record(this.metadata.id, 0, RecordType.RespiratoryRate, this.time, this.time, this.rate, metadata = "Respiratory Rate"))+        is OxygenSaturationRecord -> listOf(Record(this.metadata.id, 0, RecordType.OxygenSaturation, this.time, this.time, this.percentage.value, metadata = "Oxygen Saturation"))+        is BloodPressureRecord -> listOf(Record(this.metadata.id, 0, RecordType.BloodPressure, this.time, this.time, this.systolic.inMillimetersOfMercury, this.diastolic.inMillimetersOfMercury, metadata = "Blood Pressure"))+        is BloodGlucoseRecord -> listOf(Record(this.metadata.id, 0, RecordType.BloodGlucose, this.time, this.time, this.level.inMilligramsPerDeciliter, metadata = "Blood Glucose"))+        is Vo2MaxRecord -> listOf(Record(this.metadata.id, 0, RecordType.Vo2Max, this.time, this.time, this.vo2MillilitersPerMinuteKilogram, metadata = "VO2 Max"))+        is SkinTemperatureRecord -> this.deltas.mapIndexed { idx, delta -> Record(this.metadata.id, idx, RecordType.SkinTemperature, delta.time, delta.time, delta.delta.inCelsius, metadata = "Skin Temperature") }          // --- Body Composthision ----        is WeightRecord -> listOf(Record(this.metadata.id, 0, RecordType.Weight, this.time, this.time, this.weight.inKilograms))-        is HeightRecord -> listOf(Record(this.metadata.id, 0, RecordType.Height, this.time, this.time, this.height.inMeters))-        is BodyFatRecord -> listOf(Record(this.metadata.id, 0, RecordType.BodyFat, this.time, this.time, this.percentage.value))-        is LeanBodyMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.LeanBodyMass, this.time, this.time, this.mass.inKilograms))-        is BoneMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.BoneMass, this.time, this.time, this.mass.inKilograms))-        is BodyWaterMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.BodyWaterMass, this.time, this.time, this.mass.inKilograms))+        is WeightRecord -> listOf(Record(this.metadata.id, 0, RecordType.Weight, this.time, this.time, this.weight.inKilograms, metadata = "Weight"))+        is HeightRecord -> listOf(Record(this.metadata.id, 0, RecordType.Height, this.time, this.time, this.height.inMeters, metadata = "Height"))+        is BodyFatRecord -> listOf(Record(this.metadata.id, 0, RecordType.BodyFat, this.time, this.time, this.percentage.value, metadata = "Body Fat"))+        is LeanBodyMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.LeanBodyMass, this.time, this.time, this.mass.inKilograms, metadata = "Lean Body Mass"))+        is BoneMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.BoneMass, this.time, this.time, this.mass.inKilograms, metadata = "Bone Mass"))+        is BodyWaterMassRecord -> listOf(Record(this.metadata.id, 0, RecordType.BodyWaterMass, this.time, this.time, this.mass.inKilograms, metadata = "Body Water Mass"))          // --- Lifestyle --- //                    is SleepSessionRecord -> listOf(Record(this.metadata.id, 0, "Sleep", this.startTime, this.endTime, this))-        is MindfulnessSessionRecord -> listOf(Record(this.metadata.id, 0, RecordType.Mindfulness, this.startTime, this.endTime, Duration.between(this.startTime, this.endTime).toMillis().toDouble() / 1000.0 / 60.0))-        is HydrationRecord -> listOf(Record(this.metadata.id, 0, RecordType.Hydration, this.startTime, this.endTime, this.volume.inMilliliters))+        is MindfulnessSessionRecord -> listOf(Record(this.metadata.id, 0, RecordType.Mindfulness, this.startTime, this.endTime, Duration.between(this.startTime, this.endTime).toMillis().toDouble() / 1000.0 / 60.0, metadata = "Mindfulness"))+        is HydrationRecord -> listOf(Record(this.metadata.id, 0, RecordType.Hydration, this.startTime, this.endTime, this.volume.inMilliliters, metadata = "Hydration"))         is NutritionRecord -> listOf(Record(             this.metadata.id, 0, RecordType.Nutrition, this.startTime, this.endTime,             this.energy?.inKilocalories ?: 0.0,@@ -211,7 +211,8 @@ fun androidx.health.connect.client.records.Record.toRecord(): List<Record> =                 vitaminE = this.vitaminE?.inGrams ?: 0.0,                 vitaminK = this.vitaminK?.inGrams ?: 0.0,                 zinc = this.zinc?.inGrams ?: 0.0-            )+            ),+            metadata = this.name         ))          else -> throw IllegalArgumentException("Unsupported record type")
health/src/main/res/drawable/baseline_add_24.xml
diff --git a/health/src/main/res/drawable/baseline_add_24.xml b/health/src/main/res/drawable/baseline_add_24.xmlnew file mode 100644index 0000000000..eb232541d8--- /dev/null+++ b/health/src/main/res/drawable/baseline_add_24.xml@@ -0,0 +1,10 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+  <path+      android:fillColor="@android:color/white"+      android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>+</vector>
health/src/main/res/drawable/baseline_delete_24.xml
diff --git a/health/src/main/res/drawable/baseline_delete_24.xml b/health/src/main/res/drawable/baseline_delete_24.xmlnew file mode 100644index 0000000000..3c4030b03e--- /dev/null+++ b/health/src/main/res/drawable/baseline_delete_24.xml@@ -0,0 +1,10 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24"+    android:tint="?attr/colorControlNormal">+  <path+      android:fillColor="@android:color/white"+      android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z"/>+</vector>
library/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 45c992fccf..ef181b6357 100644--- a/lib

Diff truncated.