package com.lila.wakeup

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 状态查看 Activity（开发期辅助 + 首次启动权限申请入口）。
 *
 * 职责：
 *  1. 首次启动时弹麦克风权限申请
 *  2. 启动 [WakeupForegroundService]
 *  3. 显示当前状态（开发期可选）
 *
 * 量产时（方案 B）改为 launcher 隐藏（删 LAUNCHER intent-filter），
 * 用户不用进 APP 也能开机自启。
 */
class MainActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "KwsService.Main"
        private const val PERMISSION_REQUEST_CODE = 1001
    }

    private lateinit var statusText: TextView
    private var wakeupCount = 0
    private val timeFmt = SimpleDateFormat("HH:mm:ss", Locale.getDefault())

    /**
     * 内部唤醒事件接收器,与外部协议广播 [Config.ACTION_WAKEUP] 隔离。
     * 收到后追加到 [statusText] 显示,方便用户在 APP 界面直接看效果。
     */
    private val wakeupReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action != Config.ACTION_INTERNAL_WAKEUP) return
            val keyword = intent.getStringExtra(Config.EXTRA_KEYWORD) ?: "?"
            val confidence = intent.getFloatExtra(Config.EXTRA_CONFIDENCE, 0f)
            val ts = intent.getLongExtra(Config.EXTRA_TIMESTAMP, System.currentTimeMillis())
            val timeStr = timeFmt.format(Date(ts))
            wakeupCount++
            statusText.append("\n[$timeStr] #$wakeupCount 命中: $keyword (conf=$confidence)")
            Log.i(TAG, "UI shown wakeup #$wakeupCount keyword=$keyword")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 简化:用一个可滚动的 TextView 直接显示状态 + 唤醒事件
        statusText = TextView(this).apply {
            text = "Lila 语音唤醒服务\n\n初始化中..."
            textSize = 18f
            setPadding(60, 60, 60, 60)
            movementMethod = ScrollingMovementMethod()
        }
        setContentView(statusText)

        // 注册内部唤醒事件接收器(Android 13+ 必须显式声明 NOT_EXPORTED)
        val filter = IntentFilter(Config.ACTION_INTERNAL_WAKEUP)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(wakeupReceiver, filter, RECEIVER_NOT_EXPORTED)
        } else {
            registerReceiver(wakeupReceiver, filter)
        }

        checkAndRequestPermissions()
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            unregisterReceiver(wakeupReceiver)
        } catch (_: IllegalArgumentException) {
            // 接收器从未注册,忽略
        }
    }

    private fun checkAndRequestPermissions() {
        val needRequestList = mutableListOf<String>()

        // 麦克风权限（核心）
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED
        ) {
            needRequestList.add(Manifest.permission.RECORD_AUDIO)
        }

        // 通知权限（Android 13+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                != PackageManager.PERMISSION_GRANTED
            ) {
                needRequestList.add(Manifest.permission.POST_NOTIFICATIONS)
            }
        }

        if (needRequestList.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                needRequestList.toTypedArray(),
                PERMISSION_REQUEST_CODE
            )
        } else {
            startWakeupService()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode != PERMISSION_REQUEST_CODE) return

        val recordIdx = permissions.indexOf(Manifest.permission.RECORD_AUDIO)
        if (recordIdx >= 0 && grantResults[recordIdx] == PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "RECORD_AUDIO granted")
            startWakeupService()
        } else {
            statusText.text = "Lila 语音唤醒服务\n\n❌ 麦克风权限被拒绝，无法启动唤醒"
            Log.e(TAG, "RECORD_AUDIO denied, service NOT started")
        }
    }

    private fun startWakeupService() {
        val intent = Intent(this, WakeupForegroundService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
        statusText.text = """
            Lila 语音唤醒服务

            ✅ 服务已启动
            ✅ 监听唤醒词中

            可关闭本界面，服务会在后台持续运行。
            通知栏可看到运行状态。

            日志：adb logcat -s KwsService
        """.trimIndent()
        Log.i(TAG, "WakeupForegroundService start requested")
    }
}
