package com.lila.wakeup

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.lila.wakeup.kws.AudioCapture
import com.lila.wakeup.kws.KwsEngine
import com.lila.wakeup.kws.KwsStateMachine
import com.lila.wakeup.protocol.BroadcastSender
import com.lila.wakeup.protocol.WakeupServiceLocator

/**
 * KWS 唤醒前台 Service —— 整个 APK 的运行时核心。
 *
 * 生命周期：
 *  - onCreate: 初始化引擎、状态机、采集器、通知栏
 *  - onStartCommand: startForeground + 启动音频采集 + 进入 LISTENING
 *  - onDestroy: 停止采集、释放引擎
 *
 * START_STICKY: 被系统杀死后会自动重启（无音频帧丢失影响业务）。
 */
class WakeupForegroundService : Service() {

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

    private lateinit var engine: KwsEngine
    private lateinit var stateMachine: KwsStateMachine
    private lateinit var audioCapture: AudioCapture
    private lateinit var sender: BroadcastSender

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "onCreate")

        // 通知栏 channel 必须在 startForeground 之前创建
        createNotificationChannel()

        // 初始化引擎栈（顺序：sender → engine → state → audio）
        sender = BroadcastSender(applicationContext)
        engine = KwsEngine(applicationContext).also { it.init() }
        stateMachine = KwsStateMachine(
            engine = engine,
            sender = sender,
            onTimeoutResume = { Log.w(TAG, "[Tmout] PAUSE 超时自动 RESUME") }
        )
        audioCapture = AudioCapture(onFrame = { pcm -> stateMachine.onAudioFrame(pcm) })

        // 注册到全局定位器，使 ProtocolReceiver 能投递 PAUSE/RESUME 事件
        WakeupServiceLocator.stateMachine = stateMachine
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "onStartCommand")
        startInForeground()

        // 进入监听态
        stateMachine.transitionToListening()
        audioCapture.start()

        // 被杀重启时尝试恢复（不带 Intent）
        return START_STICKY
    }

    override fun onDestroy() {
        Log.i(TAG, "onDestroy")
        // 先解绑 locator，避免 ProtocolReceiver 投递到正在销毁的 stateMachine
        WakeupServiceLocator.stateMachine = null
        audioCapture.stop()
        engine.release()
        stateMachine.shutdown()
        super.onDestroy()
    }

    override fun onBind(intent: Intent?): IBinder? = null

    // ============================================================
    // 通知栏（前台 Service 强制要求）
    // ============================================================

    private fun startInForeground() {
        val notification = buildNotification()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(
                Config.NOTIF_ID,
                notification,
                ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
            )
        } else {
            startForeground(Config.NOTIF_ID, notification)
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return

        val mgr = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (mgr.getNotificationChannel(Config.NOTIF_CHANNEL_ID) != null) return

        val channel = NotificationChannel(
            Config.NOTIF_CHANNEL_ID,
            Config.NOTIF_CHANNEL_NAME,
            NotificationManager.IMPORTANCE_MIN     // 最低优先级，不打扰用户
        ).apply {
            description = "语音唤醒服务运行状态"
            setShowBadge(false)
        }
        mgr.createNotificationChannel(channel)
    }

    private fun buildNotification(): Notification {
        // 点击通知打开 MainActivity（状态查看）
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            Intent(this, MainActivity::class.java),
            PendingIntent.FLAG_IMMUTABLE
        )

        return NotificationCompat.Builder(this, Config.NOTIF_CHANNEL_ID)
            .setContentTitle("Lila 语音助手")
            .setContentText("正在监听唤醒词")
            .setSmallIcon(android.R.drawable.ic_btn_speak_now)  // 用系统默认麦克风图标，方案 B 时换自家
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_MIN)
            .setContentIntent(pendingIntent)
            .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
            .build()
    }
}
