package com.lila.wakeup.protocol

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.lila.wakeup.Config

/**
 * 接收 APP 端发来的 KWS_PAUSE / KWS_RESUME 广播。
 *
 * 协议 v2.1 字段：
 *  - silence_ms (long): PAUSE 默认 3000，Networking 60000
 *  - reason (String): 透传日志，便于排查
 *
 * 实现方式：通过 [WakeupServiceLocator] 静态引用 KwsStateMachine 投递事件，
 * 避免 BroadcastReceiver 与 Service 之间频繁 startService 启动开销。
 */
class ProtocolReceiver : BroadcastReceiver() {

    companion object {
        private const val TAG = "KwsService.Proto"
    }

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action ?: return

        // 安全检查：仅处理协议白名单 Action
        when (action) {
            Config.ACTION_KWS_PAUSE -> handlePause(intent)
            Config.ACTION_KWS_RESUME -> handleResume(intent)
            else -> Log.w(TAG, "Ignored unknown action: $action")
        }
    }

    private fun handlePause(intent: Intent) {
        val silenceMs = intent.getLongExtra(Config.EXTRA_SILENCE_MS, Config.DEFAULT_SILENCE_MS)
        val reason = intent.getStringExtra(Config.EXTRA_REASON) ?: "unknown"
        Log.i(TAG, "Recv PAUSE silence_ms=$silenceMs reason=$reason")

        WakeupServiceLocator.stateMachine?.onPauseReceived(silenceMs, reason)
            ?: Log.e(TAG, "stateMachine is null! Service not running?")
    }

    private fun handleResume(intent: Intent) {
        val reason = intent.getStringExtra(Config.EXTRA_REASON) ?: "unknown"
        Log.i(TAG, "Recv RESUME reason=$reason")

        WakeupServiceLocator.stateMachine?.onResumeReceived(reason)
            ?: Log.e(TAG, "stateMachine is null! Service not running?")
    }
}

/**
 * 服务定位器：BroadcastReceiver 与 Service 之间的桥接。
 *
 * Service.onCreate 中赋值，onDestroy 中置 null。
 * 该方式避免每次广播都 bindService（开销大），且不引入 AIDL 复杂度。
 */
object WakeupServiceLocator {
    @Volatile
    var stateMachine: com.lila.wakeup.kws.KwsStateMachine? = null
}
