package eu.friedcutlet.yokan.services.scheduling import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.util.nowMillis import kotlin.time.Instant import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.TimeZone import kotlinx.datetime.atTime import kotlinx.datetime.minus import kotlinx.datetime.plus import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime internal fun periodicMinutes(seconds: Int): Long = if (seconds <= 0) 0L else ((seconds + 59L) / 60L).coerceAtLeast(15L) /** Epoch millis of the most recent occurrence of [dailyAtMinutes] (local time) at or before [now]. */ @OptIn(kotlin.time.ExperimentalTime::class) internal fun latestDailySlotMillis( dailyAtMinutes: Int, now: Long = nowMillis(), zone: TimeZone = TimeZone.currentSystemDefault(), ): Long { val today = Instant.fromEpochMilliseconds(now).toLocalDateTime(zone).date val slotToday = today.atTime(dailyAtMinutes / 60, dailyAtMinutes % 60).toInstant(zone).toEpochMilliseconds() return if (slotToday <= now) { slotToday } else { today.minus(1, DateTimeUnit.DAY).atTime(dailyAtMinutes / 60, dailyAtMinutes % 60).toInstant(zone).toEpochMilliseconds() } } /** Millis until the next occurrence of [dailyAtMinutes] strictly after [now]. */ @OptIn(kotlin.time.ExperimentalTime::class) internal fun nextDailySlotDelayMillis( dailyAtMinutes: Int, now: Long = nowMillis(), zone: TimeZone = TimeZone.currentSystemDefault(), ): Long { val last = Instant.fromEpochMilliseconds(latestDailySlotMillis(dailyAtMinutes, now, zone)).toLocalDateTime(zone) return last.date.plus(1, DateTimeUnit.DAY).atTime(last.hour, last.minute).toInstant(zone).toEpochMilliseconds() - now } /** UI values 1..5 mean 6h / 12h / daily / 2 days / weekly. */ internal fun backupFrequencyHours(value: Int?): Long = when (value) { 1 -> 6L 2 -> 12L 3 -> 24L 4 -> 48L 5 -> 168L else -> 0L } /** * Periodic OS-level background workers. Android uses WorkManager, iOS uses * BGTaskScheduler, and desktop/web rely on [ForegroundScheduler] while open. */ interface BackgroundScheduler { /** [libraryUpdateDailyAtMinutes] >= 0 anchors the library update to that local time of day; else repeat every [libraryUpdateMinutes]. */ fun schedule( metadataRefreshMinutes: Long, libraryUpdateMinutes: Long, libraryUpdateDailyAtMinutes: Int, autoSyncMinutes: Long, autoBackupHours: Long, requireUnmetered: Boolean, libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints = eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints(), ) fun cancelAll() } expect fun createPlatformBackgroundScheduler( database: YokanDatabase, profileId: ProfileId = ProfileId.Default, ): BackgroundScheduler /** Stale owners are terminal no-ops; unreadable registry metadata is recoverable. */ val ProfileWorkResult.shouldRetry: Boolean get() = when (this) { is ProfileWorkResult.Completed -> value.shouldRetry ProfileWorkResult.Skipped -> false ProfileWorkResult.Retry -> true }