package eu.friedcutlet.yokan.domain import eu.friedcutlet.yokan.util.nowMillis import kotlin.math.roundToInt import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn private const val DayMillis = 86_400_000L /** Mean gap between known releases. Duplicate dates do not count as new intervals. */ fun meanChapterUpdateDays(uploadDates: Iterable, now: Long = nowMillis()): Int? { val dates = uploadDates.mapNotNull { raw -> val value = raw.trim() val date = value.toLongOrNull()?.let { if (it in 1L until 10_000_000_000L) it * 1_000L else it } ?: runCatching { LocalDate.parse(value.take(10)).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds() }.getOrNull() date?.takeIf { it > 0 && it <= now } }.distinct().sorted() if (dates.size < 2) return null val mean = (dates.last() - dates.first()).toDouble() / (dates.size - 1) / DayMillis return mean.roundToInt().coerceAtLeast(1) } /** null = automatic, zero = every update, positive = a manual cooldown. */ fun effectiveChapterUpdateDays(manualDays: Int?, uploadDates: Iterable, now: Long = nowMillis()): Int = manualDays?.coerceAtLeast(0) ?: meanChapterUpdateDays(uploadDates, now) ?: 0