package com.example.domain import com.example.data.model.MealEntry import com.example.data.model.MealType import com.example.ui.journal.DayStat import com.example.ui.journal.WeeklyStats import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale object WeeklyStatsCalculator { fun computeWeeklyStats(meals: List, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats { val todayLocalDate = LocalDate.now(zoneId) val startOfPeriod = todayLocalDate.minusDays(6) val startOfPeriodMillis = startOfPeriod.atStartOfDay(zoneId).toInstant().toEpochMilli() val endOfTodayMillis = todayLocalDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1 val recentMeals = meals.filter { it.mealTimestamp in startOfPeriodMillis..endOfTodayMillis } val dayFormat = DateTimeFormatter.ofPattern("EEE", Locale.FRENCH) val fullDayFormat = DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH) val daysList = mutableListOf() for (i in 6 downTo 0) { val currentDay = todayLocalDate.minusDays(i.toLong()) val startOfDay = currentDay.atStartOfDay(zoneId).toInstant().toEpochMilli() val endOfDay = currentDay.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1 val dayMeals = meals.filter { it.mealTimestamp in startOfDay..endOfDay } val avgSatiety = if (dayMeals.isNotEmpty()) { dayMeals.map { it.satietyAfter }.average().toFloat() } else 0f val avgHunger = if (dayMeals.isNotEmpty()) { dayMeals.map { it.hungerBefore }.average().toFloat() } else 0f daysList.add( DayStat( dayLabel = fullDayFormat.format(currentDay), dayShortName = dayFormat.format(currentDay).replace(".", "").replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString() }, timestampMillis = startOfDay, avgSatiety = avgSatiety, avgHunger = avgHunger, mealCount = dayMeals.size ) ) } val allRecentSatieties = recentMeals.map { it.satietyAfter } val allRecentHungers = recentMeals.map { it.hungerBefore } val avgSatiety = if (allRecentSatieties.isNotEmpty()) allRecentSatieties.average().toFloat() else 0f val avgHunger = if (allRecentHungers.isNotEmpty()) allRecentHungers.average().toFloat() else 0f val optimalCount = recentMeals.count { it.satietyAfter in 6..8 } val optimalPercentage = if (recentMeals.isNotEmpty()) { ((optimalCount.toFloat() / recentMeals.size) * 100).toInt() } else 0 val distribution = mutableMapOf() MealType.entries.forEach { type -> distribution[type] = recentMeals.count { it.mealType.equals(type.name, ignoreCase = true) } } return WeeklyStats( dailyStats = daysList, averageSatiety = avgSatiety, averageHunger = avgHunger, optimalZonePercentage = optimalPercentage, totalMealsLast7Days = recentMeals.size, mealTypeDistribution = distribution ) } }