package org.timesafari.dailynotification

import android.content.Context
import android.util.Log
import kotlinx.coroutines.runBlocking
import org.json.JSONObject

/**
 * Helper for resolving dual (New Activity) notification content at fire time.
 * Applies relationship (contentTimeout, fallbackBehavior) using persisted config and content cache.
 */
object DualScheduleHelper {
    private const val TAG = "DNP-DUAL"

    /**
     * Resolve title/body for a dual schedule: use cached content if within contentTimeout, else default from config.
     * Call from Worker when schedule_id starts with DUAL_NOTIFY_SCHEDULE_ID_PREFIX.
     *
     * @param context Application context
     * @param notificationId Notification run id for the display
     * @return NotificationContent with resolved title/body, or null if no config or skip
     */
    @JvmStatic
    fun resolveDualContentBlocking(context: Context, notificationId: String): NotificationContent? {
        return try {
            val prefs = context.getSharedPreferences(DailyNotificationConstants.DUAL_SCHEDULE_PREFS, Context.MODE_PRIVATE)
            val configStr = prefs.getString(DailyNotificationConstants.DUAL_SCHEDULE_CONFIG_KEY, null) ?: return null
            val config = JSONObject(configStr)
            val userNotification = config.optJSONObject("userNotification") ?: return null
            val relationship = config.optJSONObject("relationship")
            val contentTimeoutMs = relationship?.optLong("contentTimeout", 300_000L) ?: 300_000L
            val fallbackBehavior = relationship?.optString("fallbackBehavior", "show_default") ?: "show_default"

            val defaultTitle = userNotification.optString("title", "Daily Notification")
            val defaultBody = userNotification.optString("body", "Your daily update is ready")

            val db = DailyNotificationDatabase.getDatabase(context)
            val latestCache = runBlocking {
                db.contentCacheDao().getLatestByScope(ContentCacheScope.DUAL)
            }
            val nowMs = System.currentTimeMillis()

            val (title: String, body: String) = if (latestCache != null && (nowMs - latestCache.fetchedAt) <= contentTimeoutMs) {
                val payloadStr = String(latestCache.payload, Charsets.UTF_8)
                try {
                    val payload = JSONObject(payloadStr)
                    if (payload.optBoolean("skipNotification", false)) {
                        return null
                    }
                    Pair(
                        payload.optString("title", defaultTitle),
                        payload.optString("body", payload.optString("content", defaultBody))
                    )
                } catch (_: Exception) {
                    Pair(defaultTitle, defaultBody)
                }
            } else {
                val staleSkip = latestCache?.let { cache ->
                    try {
                        JSONObject(String(cache.payload, Charsets.UTF_8)).optBoolean("skipNotification", false)
                    } catch (_: Exception) {
                        false
                    }
                } ?: false
                if (staleSkip && fallbackBehavior == "skip") {
                    return null
                }
                if (fallbackBehavior != "show_default") return null
                Pair(defaultTitle, defaultBody)
            }

            val content = NotificationContent(title, body, nowMs)
            content.setId(notificationId)
            content.setSound(userNotification.optBoolean("sound", true))
            content.setPriority(userNotification.optString("priority", "normal"))
            Log.d(TAG, "Resolved dual content: useCache=${latestCache != null && (nowMs - latestCache.fetchedAt) <= contentTimeoutMs}")
            content
        } catch (e: Exception) {
            Log.w(TAG, "resolveDualContentBlocking failed", e)
            null
        }
    }
}
