package com.a2i.forwarder.service

import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import com.a2i.forwarder.A2iApp
import com.a2i.forwarder.core.BarkClient
import com.a2i.forwarder.core.ForwardLog
import com.a2i.forwarder.core.NotificationProcessor
import com.a2i.forwarder.core.PendingPush
import com.a2i.forwarder.core.RetryWorker
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.util.UUID

class NotifyListenerService : NotificationListenerService() {

    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    private val processor by lazy { NotificationProcessor(applicationContext) }
    private val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }

    override fun onListenerConnected() {
        super.onListenerConnected()
        RetryWorker.schedule(applicationContext)
    }

    override fun onNotificationPosted(sbn: StatusBarNotification?) {
        val posted = sbn ?: return
        if (posted.packageName == packageName) return
        scope.launch { handle(posted) }
    }

    private suspend fun handle(sbn: StatusBarNotification) {
        val app = A2iApp.instance
        val now = System.currentTimeMillis()
        val d = processor.process(sbn)
        val msg = d.message

        if (msg == null) {
            // 静默过滤（如持续性通知）不写日志
            if (!d.silent) {
                app.logStore.addLog(ForwardLog(now, sbn.packageName, d.appLabel, "", "", "filtered", d.reason))
            }
            return
        }

        // ---- 断网兜底：离线时紧要通知走短信，其余不转发避免离线堆积 ----
        val online = app.connectivityMonitor.isOnline.value
        if (!online) {
            if (app.smsForwarder.isSmsWorthy(d)) {
                app.smsForwarder.forward(d)
            } else {
                app.logStore.addLog(ForwardLog(now, sbn.packageName, d.appLabel, msg.title, msg.body, "filtered", "离线非紧要通知"))
            }
            return
        }

        val server = app.settings.currentServer.value
        if (server == null || server.deviceKey.isBlank()) {
            app.logStore.addLog(ForwardLog(now, sbn.packageName, d.appLabel, msg.title, msg.body, "failed", "未配置 Bark key"))
            return
        }

        val result = BarkClient(server).push(msg)
        if (result.isSuccess) {
            app.logStore.addLog(ForwardLog(now, sbn.packageName, d.appLabel, msg.title, msg.body, "sent", ""))
        } else {
            val reason = result.exceptionOrNull()?.message ?: "错误"
            app.logStore.addLog(ForwardLog(now, sbn.packageName, d.appLabel, msg.title, msg.body, "failed", reason))
            app.logStore.addPending(
                PendingPush(UUID.randomUUID().toString(), now, server.id, json.encodeToString(msg))
            )
        }
    }
}
