package com.jishisongfu.duobibi.push

import android.content.Context
import android.util.Log
import com.jishisongfu.duobibi.heartbeat.HeartbeatSender
import com.xiaomi.mipush.sdk.ErrorCode
import com.xiaomi.mipush.sdk.MiPushClient
import com.xiaomi.mipush.sdk.MiPushCommandMessage
import com.xiaomi.mipush.sdk.MiPushMessage
import com.xiaomi.mipush.sdk.PushMessageReceiver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * 小米推送回调入口。所有日志统一打到 DUOBIBI-PUSH tag,验证时跑:
 *   adb logcat -s DUOBIBI-PUSH:V
 *
 * 验证矩阵 6 个场景每个场景关注的 logcat 行:
 *   - register success      → 拿 regId 复制到小米后台"指定 regId"
 *   - PUSH arrived          → 通知到达回调(App 在线时触发)
 *   - PUSH notification     → 通知栏弹出回调(App 在线时触发)
 *   - PUSH clicked          → 用户点击通知拉起 App
 *
 * 注意:App 被 force-stop 后所有 receiver 被系统 disable,通知仍能弹(由小米
 * XMSF 系统进程负责)但本类回调不会触发——这是 Android force-stop 语义,不是 bug。
 */
class MiPushReceiver : PushMessageReceiver() {

    override fun onReceiveRegisterResult(context: Context, message: MiPushCommandMessage) {
        val cmd = message.command
        val args = message.commandArguments
        val resultCode = message.resultCode
        if (MiPushClient.COMMAND_REGISTER == cmd) {
            if (resultCode == ErrorCode.SUCCESS.toLong()) {
                val regId = args?.firstOrNull().orEmpty()
                Log.i(TAG, "register success regId=$regId")
                // 持久化方便后续 SettingsScreen / 其他入口取用,验证期可 adb 拷出
                context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
                    .edit()
                    .putString(KEY_REG_ID, regId)
                    .apply()
                // 拿到 regId 立刻 register-device + 补发一次心跳 ——
                // 否则后端要等 5 分钟下次 alarm 才知道这个设备
                val app = context.applicationContext
                scope.launch {
                    HeartbeatSender.registerDevice(app)
                    HeartbeatSender.send(app, "regid_received")
                }
            } else {
                Log.e(TAG, "register failed code=$resultCode reason=${message.reason}")
            }
        } else {
            Log.i(TAG, "command=$cmd args=$args resultCode=$resultCode reason=${message.reason}")
        }
    }

    override fun onCommandResult(context: Context, message: MiPushCommandMessage) {
        Log.i(TAG, "onCommandResult cmd=${message.command} args=${message.commandArguments} code=${message.resultCode}")
    }

    /** 透传消息(本次验证不用,占位以防误判) */
    override fun onReceivePassThroughMessage(context: Context, message: MiPushMessage) {
        Log.i(TAG, "passthrough content=${message.content?.take(80)} msgId=${message.messageId}")
    }

    /** 通知到达 — App 在线时触发,被杀 / force-stop 时不触发 */
    override fun onNotificationMessageArrived(context: Context, message: MiPushMessage) {
        Log.i(TAG, "PUSH arrived title=${message.title} desc=${message.description?.take(80)} msgId=${message.messageId}")
    }

    /** 用户点击通知拉起 App */
    override fun onNotificationMessageClicked(context: Context, message: MiPushMessage) {
        Log.i(TAG, "PUSH clicked title=${message.title} desc=${message.description?.take(80)} msgId=${message.messageId} extra=${message.extra}")
    }

    companion object {
        private const val TAG = "DUOBIBI-PUSH"
        const val PREFS = "push_prefs"
        const val KEY_REG_ID = "reg_id"

        // 静态 scope 而非每次新建,避免 receiver 多次触发时累积。SupervisorJob 防失败传染。
        private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    }
}
