package org.timesafari.dailynotification

import android.util.Log

/**
 * Shared cron → next wall-clock instant (daily "minute hour * * *" style).
 * Used by dual prefetch scheduling, rollover, and [DailyNotificationPlugin] scheduling.
 */
object ScheduleCronUtils {
    private const val TAG = "DNP-CRON"

    /**
     * Next occurrence of the given daily cron after "now" (same logic as DailyNotificationPlugin.calculateNextRunTime).
     */
    @JvmStatic
    fun calculateNextRunTimeMillis(schedule: String): Long {
        try {
            val parts = schedule.trim().split("\\s+".toRegex())
            if (parts.size < 2) {
                Log.w(TAG, "Invalid cron format: $schedule, defaulting to 24h from now")
                return System.currentTimeMillis() + (24 * 60 * 60 * 1000L)
            }

            val minute = parts[0].toIntOrNull() ?: 0
            val hour = parts[1].toIntOrNull() ?: 9

            if (minute < 0 || minute > 59 || hour < 0 || hour > 23) {
                Log.w(TAG, "Invalid time values in cron: $schedule, defaulting to 24h from now")
                return System.currentTimeMillis() + (24 * 60 * 60 * 1000L)
            }

            val calendar = java.util.Calendar.getInstance()
            val now = calendar.timeInMillis

            calendar.set(java.util.Calendar.HOUR_OF_DAY, hour)
            calendar.set(java.util.Calendar.MINUTE, minute)
            calendar.set(java.util.Calendar.SECOND, 0)
            calendar.set(java.util.Calendar.MILLISECOND, 0)

            var nextRun = calendar.timeInMillis
            if (nextRun <= now) {
                calendar.add(java.util.Calendar.DAY_OF_YEAR, 1)
                nextRun = calendar.timeInMillis
            }

            Log.d(
                TAG,
                "Next run: cron=$schedule, nextRun=${
                    java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US)
                        .format(java.util.Date(nextRun))
                }"
            )
            return nextRun
        } catch (e: Exception) {
            Log.e(TAG, "Error calculating next run for schedule: $schedule", e)
            return System.currentTimeMillis() + (24 * 60 * 60 * 1000L)
        }
    }
}
