package com.hikoncont.service

import android.content.Intent
import android.os.Build
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import androidx.core.app.NotificationManagerCompat
import kotlinx.coroutines.*

/**
 * 通知监听服务 - 参考 f 目录的 MessageToolUse
 * 系统级服务，用于监听系统通知（保活机制之一）
 * 
 * 注意：需要用户手动授权通知监听权限
 */
class NotificationMonitorService : NotificationListenerService() {

    companion object {
        private const val TAG = "NotificationMonitor"
        
        @Volatile
        private var instance: NotificationMonitorService? = null
        
        fun getInstance(): NotificationMonitorService? = instance
        
        /**
         * 检查通知监听服务是否已启用
         */
        fun isNotificationListenerEnabled(context: android.content.Context): Boolean {
            return try {
                // ✅ 参考 f 目录的 MessageToolUse.isNotificationListenerEnabled()
                val enabledListeners = NotificationManagerCompat.getEnabledListenerPackages(context)
                enabledListeners.contains(context.packageName)
            } catch (e: Exception) {
                Log.e(TAG, "❌ 检查通知监听权限失败", e)
                false
            }
        }
        
        /**
         * 打开通知监听设置页面
         */
        fun openNotificationListenSettings(context: android.content.Context) {
            try {
                // ✅ 参考 f 目录的 MessageToolUse.openNotificationListenSettings()
                val intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(intent)
                Log.i(TAG, "✅ 已打开通知监听设置页面")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 打开通知监听设置页面失败", e)
            }
        }
    }

    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    override fun onCreate() {
        super.onCreate()
        instance = this
        Log.i(TAG, "🚀 通知监听服务已创建")
    }

    override fun onDestroy() {
        super.onDestroy()
        instance = null
        serviceScope.cancel()
        Log.i(TAG, "🛑 通知监听服务已销毁")
    }

    override fun onListenerConnected() {
        super.onListenerConnected()
        Log.i(TAG, "✅ 通知监听服务已连接（系统级保活）")
        
        // ✅ 参考 f 目录：通知监听服务可用于保活触发
        // 可以在这里启动其他保活服务
        try {
            serviceScope.launch {
                // 延迟启动，避免阻塞
                delay(1000L)
                startKeepAliveServices()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动保活服务失败", e)
        }
    }

    override fun onListenerDisconnected() {
        super.onListenerDisconnected()
        Log.w(TAG, "⚠️ 通知监听服务已断开")
    }

    /**
     * ✅ 参考 f 目录的 MessageToolUse.onNotificationPosted()
     * 当有新通知时触发
     */
    override fun onNotificationPosted(sbn: StatusBarNotification?) {
        super.onNotificationPosted(sbn)
        
        if (sbn == null) {
            return
        }
        
        try {
            val notification = sbn.notification
            if (notification == null || notification.extras == null) {
                return
            }
            
            val title = notification.extras.getString(android.app.Notification.EXTRA_TITLE, "")
            val text = notification.extras.getString(android.app.Notification.EXTRA_TEXT, "")
            val packageName = sbn.packageName
            
            Log.d(TAG, "📱 收到通知: $packageName - 标题: $title, 内容: $text")
            
            // ✅ 参考 f 目录：可以在这里处理特定应用的通知
            // 例如：微信、QQ 等应用的通知可以用于保活触发
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理通知失败", e)
        }
    }

    /**
     * ✅ 参考 f 目录的 MessageToolUse.onNotificationRemoved()
     * 当通知被移除时触发
     */
    override fun onNotificationRemoved(sbn: StatusBarNotification?) {
        super.onNotificationRemoved(sbn)
        
        if (sbn == null) {
            return
        }
        
        try {
            val notification = sbn.notification
            if (notification == null || notification.extras == null) {
                return
            }
            
            val title = notification.extras.getString(android.app.Notification.EXTRA_TITLE, "")
            val text = notification.extras.getString(android.app.Notification.EXTRA_TEXT, "")
            val packageName = sbn.packageName
            
            Log.d(TAG, "🗑️ 通知已移除: $packageName - 标题: $title, 内容: $text")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理通知移除失败", e)
        }
    }

    /**
     * 启动保活服务（通知监听服务作为系统级保活机制）
     */
    private fun startKeepAliveServices() {
        try {
            Log.i(TAG, "🛡️ 通知监听服务启动保活服务")
            
            // 启动主前台服务
            val foregroundIntent = Intent(this, RemoteControlForegroundService::class.java)
            if (Build.VERSION.SDK_INT >= 26) {
                startForegroundService(foregroundIntent)
            } else {
                startService(foregroundIntent)
            }
            Log.i(TAG, "✅ 主前台服务已启动（通知监听服务保活）")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动保活服务失败", e)
        }
    }
}

