package com.hikoncont.service.modules

import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.manager.GestureController
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.*

/**
 * 权限界面自动化管理器
 * 负责权限界面自动化处理
 * 
 * 主要职责:
 * - 权限页面自动检测
 * - 权限申请流程控制
 * - 权限按钮识别和点击
 * - 悬浮窗权限自动化
 * - 权限异常处理
 * - 权限状态监控
 */
class PermissionUIManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "PermissionUIManager"
    }
    
    // 依赖项
    private lateinit var gestureController: GestureController
    
    // 协程作用域
    private val permissionScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    // 状态变量
    private var isInitialized = false
    private var isProcessingPermission = false
    
    /**
     * 初始化权限UI管理器
     */
    fun initialize() {
        try {
            Log.i(TAG, "🔐 初始化权限UI管理器")
            
            // 初始化手势控制器
            gestureController = GestureController(service)
            
            isInitialized = true
            Log.i(TAG, "✅ 权限UI管理器初始化完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 权限UI管理器初始化失败", e)
        }
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            Log.d(TAG, "🧹 开始清理权限UI管理器资源")
            
            permissionScope.cancel()
            isInitialized = false
            isProcessingPermission = false
            
            Log.d(TAG, "✅ 权限UI管理器资源清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理权限UI管理器资源失败", e)
        }
    }
    
    /**
     * 自动点击悬浮窗权限开启按钮 - 主入口
     */
    fun autoClickOverlayPermissionButton(): Boolean {
        return try {
            Log.i(TAG, "🎯 开始自动点击悬浮窗权限开启按钮")
            
            if (isProcessingPermission) {
                Log.w(TAG, "⚠️ 权限处理正在进行中，跳过重复调用")
                return false
            }
            
            isProcessingPermission = true
            
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "❌ 无法获取根节点")
                isProcessingPermission = false
                return false
            }
            
            // 安全检查：确保只操作自己应用的权限页面
            if (!isOurAppPermissionPage(rootNode)) {
                Log.w(TAG, "🚫 当前页面不是我们应用的权限页面，跳过自动点击")
                rootNode.recycle()
                isProcessingPermission = false
                return false
            }
            
            Log.i(TAG, "✅ 确认是我们应用的权限页面，开始权限处理")
            
            var success = false
            
            // 策略1: 查找应用节点附近的开关
            success = findAndClickAppNodeSwitch(rootNode)
            
            // 策略2: 查找权限描述文本并点击
            if (!success) {
                success = findAndClickPermissionDescription(rootNode)
            }
            
            // 策略3: 查找开关控件
            if (!success) {
                success = findAndClickSwitchControls(rootNode)
            }
            
            // 策略4: 查找ON/OFF文本
            if (!success) {
                success = findAndClickOnOffText(rootNode)
            }
            
            // 策略5: 通用可点击元素分析
            if (!success) {
                success = findAndClickGenericPermissionButton(rootNode)
            }
            
            rootNode.recycle()
            isProcessingPermission = false
            
            if (success) {
                Log.i(TAG, "🎉 悬浮窗权限处理成功")
            } else {
                Log.w(TAG, "⚠️ 所有策略都失败，无法自动处理权限")
            }
            
            success
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 自动点击悬浮窗权限按钮失败", e)
            isProcessingPermission = false
            false
        }
    }
    
    /**
     * 检查悬浮窗权限页面是否有效
     */
    fun checkOverlayPermissionPageValid(): Boolean {
        return try {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "🔍 页面检查：无法获取根节点")
                return false
            }
            
            val packageName = rootNode.packageName?.toString()
            Log.d(TAG, "🔍 页面检查：当前包名=$packageName")
            
            // 检查是否在系统设置页面
            val isSettingsPage = packageName?.contains("settings", ignoreCase = true) == true ||
                                packageName?.contains("systemui", ignoreCase = true) == true ||
                                packageName?.contains("permission", ignoreCase = true) == true
            
            if (!isSettingsPage) {
                Log.w(TAG, "🔍 页面检查：不在设置页面，当前包名=$packageName")
                rootNode.recycle()
                return false
            }
            
            // 检查是否能找到悬浮窗相关的UI元素
            val hasOverlayElements = hasOverlayPermissionElements(rootNode)
            
            rootNode.recycle()
            
            Log.d(TAG, "🔍 页面检查：设置页面=$isSettingsPage, 悬浮窗元素=$hasOverlayElements")
            return hasOverlayElements
            
        } catch (e: Exception) {
            Log.e(TAG, "🔍 页面检查失败", e)
            false
        }
    }
    
    /**
     * 检查是否为我们应用的权限页面
     */
    private fun isOurAppPermissionPage(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            val packageName = rootNode.packageName?.toString() ?: ""
            
            // 检查是否在已知的权限管理页面
            val validPackages = setOf(
                "com.android.settings",
                "com.android.permissioncontroller", 
                "com.lge.appsettings",
                "com.samsung.android.permissioncontroller",
                "com.miui.securitycenter",
                "com.coloros.safecenter",
                "com.huawei.systemmanager"
            )
            
            if (packageName !in validPackages) {
                Log.d(TAG, "🔍 不在已知的权限管理页面，继续检查页面内容")
            } else {
                Log.i(TAG, "✅ 在已知权限管理页面: $packageName")
            }
            
            // 查找我们应用的标识
            val ourAppIdentifiers = listOf(
                "com.hikoncont",
                "Remote Control",
                "RemoteControl", 
                "远程控制",
                "Android Remote Control"
            )
            
            var foundOurApp = false
            
            // 在已知权限页面中查找应用标识
            if (packageName in validPackages) {
                for (identifier in ourAppIdentifiers) {
                    val foundNode = findNodeByText(rootNode, identifier)
                    if (foundNode != null) {
                        Log.i(TAG, "✅ 在权限页面找到我们应用的标识: $identifier")
                        foundNode.recycle()
                        foundOurApp = true
                        break
                    }
                }
            }
            
            // 如果没有找到明确标识，进行补充检查
            if (!foundOurApp) {
                Log.w(TAG, "⚠️ 未找到我们应用的明确标识，进行补充检查")
                
                // 检查是否包含悬浮窗相关文本
                val overlayTexts = listOf(
                    "显示在其他应用的上层", "悬浮窗权限", "悬浮窗",
                    "Display over other apps", "Overlay permission",
                    "在其他应用上层显示", "应用上层显示", "系统窗口"
                )
                
                for (overlayText in overlayTexts) {
                    val overlayNode = findNodeByText(rootNode, overlayText)
                    if (overlayNode != null) {
                        Log.i(TAG, "✅ 找到悬浮窗权限相关文本: $overlayText")
                        overlayNode.recycle()
                        foundOurApp = true
                        break
                    }
                }
                
                // 检查开关文本
                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
                        }
                    }
                }
            }
            
            foundOurApp
            
        } catch (e: Exception) {
            Log.e(TAG, "检查应用权限页面失败", e)
            false
        }
    }
    
    /**
     * 检查是否有悬浮窗权限相关元素
     */
    private fun hasOverlayPermissionElements(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            // 检查悬浮窗相关文本
            val overlayTexts = listOf(
                "悬浮窗", "显示在其他应用", "Display over", "Overlay",
                "在其他应用上层显示", "系统级窗口"
            )
            
            for (text in overlayTexts) {
                val node = findNodeByText(rootNode, text)
                if (node != null) {
                    node.recycle()
                    return true
                }
            }
            
            // 检查开关控件
            val switchTypes = listOf(
                "android.widget.Switch",
                "android.widget.ToggleButton", 
                "androidx.appcompat.widget.SwitchCompat"
            )
            
            for (switchType in switchTypes) {
                val switches = findNodesByViewType(rootNode, switchType)
                if (switches.isNotEmpty()) {
                    switches.forEach { it.recycle() }
                    return true
                }
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "检查悬浮窗权限元素失败", e)
            false
        }
    }
    
    /**
     * 策略1: 查找应用节点附近的开关
     */
    private fun findAndClickAppNodeSwitch(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.i(TAG, "🔍 策略1: 查找应用节点附近的开关")
            
            val appNames = listOf("Remote Control", "RemoteControl", "远程控制")
            
            for (appName in appNames) {
                val appNode = findNodeByText(rootNode, appName)
                if (appNode != null) {
                    Log.i(TAG, "✅ 找到应用节点: $appName")
                    
                    // 查找应用节点的可点击父容器
                    val clickableParent = findClickableParent(appNode)
                    if (clickableParent != null) {
                        Log.i(TAG, "🎯 尝试点击应用节点的父容器")
                        
                        val success = tryMultipleClickMethods(clickableParent, "应用节点父容器")
                        if (success) {
                            appNode.recycle()
                            clickableParent.recycle()
                            return true
                        }
                        clickableParent.recycle()
                    }
                    
                    // 查找应用节点附近的开关控件
                    val nearbySwitch = findNearbySwitch(appNode)
                    if (nearbySwitch != null) {
                        Log.i(TAG, "🎯 找到应用节点附近的开关")
                        
                        val success = tryMultipleClickMethods(nearbySwitch, "附近开关")
                        if (success) {
                            appNode.recycle()
                            nearbySwitch.recycle()
                            return true
                        }
                        nearbySwitch.recycle()
                    }
                    
                    appNode.recycle()
                }
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "策略1失败", e)
            false
        }
    }
    
    /**
     * 策略2: 查找权限描述文本并点击
     */
    private fun findAndClickPermissionDescription(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.i(TAG, "🔍 策略2: 查找权限描述文本")
            
            val permissionTexts = listOf(
                "显示在其他应用的上层", "允许在上层显示",
                "悬浮窗权限", "系统级窗口", "覆盖显示",
                "Display over other apps", "Draw over other apps"
            )
            
            val actionTexts = listOf(
                "允许", "开启", "启用", "打开", "激活",
                "Allow", "Enable", "Turn on", "Grant"
            )
            
            // 查找权限描述文本
            for (permText in permissionTexts) {
                val permNode = findNodeByText(rootNode, permText)
                if (permNode != null) {
                    Log.i(TAG, "✅ 找到权限描述: $permText")
                    
                    // 查找描述文本的可点击父容器
                    val clickableParent = findClickableParent(permNode)
                    if (clickableParent != null) {
                        val success = tryMultipleClickMethods(clickableParent, "权限描述父容器")
                        if (success) {
                            permNode.recycle()
                            clickableParent.recycle()
                            return true
                        }
                        clickableParent.recycle()
                    }
                    
                    permNode.recycle()
                }
            }
            
            // 查找操作按钮
            for (actionText in actionTexts) {
                val actionNode = findNodeByText(rootNode, actionText)
                if (actionNode != null && actionNode.isClickable) {
                    Log.i(TAG, "✅ 找到操作按钮: $actionText")
                    
                    val success = tryMultipleClickMethods(actionNode, "操作按钮")
                    if (success) {
                        actionNode.recycle()
                        return true
                    }
                    
                    actionNode.recycle()
                }
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "策略2失败", e)
            false
        }
    }
    
    /**
     * 策略3: 查找开关控件
     */
    private fun findAndClickSwitchControls(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.i(TAG, "🔍 策略3: 查找开关控件")
            
            val switchTypes = listOf(
                "android.widget.Switch",
                "android.widget.ToggleButton",
                "androidx.appcompat.widget.SwitchCompat"
            )
            
            for (switchType in switchTypes) {
                val switches = findNodesByViewType(rootNode, switchType)
                Log.i(TAG, "找到 ${switches.size} 个 $switchType 控件")
                
                for ((index, switchNode) in switches.withIndex()) {
                    if (!switchNode.isChecked && switchNode.isEnabled) {
                        Log.i(TAG, "🎯 尝试切换Switch[$index]: ${switchNode.className}")
                        
                        val success = tryMultipleClickMethods(switchNode, "Switch控件")
                        if (success) {
                            switches.forEach { it.recycle() }
                            return true
                        }
                    }
                }
                
                switches.forEach { it.recycle() }
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "策略3失败", e)
            false
        }
    }
    
    /**
     * 策略4: 查找ON/OFF文本
     */
    private fun findAndClickOnOffText(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.i(TAG, "🔍 策略4: 查找ON/OFF文本")
            
            // 先检查权限状态
            val actuallyEnabled = Settings.canDrawOverlays(context)
            if (actuallyEnabled) {
                Log.i(TAG, "✅ 系统确认权限已开启，无需点击")
                return true
            }
            
            val offTexts = listOf("OFF", "关", "关闭", "禁用", "Disabled", "No", "否")
            
            for (offText in offTexts) {
                val offNode = findNodeByText(rootNode, offText)
                if (offNode != null) {
                    Log.i(TAG, "✅ 找到OFF文本: $offText")
                    
                    val success = tryMultipleClickMethods(offNode, "OFF文本")
                    if (success) {
                        offNode.recycle()
                        return true
                    }
                    
                    offNode.recycle()
                }
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "策略4失败", e)
            false
        }
    }
    
    /**
     * 策略5: 通用可点击元素分析
     */
    private fun findAndClickGenericPermissionButton(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.i(TAG, "🔍 策略5: 通用可点击元素分析")
            
            val allClickableNodes = mutableListOf<AccessibilityNodeInfo>()
            findAllClickableNodes(rootNode, allClickableNodes)
            
            val potentialNodes = allClickableNodes.filter { node ->
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                val className = node.className?.toString()?.lowercase() ?: ""
                
                // 过滤潜在的权限相关控件
                text.contains("switch") || text.contains("toggle") ||
                desc.contains("switch") || desc.contains("toggle") ||
                className.contains("switch") || className.contains("toggle") ||
                className.contains("button")
            }
            
            Log.i(TAG, "过滤出 ${potentialNodes.size} 个可能的权限控件")
            
            for ((index, node) in potentialNodes.withIndex()) {
                Log.i(TAG, "🎯 尝试点击潜在权限控件[$index]: ${node.className}")
                
                val success = tryMultipleClickMethods(node, "潜在权限控件")
                if (success) {
                    allClickableNodes.forEach { it.recycle() }
                    return true
                }
            }
            
            allClickableNodes.forEach { it.recycle() }
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "策略5失败", e)
            false
        }
    }
    
    /**
     * 尝试多种点击方法
     */
    private fun tryMultipleClickMethods(node: AccessibilityNodeInfo, description: String): Boolean {
        val originalChecked = node.isChecked
        
        Log.d(TAG, "尝试多种点击方法: $description")
        
        // 方法1: 直接点击
        try {
            val click = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            if (click && waitAndCheckStateChange(node, originalChecked, "直接点击")) {
                return true
            }
        } catch (e: Exception) {
            Log.w(TAG, "直接点击异常: ${e.message}")
        }
        
        // 方法2: 长按
        try {
            val longClick = node.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK)
            if (longClick && waitAndCheckStateChange(node, originalChecked, "长按")) {
                return true
            }
        } catch (e: Exception) {
            Log.w(TAG, "长按异常: ${e.message}")
        }
        
        // 方法3: 坐标点击
        if (::gestureController.isInitialized) {
            try {
                val rect = Rect()
                node.getBoundsInScreen(rect)
                
                val clickPositions = listOf(
                    Pair(rect.left + (rect.right - rect.left) * 0.9f, (rect.top + rect.bottom) / 2f),
                    Pair(rect.left + (rect.right - rect.left) * 0.8f, (rect.top + rect.bottom) / 2f),
                    Pair((rect.left + rect.right) / 2f, (rect.top + rect.bottom) / 2f)
                )
                
                for ((x, y) in clickPositions) {
                    gestureController.performClick(x, y)
                    if (waitAndCheckStateChange(node, originalChecked, "坐标点击")) {
                        return true
                    }
                }
            } catch (e: Exception) {
                Log.w(TAG, "坐标点击异常: ${e.message}")
            }
        }
        
        // 方法4: 双击
        try {
            val click1 = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            Thread.sleep(100)
            val click2 = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            if (click1 && click2 && waitAndCheckStateChange(node, originalChecked, "双击")) {
                return true
            }
        } catch (e: Exception) {
            Log.w(TAG, "双击异常: ${e.message}")
        }
        
        // 最后检查系统权限状态
        try {
            Thread.sleep(1000)
            val actuallyEnabled = Settings.canDrawOverlays(context)
            if (actuallyEnabled) {
                Log.i(TAG, "✅ 虽然UI状态未改变，但系统权限已开启！")
                return true
            }
        } catch (e: Exception) {
            Log.w(TAG, "系统权限检查异常: ${e.message}")
        }
        
        return false
    }
    
    /**
     * 等待并检查状态变化
     */
    private fun waitAndCheckStateChange(node: AccessibilityNodeInfo, originalChecked: Boolean, method: String): Boolean {
        Log.d(TAG, "⏳ 等待${method}的状态更新...")
        
        val beforePermission = Settings.canDrawOverlays(context)
        
        val maxChecks = 10  // 统一使用10次检查，确保Android 11+设备兼容性
        val checkInterval = 300L
        
        for (i in 1..maxChecks) {
            Thread.sleep(checkInterval)
            
            try {
                // 优先检查系统权限状态
                val currentPermission = Settings.canDrawOverlays(context)
                if (currentPermission != beforePermission) {
                    Log.i(TAG, "✅ ${method}成功！系统权限状态已改变")
                    return true
                }
                
                // 检查节点状态变化
                try {
                    val currentChecked = node.isChecked
                    if (currentChecked != originalChecked) {
                        Log.i(TAG, "✅ ${method}成功！节点状态已改变")
                        return true
                    }
                } catch (e: Exception) {
                    Log.d(TAG, "节点状态检查异常: ${e.message}")
                }
                
            } catch (e: Exception) {
                Log.w(TAG, "检查状态时出错: ${e.message}")
            }
        }
        
        // 最终检查
        try {
            Thread.sleep(1000)
            val finalPermission = Settings.canDrawOverlays(context)
            if (finalPermission) {
                Log.i(TAG, "✅ ${method}最终成功！系统确认权限已获取")
                return true
            }
        } catch (e: Exception) {
            Log.w(TAG, "最终权限检查失败: ${e.message}")
        }
        
        return false
    }
    
    /**
     * 查找可点击的父节点
     */
    private fun findClickableParent(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        var parent = node.parent
        while (parent != null) {
            if (parent.isClickable) {
                return parent
            }
            val nextParent = parent.parent
            parent.recycle()
            parent = nextParent
        }
        return null
    }
    
    /**
     * 查找附近的开关控件
     */
    private fun findNearbySwitch(appNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            val appRect = Rect()
            appNode.getBoundsInScreen(appRect)
            
            val rootNode = service.rootInActiveWindow ?: return null
            val allSwitches = mutableListOf<AccessibilityNodeInfo>()
            
            fun findSwitches(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10) return
                
                if (node.className?.toString()?.contains("Switch") == true && node.isClickable) {
                    allSwitches.add(node)
                }
                
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let {
                        findSwitches(it, depth + 1)
                    }
                }
            }
            
            findSwitches(rootNode)
            rootNode.recycle()
            
            // 查找距离应用节点最近的开关
            var nearestSwitch: AccessibilityNodeInfo? = null
            var minDistance = Float.MAX_VALUE
            
            for (switch in allSwitches) {
                val switchRect = Rect()
                switch.getBoundsInScreen(switchRect)
                
                val distance = calculateDistance(appRect, switchRect)
                if (distance < minDistance) {
                    nearestSwitch?.recycle()
                    nearestSwitch = switch
                    minDistance = distance
                } else {
                    switch.recycle()
                }
            }
            
            nearestSwitch
            
        } catch (e: Exception) {
            Log.e(TAG, "查找附近开关失败", e)
            null
        }
    }
    
    /**
     * 计算两个矩形的距离
     */
    private fun calculateDistance(rect1: Rect, rect2: Rect): Float {
        val dx = (rect1.centerX() - rect2.centerX()).toFloat()
        val dy = (rect1.centerY() - rect2.centerY()).toFloat()
        return kotlin.math.sqrt(dx * dx + dy * dy)
    }
    
    /**
     * 通过文本查找节点
     */
    private fun findNodeByText(rootNode: AccessibilityNodeInfo, targetText: String): AccessibilityNodeInfo? {
        return try {
            var foundNode: AccessibilityNodeInfo? = null
            
            fun searchByText(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 15 || foundNode != null) return
                
                val text = node.text?.toString()?.trim() ?: ""
                val desc = node.contentDescription?.toString()?.trim() ?: ""
                
                if (text.contains(targetText, ignoreCase = true) || 
                    desc.contains(targetText, ignoreCase = true)) {
                    foundNode = node
                    return
                }
                
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let {
                        searchByText(it, depth + 1)
                        if (foundNode == null) {
                            it.recycle()
                        }
                    }
                }
            }
            
            searchByText(rootNode)
            foundNode
            
        } catch (e: Exception) {
            Log.e(TAG, "通过文本查找节点失败", e)
            null
        }
    }
    
    /**
     * 通过视图类型查找节点
     */
    private fun findNodesByViewType(rootNode: AccessibilityNodeInfo, viewType: String): List<AccessibilityNodeInfo> {
        val nodes = mutableListOf<AccessibilityNodeInfo>()
        
        try {
            fun searchByViewType(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 15) return
                
                if (node.className?.toString() == viewType) {
                    nodes.add(node)
                }
                
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let {
                        searchByViewType(it, depth + 1)
                    }
                }
            }
            
            searchByViewType(rootNode)
        } catch (e: Exception) {
            Log.e(TAG, "通过视图类型查找节点失败", e)
        }
        
        return nodes
    }
    
    /**
     * 查找所有可点击节点
     */
    private fun findAllClickableNodes(rootNode: AccessibilityNodeInfo, nodes: MutableList<AccessibilityNodeInfo>) {
        try {
            fun collectClickableNodes(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 15) return
                
                if (node.isClickable) {
                    nodes.add(node)
                }
                
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let {
                        collectClickableNodes(it, depth + 1)
                    }
                }
            }
            
            collectClickableNodes(rootNode)
        } catch (e: Exception) {
            Log.e(TAG, "收集可点击节点失败", e)
        }
    }
    
    /**
     * 打开悬浮窗权限设置页面
     */
    fun openOverlayPermissionSettings() {
        try {
            Log.d(TAG, "🚀 打开悬浮窗权限设置页面")
            
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply {
                data = Uri.parse("package:${context.packageName}")
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            
            context.startActivity(intent)
            Log.d(TAG, "✅ 已发送打开悬浮窗权限设置的Intent")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开悬浮窗权限设置失败", e)
        }
    }
    
    /**
     * 处理权限流程 - 异步版本
     */
    suspend fun handlePermissionFlow(): Boolean {
        return withContext(permissionScope.coroutineContext) {
            try {
                Log.i(TAG, "🚀 开始处理权限流程")
                
                // 检查是否需要悬浮窗权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(context)) {
                    Log.i(TAG, "⚠️ 需要悬浮窗权限，开始自动获取")
                    
                    // 打开权限设置页面
                    openOverlayPermissionSettings()
                    
                    // 等待页面加载
                    delay(2500)
                    
                    // 尝试自动点击
                    val maxAttempts = 4
                    var permissionObtained = false
                    
                    for (attempt in 1..maxAttempts) {
                        Log.i(TAG, "🎯 第${attempt}次尝试自动处理权限")
                        
                        // 检查页面状态
                        val pageValid = checkOverlayPermissionPageValid()
                        if (!pageValid) {
                            Log.w(TAG, "⚠️ 当前页面无效，重新打开设置页面")
                            openOverlayPermissionSettings()
                            delay(2000)
                        }
                        
                        // 自动点击
                        val success = autoClickOverlayPermissionButton()
                        
                        val waitTime = when (attempt) {
                            1 -> 2000L
                            2 -> 2500L  
                            3 -> 3000L
                            else -> 3500L
                        }
                        delay(waitTime)
                        
                        // 检查权限是否获取成功
                        if (Settings.canDrawOverlays(context)) {
                            Log.i(TAG, "✅ 悬浮窗权限获取成功 (第${attempt}次尝试)")
                            permissionObtained = true
                            break
                        } else {
                            Log.w(TAG, "⚠️ 第${attempt}次尝试失败，权限仍未获取")
                            if (attempt < maxAttempts) {
                                delay(1500)
                            }
                        }
                    }
                    
                    if (permissionObtained) {
                        Log.i(TAG, "🎉 悬浮窗权限获取成功！")
                    } else {
                        Log.i(TAG, "ℹ️ 悬浮窗权限未获取，但不影响核心功能")
                    }
                    
                    return@withContext permissionObtained
                } else {
                    Log.i(TAG, "✅ 悬浮窗权限已存在或不需要")
                    return@withContext true
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理权限流程失败", e)
                false
            }
        }
    }
    
    /**
     * 检测权限页面变化
     */
    fun detectPermissionPageChange(): Boolean {
        return try {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                return false
            }
            
            val currentPackage = rootNode.packageName?.toString() ?: ""
            rootNode.recycle()
            
            // 检查是否在权限相关页面
            val isPermissionPage = currentPackage.contains("settings", ignoreCase = true) ||
                                  currentPackage.contains("permission", ignoreCase = true) ||
                                  currentPackage.contains("systemui", ignoreCase = true)
            
            Log.d(TAG, "🔍 权限页面检测: 包名=$currentPackage, 权限页面=$isPermissionPage")
            isPermissionPage
            
        } catch (e: Exception) {
            Log.e(TAG, "检测权限页面变化失败", e)
            false
        }
    }
    
    /**
     * 获取权限UI管理器状态
     */
    fun isInitialized(): Boolean = isInitialized
    
    /**
     * 检查是否正在处理权限
     */
    fun isProcessingPermission(): Boolean = isProcessingPermission
} 