package org.timesafari.dailynotification

import android.content.Context
import android.util.Log
import org.json.JSONObject

/**
 * Arms the dual (New Activity) user notification **after** prefetch completes (chained schedule).
 * Fires at [max]([nextNotifyAtMillis], now) so a late fetch delays delivery instead of showing stale API copy first.
 */
object DualScheduleNotifyScheduler {
    private const val TAG = "DNP-DUAL-NOTIFY"

    /**
     * Schedule exact alarm for dual notify using persisted [DailyNotificationConstants.DUAL_SCHEDULE_CONFIG_KEY]
     * and [DailyNotificationConstants.DUAL_NOTIFY_SCHEDULE_ID_KEY].
     */
    @JvmStatic
    fun scheduleChainedNotifyAlarm(context: Context, nextNotifyAtMillis: Long) {
        try {
            val prefs = context.getSharedPreferences(
                DailyNotificationConstants.DUAL_SCHEDULE_PREFS,
                Context.MODE_PRIVATE
            )
            val configStr = prefs.getString(DailyNotificationConstants.DUAL_SCHEDULE_CONFIG_KEY, null)
                ?: run {
                    Log.w(TAG, "No dual_schedule_config; skip chained notify")
                    return
                }
            val scheduleId = prefs.getString(DailyNotificationConstants.DUAL_NOTIFY_SCHEDULE_ID_KEY, null)
                ?: run {
                    Log.w(TAG, "No dual_notify_schedule_id; skip chained notify")
                    return
                }
            val root = JSONObject(configStr)
            val userObj = root.optJSONObject("userNotification") ?: run {
                Log.w(TAG, "dual config missing userNotification")
                return
            }
            val config = parseUserNotificationConfig(userObj)
            val now = System.currentTimeMillis()
            val triggerAt = maxOf(nextNotifyAtMillis, now + 500L)
            Log.i(TAG, "Chained dual notify: scheduleId=$scheduleId triggerAt=$triggerAt (nextNotify=$nextNotifyAtMillis)")
            NotifyReceiver.scheduleExactNotification(
                context,
                triggerAt,
                config,
                scheduleId = scheduleId,
                source = ScheduleSource.INITIAL_SETUP,
                skipPendingIntentIdempotence = true
            )
        } catch (e: Exception) {
            Log.e(TAG, "scheduleChainedNotifyAlarm failed", e)
        }
    }

    private fun parseUserNotificationConfig(configJson: JSONObject): UserNotificationConfig {
        return UserNotificationConfig(
            enabled = configJson.optBoolean("enabled", true),
            schedule = configJson.optString("schedule", "0 9 * * *"),
            title = configJson.optString("title").takeIf { it.isNotEmpty() },
            body = configJson.optString("body").takeIf { it.isNotEmpty() },
            sound = if (configJson.has("sound") && JSONObject.NULL != configJson.get("sound")) {
                configJson.optBoolean("sound")
            } else {
                null
            },
            vibration = if (configJson.has("vibration") && JSONObject.NULL != configJson.get("vibration")) {
                configJson.optBoolean("vibration")
            } else {
                null
            },
            priority = configJson.optString("priority").takeIf { it.isNotEmpty() }
        )
    }
}
