package dev.privacyllc.period.feature.insights

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.privacyllc.period.core.data.CycleRepository
import dev.privacyllc.period.core.data.PredictionAccuracy
import dev.privacyllc.period.domain.cycle.CycleInsights
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

data class InsightsUiState(
    val insights: CycleInsights = CycleInsights.from(emptyList()),
    val accuracy: PredictionAccuracy = PredictionAccuracy.Empty,
)

/**
 * §27, and everything on it is computed here on the device.
 *
 * §46 lists `prediction_error=` among the values that must never leave as an
 * analytics event, and this is the screen that would tempt somebody to send one.
 * There is no network call in this file and there must never be.
 */
@HiltViewModel
class InsightsViewModel @Inject constructor(
    repository: CycleRepository,
) : ViewModel() {

    val state: StateFlow<InsightsUiState> =
        combine(repository.confirmedPeriods, repository.accuracy) { periods, accuracy ->
            InsightsUiState(insights = CycleInsights.from(periods), accuracy = accuracy)
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), InsightsUiState())
}
