package com.jishisongfu.duobibi.heartbeat

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * AlarmManager 周期唤起 → 触发一次心跳上报 + adb broadcast 手动测试。
 *
 * 用 goAsync() 把 onReceive 异步化(BroadcastReceiver 默认 ANR 阈值 5s 内必须返回)。
 *
 * 手动触发(实测期常用):
 *   adb shell am broadcast -a com.jishisongfu.duobibi.HEARTBEAT_TICK \
 *     -n com.jishisongfu.duobibi/.heartbeat.HeartbeatReceiver
 */
class HeartbeatReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent?) {
        Log.i(TAG, "alarm tick received action=${intent?.action}")
        val pending = goAsync()
        scope.launch {
            try {
                HeartbeatSender.send(context.applicationContext, trigger = "alarm")
            } finally {
                pending.finish()
            }
        }
    }

    companion object {
        private const val TAG = "DUOBIBI-HB"
        const val ACTION_TICK = "com.jishisongfu.duobibi.HEARTBEAT_TICK"

        // SupervisorJob 防一次失败拖死后续
        private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    }
}
