package com.mice.voice_keep_alive.services

import android.Manifest
import android.app.*
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.os.PowerManager
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import com.mice.voice_keep_alive.R

/**
 * 商业级 VoiceKeepService 完整版
 * - 前后台区分，主播模式 + 音频活跃才保活
 * - MIC 权限检查 + FGS 类型安全
 * - 点击通知打开 Activity 并传递 roomParams
 * - WakeLock 限时 5 分钟
 */
class VoiceKeepService : Service() {

    companion object {
        const val CHANNEL_ID = "voice_service_channel"
        const val NOTIFICATION_ID = 1001
        const val MODE_AUDIENCE = 0
        const val MODE_ANCHOR = 1

        private var wakeLock: PowerManager.WakeLock? = null
    }

    private var currentMode: Int = MODE_AUDIENCE
    private var title: String = ""
    private var content: String = ""
    private var roomParams: String = ""

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        currentMode = intent?.getIntExtra("mode", MODE_AUDIENCE) ?: MODE_AUDIENCE
        title = intent?.getStringExtra("title") ?: getString(R.string.voice_service_title)
        content = intent?.getStringExtra("content") ?: getString(R.string.voice_service_text)
        roomParams = intent?.getStringExtra("roomParams") ?: ""

        // 🔹立即启动前台服务
        val notification = buildNotification()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(
                NOTIFICATION_ID,
                notification,
                ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK or
                        if (currentMode == MODE_ANCHOR) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0
            )
        } else {
            startForeground(NOTIFICATION_ID, notification)
        }

        // 🔹异步处理后续逻辑
        Thread {
            try {
                handleIntentWork(intent)
            } catch (_: Exception) {}
        }.start()

        return START_STICKY
    }

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

    /**
     * Flutter / Zego SDK 调用：音频状态变化
     * active = true 表示音频活跃
     */
    fun onZegoAudioStateChanged(active: Boolean) {
        if (isAppInBackground()) {
            if (active && currentMode == MODE_ANCHOR && hasMicPermission()) {
                acquireWakeLock()
            } else {
                releaseWakeLock()
            }
        } else {
            releaseWakeLock()
        }
    }

    private fun hasMicPermission(): Boolean {
        return ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED &&
                (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE ||
                        ActivityCompat.checkSelfPermission(
                            this,
                            Manifest.permission.FOREGROUND_SERVICE_MICROPHONE
                        ) == PackageManager.PERMISSION_GRANTED)
    }

    private fun handleIntentWork(intent: Intent?) {
        // 可在此处理 Flutter 通信或其他业务逻辑
    }

    /** 创建通知通道 */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                getString(R.string.voice_service_channel_name),
                NotificationManager.IMPORTANCE_LOW
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager?.createNotificationChannel(channel)
        }
    }

    /** 构建前台服务通知，点击通知打开 Activity 并传 roomParams */
    private fun buildNotification(): Notification {
        val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
            ?.apply {
                putExtra("roomParams", roomParams)
                action = "OPEN_ROOM_FROM_SERVICE"
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or
                        Intent.FLAG_ACTIVITY_SINGLE_TOP or
                        Intent.FLAG_ACTIVITY_CLEAR_TOP
            }

        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            launchIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(content)
            .setSmallIcon(
                if (currentMode == MODE_ANCHOR)
                    android.R.drawable.ic_btn_speak_now
                else
                    android.R.drawable.ic_lock_silent_mode_off
            )
            .setContentIntent(pendingIntent)  // 点击通知打开房间
            .setOngoing(true)
            .build()
    }

    /** 获取短期 WakeLock（最多 5 分钟） */
    private fun acquireWakeLock() {
        if (wakeLock == null) {
            val pm = getSystemService(POWER_SERVICE) as PowerManager
            wakeLock = pm.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK,
                "VoiceKeepService::WakeLock"
            )
        }
        if (wakeLock?.isHeld == false) {
            try {
                wakeLock?.acquire(5 * 60 * 1000L)
            } catch (_: Exception) {}
        }
    }

    /** 释放 WakeLock */
    private fun releaseWakeLock() {
        try {
            if (wakeLock?.isHeld == true) wakeLock?.release()
        } catch (_: Exception) {}
    }

    override fun onDestroy() {
        stopForeground(true)
        releaseWakeLock()
        super.onDestroy()
    }

    /** 判断 App 是否在后台 */
    private fun isAppInBackground(): Boolean {
        return !VoiceKeepApp.isForeground
    }
}

/**
 * Application 类，用于追踪前后台状态
 */
class VoiceKeepApp : Application() {

    companion object {
        var isForeground = false
    }

    override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityResumed(activity: Activity) { isForeground = true }
            override fun onActivityPaused(activity: Activity) { isForeground = false }
            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {}
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
            override fun onActivityDestroyed(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
        })
    }
}
