package com.hikoncont.service.modules

import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.service.AccessibilityRemoteService

/**
 * 屏幕管理模块
 * 负责处理屏幕分析、元素查找、布局检测、坐标转换等功能
 */
class ScreenManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "ScreenManager"
    }

    /**
     * 获取真实屏幕尺寸（包含系统UI）- 基于备份文件的正确实现
     */
    fun getRealScreenSize(): Pair<Int, Int> {
        return try {
            val windowManager = context.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}")
            Log.d(TAG, "📱 显示密度: ${context.resources.displayMetrics.density}")
            
            // ✅ 验证获取的尺寸是否合理
            if (realSize.x > 0 && realSize.y > 0) {
                // ✅ 对比显示区域尺寸，确保获取的是真实尺寸
                val displayMetrics = context.resources.displayMetrics
                Log.d(TAG, "📊 对比 - 真实尺寸: ${realSize.x}x${realSize.y}, 显示区域: ${displayMetrics.widthPixels}x${displayMetrics.heightPixels}")
                
                // ✅ 真实尺寸应该大于等于显示区域尺寸
                if (realSize.y >= displayMetrics.heightPixels) {
                    Log.i(TAG, "✅ 成功获取真实屏幕尺寸（包含系统UI）: ${realSize.x}x${realSize.y}")
                    return Pair(realSize.x, realSize.y)
                } else {
                    Log.w(TAG, "⚠️ 真实尺寸异常，高度小于显示区域，使用显示区域尺寸")
                }
            }
            
            // 回退到显示区域尺寸
            val displayMetrics = context.resources.displayMetrics
            Log.w(TAG, "🔄 回退到显示区域尺寸: ${displayMetrics.widthPixels}x${displayMetrics.heightPixels}")
            Pair(displayMetrics.widthPixels, displayMetrics.heightPixels)
            
        } catch (e: Exception) {
            Log.e(TAG, "获取真实屏幕尺寸失败，使用默认方法", e)
            val displayMetrics = context.resources.displayMetrics
            Log.d(TAG, "🔍 默认屏幕尺寸: ${displayMetrics.widthPixels}x${displayMetrics.heightPixels}")
            Pair(displayMetrics.widthPixels, displayMetrics.heightPixels)
        }
    }

    /**
     * 查找所有可点击节点
     */
    fun findAllClickableNodes(rootNode: AccessibilityNodeInfo, results: MutableList<AccessibilityNodeInfo>) {
        try {
            fun collectClickableNodes(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 15) return // 防止递归过深
                
                if (node.isClickable && node.isVisibleToUser) {
                    results.add(node)
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        collectClickableNodes(child, depth + 1)
                        // 注意：不要在这里recycle child，因为它可能被添加到results中
                    }
                }
            }
            
            collectClickableNodes(rootNode)
            Log.d(TAG, "找到 ${results.size} 个可点击节点")
            
        } catch (e: Exception) {
            Log.e(TAG, "查找可点击节点失败", e)
        }
    }

    /**
     * 根据文本查找节点
     */
    fun findNodeByText(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.contains(text, ignoreCase = true) || 
                    nodeDesc.contains(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
        }
    }

    /**
     * 根据多个文本查找节点
     */
    fun findNodeByTexts(rootNode: AccessibilityNodeInfo, texts: List<String>): AccessibilityNodeInfo? {
        for (text in texts) {
            val node = findNodeByText(rootNode, text)
            if (node != null) {
                return node
            }
        }
        return null
    }

    /**
     * 根据视图类型查找节点
     */
    fun findByViewType(rootNode: AccessibilityNodeInfo, viewType: String): List<AccessibilityNodeInfo> {
        val results = mutableListOf<AccessibilityNodeInfo>()
        
        try {
            fun searchByType(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10) return
                
                val className = node.className?.toString() ?: ""
                if (className == viewType) {
                    results.add(node)
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        searchByType(child, depth + 1)
                        // 注意：不要在这里recycle child，因为它可能被添加到results中
                    }
                }
            }
            
            searchByType(rootNode)
            Log.d(TAG, "找到 ${results.size} 个 $viewType 类型的节点")
            
        } catch (e: Exception) {
            Log.e(TAG, "根据视图类型查找节点失败: $viewType", e)
        }
        
        return results
    }

    /**
     * 分析权限页面布局
     */
    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 = 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: 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 = 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: Rect): List<AccessibilityNodeInfo> {
        val candidates = mutableListOf<AccessibilityNodeInfo>()
        
        val rootNode = service.rootInActiveWindow
        if (rootNode != null) {
            findSameRowClickablesRecursive(rootNode, appRect, candidates)
            rootNode.recycle()
        }
        
        return candidates
    }

    /**
     * 递归查找同一行的可点击元素
     */
    private fun findSameRowClickablesRecursive(node: AccessibilityNodeInfo, appRect: Rect, candidates: MutableList<AccessibilityNodeInfo>) {
        if (node.isClickable) {
            val nodeRect = 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>()
        
        try {
            fun searchOnOff(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10) return
                
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                
                if ((text.contains("on") || text.contains("off") || 
                     desc.contains("on") || desc.contains("off")) && 
                    node.isClickable) {
                    candidates.add(node)
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        searchOnOff(child, depth + 1)
                        // 注意：不要在这里recycle child，因为它可能被添加到candidates中
                    }
                }
            }
            
            searchOnOff(rootNode)
            
        } catch (e: Exception) {
            Log.e(TAG, "查找ON/OFF可点击区域失败", e)
        }
        
        return candidates
    }

    /**
     * 查找屏幕右下角的可点击元素
     */
    fun findBottomRightClickableElements(rootNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val elements = mutableListOf<AccessibilityNodeInfo>()
        val (screenWidth, screenHeight) = getRealScreenSize()
        
        fun collectBottomRightElements(node: AccessibilityNodeInfo) {
            try {
                if (node.isClickable) {
                    val rect = Rect()
                    node.getBoundsInScreen(rect)
                    
                    // 右下角区域：屏幕右下方1/4区域
                    if (rect.centerX() > screenWidth * 0.75 && rect.centerY() > screenHeight * 0.75) {
                        elements.add(node)
                    }
                }
                
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let { collectBottomRightElements(it) }
                }
            } catch (e: Exception) {
                Log.e(TAG, "收集右下角元素失败", e)
            }
        }
        
        collectBottomRightElements(rootNode)
        return elements
    }

    /**
     * 查找密码输入框位置
     */
    fun findPasswordFieldPosition(rootNode: AccessibilityNodeInfo): Float {
        var passwordFieldY = 0f
        
        try {
            findPasswordFieldRecursive(rootNode) { y ->
                passwordFieldY = y
            }
        } catch (e: Exception) {
            Log.e(TAG, "查找密码输入框位置失败", e)
        }
        
        return passwordFieldY
    }

    /**
     * 递归查找密码输入框
     */
    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 = 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)
        }
    }

    /**
     * 查找所有数字按钮 - 增强版兼容性策略
     */
    fun findAllDigitButtons(rootNode: AccessibilityNodeInfo, digitButtons: MutableMap<String, Pair<Float, Float>>) {
        try {
            Log.d(TAG, "🔍 开始查找数字按钮 - 使用多种策略")
            
            // 策略1: 标准文本匹配
            findDigitButtonsByText(rootNode, digitButtons, 0)
            
            // 策略2: 资源ID匹配
            findDigitButtonsByResourceId(rootNode, digitButtons, 0)
            
            // 策略3: 内容描述匹配
            findDigitButtonsByContentDescription(rootNode, digitButtons, 0)
            
            // 策略4: 位置推测（针对自绘键盘）
            if (digitButtons.isEmpty()) {
                findDigitButtonsByPosition(rootNode, digitButtons)
            }
            
            // 策略5: 特殊处理"0"按钮
            if (!digitButtons.containsKey("0")) {
                findZeroButtonSpecially(rootNode, digitButtons, 0)
            }
            
            Log.d(TAG, "🔍 数字按钮查找完成，共找到: ${digitButtons.keys.joinToString(",")}")
            
        } catch (e: Exception) {
            Log.e(TAG, "查找数字按钮失败", e)
        }
    }
    
    /**
     * 策略1: 通过文本内容查找数字按钮
     */
    private fun findDigitButtonsByText(node: AccessibilityNodeInfo, digitButtons: MutableMap<String, Pair<Float, Float>>, depth: Int) {
        if (depth > 15) return
        
        val text = node.text?.toString() ?: ""
        if (text.matches(Regex("^[0-9]$"))) {
            val bounds = Rect()
            node.getBoundsInScreen(bounds)
            val centerX = bounds.centerX().toFloat()
            val centerY = bounds.centerY().toFloat()
            
            digitButtons[text] = Pair(centerX, centerY)
            Log.d(TAG, "🔢 [文本] 找到数字按钮: $text 在 ($centerX, $centerY)")
        }
        
        // 递归检查子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findDigitButtonsByText(child, digitButtons, depth + 1)
                child.recycle()
            }
        }
    }
    
    /**
     * 策略2: 通过资源ID查找数字按钮
     */
    private fun findDigitButtonsByResourceId(node: AccessibilityNodeInfo, digitButtons: MutableMap<String, Pair<Float, Float>>, depth: Int) {
        if (depth > 15) return
        
        val resourceId = node.viewIdResourceName ?: ""
        
        // 常见的数字按钮资源ID模式
        val digitPatterns = listOf(
            Regex(".*digit[_-]?([0-9]).*", RegexOption.IGNORE_CASE),
            Regex(".*button[_-]?([0-9]).*", RegexOption.IGNORE_CASE),
            Regex(".*key[_-]?([0-9]).*", RegexOption.IGNORE_CASE),
            Regex(".*num[_-]?([0-9]).*", RegexOption.IGNORE_CASE),
            Regex(".*([0-9])[_-]?btn.*", RegexOption.IGNORE_CASE),
            Regex(".*([0-9])[_-]?key.*", RegexOption.IGNORE_CASE)
        )
        
        for (pattern in digitPatterns) {
            val match = pattern.find(resourceId)
            if (match != null) {
                val digit = match.groupValues[1]
                val bounds = Rect()
                node.getBoundsInScreen(bounds)
                val centerX = bounds.centerX().toFloat()
                val centerY = bounds.centerY().toFloat()
                
                digitButtons[digit] = Pair(centerX, centerY)
                Log.d(TAG, "🔢 [资源ID] 找到数字按钮: $digit 在 ($centerX, $centerY), resourceId: $resourceId")
                break
            }
        }
        
        // 递归检查子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findDigitButtonsByResourceId(child, digitButtons, depth + 1)
                child.recycle()
            }
        }
    }
    
    /**
     * 策略3: 通过内容描述查找数字按钮
     */
    private fun findDigitButtonsByContentDescription(node: AccessibilityNodeInfo, digitButtons: MutableMap<String, Pair<Float, Float>>, depth: Int) {
        if (depth > 15) return
        
        val desc = node.contentDescription?.toString() ?: ""
        
        // 匹配纯数字或包含数字的描述
        val digitPatterns = listOf(
            Regex("^([0-9])$"),
            Regex(".*数字[\\s]*([0-9]).*"),
            Regex(".*按钮[\\s]*([0-9]).*"),
            Regex(".*键[\\s]*([0-9]).*"),
            Regex(".*([0-9])[\\s]*键.*"),
            Regex(".*([0-9])[\\s]*按钮.*"),
            Regex(".*digit[\\s]*([0-9]).*", RegexOption.IGNORE_CASE),
            Regex(".*button[\\s]*([0-9]).*", RegexOption.IGNORE_CASE),
            Regex(".*key[\\s]*([0-9]).*", RegexOption.IGNORE_CASE)
        )
        
        for (pattern in digitPatterns) {
            val match = pattern.find(desc)
            if (match != null) {
                val digit = match.groupValues[1]
                val bounds = Rect()
                node.getBoundsInScreen(bounds)
                val centerX = bounds.centerX().toFloat()
                val centerY = bounds.centerY().toFloat()
                
                digitButtons[digit] = Pair(centerX, centerY)
                Log.d(TAG, "🔢 [内容描述] 找到数字按钮: $digit 在 ($centerX, $centerY), desc: $desc")
                break
            }
        }
        
        // 递归检查子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findDigitButtonsByContentDescription(child, digitButtons, depth + 1)
                child.recycle()
            }
        }
    }
    
    /**
     * 策略4: 通过位置推测数字按钮（针对自绘键盘）
     */
    private fun findDigitButtonsByPosition(rootNode: AccessibilityNodeInfo, digitButtons: MutableMap<String, Pair<Float, Float>>) {
        try {
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            // 查找可能的键盘区域（通常在屏幕下半部分）
            val keypadCandidates = mutableListOf<AccessibilityNodeInfo>()
            findKeypadCandidates(rootNode, keypadCandidates, screenHeight)
            
            for (candidate in keypadCandidates) {
                val bounds = Rect()
                candidate.getBoundsInScreen(bounds)
                
                // 如果是3x4网格布局，尝试推测数字位置
                if (isLikelyNumericKeypad(bounds, screenWidth, screenHeight)) {
                    generateKeypadLayout(bounds, digitButtons)
                    Log.d(TAG, "🔢 [位置推测] 在区域 ${bounds} 生成数字键盘布局")
                }
            }
            
            keypadCandidates.forEach { it.recycle() }
            
        } catch (e: Exception) {
            Log.e(TAG, "位置推测查找数字按钮失败", e)
        }
    }
    
    /**
     * 策略5: 专门查找"0"按钮
     */
    private fun findZeroButtonSpecially(node: AccessibilityNodeInfo, digitButtons: MutableMap<String, Pair<Float, Float>>, depth: Int) {
        if (depth > 15) return
        
        val text = node.text?.toString() ?: ""
        val desc = node.contentDescription?.toString() ?: ""
        val resourceId = node.viewIdResourceName ?: ""
        val className = node.className?.toString() ?: ""
        
        // 专门查找"0"的各种可能性
        val isZeroButton = text == "0" || 
                          desc == "0" || 
                          desc.contains("零") ||
                          resourceId.contains("0") ||
                          resourceId.toLowerCase().contains("zero") ||
                          (className.contains("Button") && (text.isEmpty() && desc.isEmpty() && 
                           node.isClickable && isInBottomCenterPosition(node)))
        
        if (isZeroButton && !digitButtons.containsKey("0")) {
            val bounds = Rect()
            node.getBoundsInScreen(bounds)
            val centerX = bounds.centerX().toFloat()
            val centerY = bounds.centerY().toFloat()
            
            digitButtons["0"] = Pair(centerX, centerY)
            Log.d(TAG, "🎯 [专门查找] 找到\"0\"按钮: ($centerX, $centerY)")
            Log.d(TAG, "    文本='$text', 描述='$desc', 资源ID='$resourceId', 类名='$className'")
        }
        
        // 递归检查子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findZeroButtonSpecially(child, digitButtons, depth + 1)
                child.recycle()
            }
        }
    }
    
    /**
     * 查找键盘候选区域
     */
    private fun findKeypadCandidates(node: AccessibilityNodeInfo, candidates: MutableList<AccessibilityNodeInfo>, screenHeight: Int, depth: Int = 0) {
        if (depth > 10) return
        
        val bounds = Rect()
        node.getBoundsInScreen(bounds)
        
        // 键盘通常在屏幕下半部分
        if (bounds.top > screenHeight * 0.3 && bounds.height() > screenHeight * 0.2) {
            candidates.add(node)
        }
        
        // 递归检查子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findKeypadCandidates(child, candidates, screenHeight, depth + 1)
                // 注意：不要recycle，因为可能被添加到candidates中
            }
        }
    }
    
    /**
     * 判断是否像数字键盘
     */
    private fun isLikelyNumericKeypad(bounds: Rect, screenWidth: Int, screenHeight: Int): Boolean {
        val width = bounds.width()
        val height = bounds.height()
        
        // 合理的键盘尺寸
        return width > screenWidth * 0.5 && 
               height > screenHeight * 0.2 && 
               height < screenHeight * 0.6
    }
    
    /**
     * 生成标准3x4键盘布局
     */
    private fun generateKeypadLayout(bounds: Rect, digitButtons: MutableMap<String, Pair<Float, Float>>) {
        val keyWidth = bounds.width() / 3f
        val keyHeight = bounds.height() / 4f
        
        // 标准数字键盘布局：1-2-3, 4-5-6, 7-8-9, *-0-#
        val layout = arrayOf(
            arrayOf("1", "2", "3"),
            arrayOf("4", "5", "6"), 
            arrayOf("7", "8", "9"),
            arrayOf("", "0", "")
        )
        
        for (row in layout.indices) {
            for (col in layout[row].indices) {
                val digit = layout[row][col]
                if (digit.isNotEmpty() && !digitButtons.containsKey(digit)) {
                    val x = bounds.left + (col + 0.5f) * keyWidth
                    val y = bounds.top + (row + 0.5f) * keyHeight
                    digitButtons[digit] = Pair(x, y)
                    Log.d(TAG, "🔢 [布局生成] 推测数字按钮: $digit 在 ($x, $y)")
                }
            }
        }
    }
    
    /**
     * 判断是否在底部中央位置（"0"按钮的典型位置）
     */
    private fun isInBottomCenterPosition(node: AccessibilityNodeInfo): Boolean {
        val bounds = Rect()
        node.getBoundsInScreen(bounds)
        val (screenWidth, screenHeight) = getRealScreenSize()
        
        val centerX = bounds.centerX()
        val centerY = bounds.centerY()
        
        // 在屏幕下半部分的中央位置
        return centerX > screenWidth * 0.3 && centerX < screenWidth * 0.7 &&
               centerY > screenHeight * 0.6
    }

    /**
     * 调试屏幕元素 - 输出所有可点击元素的详细信息
     */
    fun debugScreenElements() {
        try {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "🔍 [调试] 无法获取根窗口节点")
                return
            }
            
            val currentPackage = rootNode.packageName?.toString()
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            Log.i(TAG, "🔍 [调试] 开始分析屏幕元素")
            Log.i(TAG, "🔍 [调试] 当前包名: $currentPackage")
            Log.i(TAG, "🔍 [调试] 屏幕尺寸: ${screenWidth}x${screenHeight}")
            
            val clickableElements = mutableListOf<String>()
            analyzeNode(rootNode, clickableElements, 0)
            
            Log.i(TAG, "🔍 [调试] 找到 ${clickableElements.size} 个可点击元素:")
            clickableElements.forEachIndexed { index, elementInfo ->
                Log.i(TAG, "🔍 [调试] 元素 ${index + 1}: $elementInfo")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "🔍 [调试] 分析屏幕元素失败", e)
        }
    }

    /**
     * 递归分析节点
     */
    private fun analyzeNode(node: AccessibilityNodeInfo, results: MutableList<String>, depth: Int) {
        try {
            if (depth > 10) return // 防止递归过深
            
            if (node.isClickable) {
                val rect = Rect()
                node.getBoundsInScreen(rect)
                
                val elementInfo = buildString {
                    append("类型: ${node.className}")
                    append(", 文本: '${node.text ?: ""}'")
                    append(", 描述: '${node.contentDescription ?: ""}'")
                    append(", 位置: (${rect.left},${rect.top})-(${rect.right},${rect.bottom})")
                    append(", 大小: ${rect.width()}x${rect.height()}")
                    append(", 中心: (${rect.centerX()},${rect.centerY()})")
                    append(", 可见: ${node.isVisibleToUser}")
                    append(", 启用: ${node.isEnabled}")
                }
                
                results.add(elementInfo)
            }
            
            // 递归分析子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    analyzeNode(it, results, depth + 1)
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "分析节点失败", e)
        }
    }

    /**
     * 检查确认按钮位置是否合理
     */
    fun isConfirmButtonPositionReasonable(button: AccessibilityNodeInfo, matchedText: String): Boolean {
        return try {
            val bounds = Rect()
            button.getBoundsInScreen(bounds)
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            val centerX = bounds.centerX()
            val centerY = bounds.centerY()
            
            // 1. 确认按钮通常在屏幕下半部分
            val isInLowerHalf = centerY > screenHeight * 0.4
            
            // 2. 确认按钮通常不在屏幕最顶部（状态栏区域）
            val isNotInStatusBar = centerY > screenHeight * 0.1
            
            // 3. 确认按钮通常不在屏幕最底部（导航栏区域）
            val isNotInNavBar = centerY < screenHeight * 0.95
            
            // 4. 确认按钮通常在合理的区域内
            val isInReasonableArea = centerY > screenHeight * 0.3 && centerY < screenHeight * 0.85
            
            // 5. 确认按钮通常不会在屏幕最左边或最右边
            val isNotEdge = centerX > screenWidth * 0.1 && centerX < screenWidth * 0.9
            
            // 6. 检查元素大小是否合理（太小的可能是图标，太大的可能是背景）
            val width = bounds.width()
            val height = bounds.height()
            val hasReasonableSize = width > 30 && height > 30 && 
                                   width < screenWidth * 0.8 && height < screenHeight * 0.3
            
            // 7. 综合判断
            val isReasonable = isInReasonableArea && isNotEdge && hasReasonableSize
            
            if (!isReasonable) {
                Log.d(TAG, "🚫 确认按钮位置不合理: 位置=($centerX, $centerY), 大小=${width}x${height}, " +
                          "合理区域=$isInReasonableArea, 非边缘=$isNotEdge, 大小合理=$hasReasonableSize, 匹配文本='$matchedText'")
                return false
            }
            
            Log.d(TAG, "✅ 确认按钮位置合理: 位置=($centerX, $centerY), 匹配文本='$matchedText'")
            true
            
        } catch (e: Exception) {
            Log.e(TAG, "检查确认按钮位置失败", e)
            false
        }
    }

    /**
     * 检查是否为有效的确认按钮大小
     */
    fun isValidConfirmButtonSize(rect: Rect, screenWidth: Int, screenHeight: Int): Boolean {
        val buttonWidth = rect.width()
        val buttonHeight = rect.height()
        
        // 按钮不能太小（避免误识别小图标）- 为数字按钮降低门槛
        val minSize = screenWidth * 0.04 // 最小4%屏幕宽度（从8%降低到4%）
        if (buttonWidth < minSize || buttonHeight < minSize * 0.5) {
            Log.d(TAG, "🚫 按钮太小: ${buttonWidth}x${buttonHeight}, 最小要求: ${minSize}x${minSize * 0.5}")
            return false
        }
        
        // 按钮不能太大（避免误识别大容器）
        val maxWidth = screenWidth * 0.4 // 最大40%屏幕宽度
        val maxHeight = screenHeight * 0.15 // 最大15%屏幕高度
        if (buttonWidth > maxWidth || buttonHeight > maxHeight) {
            Log.d(TAG, "🚫 按钮太大: ${buttonWidth}x${buttonHeight}, 最大限制: ${maxWidth}x${maxHeight}")
            return false
        }
        
        return true
    }

    /**
     * 生成详细的调试报告
     */
    fun generateDebugReport(rootNode: AccessibilityNodeInfo) {
        Log.i(TAG, "📋 ===== 调试报告开始 =====")
        
        try {
            // 1. 基本信息
            val packageName = rootNode.packageName?.toString() ?: "unknown"
            val className = rootNode.className?.toString() ?: "unknown"
            Log.i(TAG, "📱 页面信息: 包名=$packageName, 类名=$className")
            
            // 2. 应用节点分析
            val appNames = listOf("Remote Control", "Android Remote Control", "RemoteControl", "远程控制")
            var foundAppNodes = 0
            for (appName in appNames) {
                val appNode = findNodeByText(rootNode, appName)
                if (appNode != null) {
                    foundAppNodes++
                    val rect = Rect()
                    appNode.getBoundsInScreen(rect)
                    Log.i(TAG, "📍 找到应用节点: '$appName' 位置=(${rect.left},${rect.top},${rect.right},${rect.bottom})")
                    
                    // 分析应用节点周围的可点击元素
                    analyzeClickableAroundApp(appNode, rect)
                }
            }
            Log.i(TAG, "📊 应用节点统计: 找到${foundAppNodes}个应用节点")
            
            // 3. ON/OFF文本分析
            analyzeOnOffTexts(rootNode)
            
            // 4. 开关控件分析
            analyzeSwitchControls(rootNode)
            
            // 5. 可点击元素统计
            analyzeClickableElements(rootNode)
            
        } catch (e: Exception) {
            Log.e(TAG, "生成调试报告异常", e)
        }
        
        Log.i(TAG, "📋 ===== 调试报告结束 =====")
    }

    // 私有辅助方法
    private fun analyzeClickableAroundApp(appNode: AccessibilityNodeInfo, appRect: Rect) {
        Log.i(TAG, "🔍 分析应用节点周围的可点击元素:")
        
        val parent = appNode.parent
        if (parent != null) {
            var clickableCount = 0
            var rightSideCount = 0
            
            for (i in 0 until parent.childCount) {
                val sibling = parent.getChild(i)
                if (sibling != null && sibling != appNode) {
                    if (sibling.isClickable) {
                        clickableCount++
                        val siblingRect = Rect()
                        sibling.getBoundsInScreen(siblingRect)
                        
                        if (siblingRect.left >= appRect.right - 100) {
                            rightSideCount++
                            Log.i(TAG, "  ✅ 右侧可点击元素: ${sibling.className} 位置=(${siblingRect.left},${siblingRect.top})")
                        }
                    }
                    sibling.recycle()
                }
            }
            
            Log.i(TAG, "📊 兄弟节点统计: 总可点击=${clickableCount}, 右侧可点击=${rightSideCount}")
            parent.recycle()
        }
    }

    private fun analyzeOnOffTexts(rootNode: AccessibilityNodeInfo) {
        Log.i(TAG, "🔍 分析ON/OFF文本:")
        
        val onNodes = findNodeByText(rootNode, "ON")
        val offNodes = findNodeByText(rootNode, "OFF")
        
        Log.i(TAG, "📊 ON/OFF统计: ON节点=${if (onNodes != null) 1 else 0}, OFF节点=${if (offNodes != null) 1 else 0}")
        
        onNodes?.recycle()
        offNodes?.recycle()
    }

    private fun analyzeSwitchControls(rootNode: AccessibilityNodeInfo) {
        Log.i(TAG, "🔍 分析开关控件:")
        
        val switches = findByViewType(rootNode, "android.widget.Switch")
        Log.i(TAG, "📊 开关控件统计: 找到${switches.size}个Switch控件")
        
        switches.forEach { it.recycle() }
    }

    private fun analyzeClickableElements(rootNode: AccessibilityNodeInfo) {
        Log.i(TAG, "🔍 分析可点击元素:")
        
        val clickableElements = mutableListOf<AccessibilityNodeInfo>()
        findAllClickableNodes(rootNode, clickableElements)
        
        Log.i(TAG, "📊 可点击元素统计: 总共${clickableElements.size}个")
        
        clickableElements.forEach { it.recycle() }
    }

    /**
     * ✅ 方案五：多源设备检测和特征识别
     */
    fun detectDeviceCharacteristics(): Map<String, Any> {
        val characteristics = mutableMapOf<String, Any>()
        
        try {
            Log.i(TAG, "🔍 ScreenManager: 开始设备特征检测")
            
            // 1. 设备基本信息
            characteristics["deviceInfo"] = gatherDeviceInfo()
            
            // 2. 屏幕特征分析
            characteristics["screenFeatures"] = analyzeScreenFeatures()
            
            // 3. 输入法检测
            characteristics["inputMethodInfo"] = detectInputMethodInfo()
            
            // 4. ROM特征检测
            characteristics["romFeatures"] = detectROMFeatures()
            
            // 5. 无障碍能力评估
            characteristics["accessibilityCapabilities"] = assessAccessibilityCapabilities()
            
            // 6. 虚拟键盘检测策略建议
            characteristics["keyboardDetectionStrategy"] = suggestKeyboardDetectionStrategy(characteristics)
            
            Log.i(TAG, "✅ 设备特征检测完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 设备特征检测失败", e)
            characteristics["error"] = e.message ?: "未知错误"
        }
        
        return characteristics.toMap()
    }
    
    /**
     * ✅ 收集设备基本信息
     */
    private fun gatherDeviceInfo(): Map<String, Any> {
        return mapOf(
            "brand" to android.os.Build.BRAND,
            "manufacturer" to android.os.Build.MANUFACTURER,
            "model" to android.os.Build.MODEL,
            "device" to android.os.Build.DEVICE,
            "product" to android.os.Build.PRODUCT,
            "sdkInt" to android.os.Build.VERSION.SDK_INT,
            "release" to android.os.Build.VERSION.RELEASE,
            "incremental" to android.os.Build.VERSION.INCREMENTAL,
            "displayDensity" to context.resources.displayMetrics.density,
            "densityDpi" to context.resources.displayMetrics.densityDpi,
            "screenWidth" to context.resources.displayMetrics.widthPixels,
            "screenHeight" to context.resources.displayMetrics.heightPixels
        )
    }
    
    /**
     * ✅ 分析屏幕特征
     */
    private fun analyzeScreenFeatures(): Map<String, Any> {
        val features = mutableMapOf<String, Any>()
        
        try {
            val displayMetrics = context.resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels
            
            // 计算屏幕比例
            val aspectRatio = screenHeight.toDouble() / screenWidth.toDouble()
            features["aspectRatio"] = aspectRatio
            
            // 判断屏幕类型
            features["screenType"] = when {
                aspectRatio > 2.0 -> "ultra_long" // 超长屏
                aspectRatio > 1.8 -> "long" // 长屏
                aspectRatio > 1.5 -> "standard" // 标准屏
                else -> "wide" // 宽屏
            }
            
            // 计算DPI类型
            val densityDpi = displayMetrics.densityDpi
            features["densityType"] = when {
                densityDpi <= 160 -> "mdpi"
                densityDpi <= 240 -> "hdpi"
                densityDpi <= 320 -> "xhdpi"
                densityDpi <= 480 -> "xxhdpi"
                else -> "xxxhdpi"
            }
            
            // 屏幕尺寸估算（英寸）
            val xdpi = displayMetrics.xdpi
            val ydpi = displayMetrics.ydpi
            if (xdpi > 0 && ydpi > 0) {
                val widthInches = screenWidth / xdpi
                val heightInches = screenHeight / ydpi
                val screenSizeInches = kotlin.math.sqrt(widthInches * widthInches + heightInches * heightInches)
                features["screenSizeInches"] = screenSizeInches
                
                features["sizeCategory"] = when {
                    screenSizeInches < 4.5 -> "small"
                    screenSizeInches < 6.0 -> "normal"
                    screenSizeInches < 7.0 -> "large"
                    else -> "xlarge"
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "分析屏幕特征失败", e)
            features["error"] = e.message ?: "unknown error"
        }
        
        return features
    }
    
    /**
     * ✅ 检测输入法信息
     */
    private fun detectInputMethodInfo(): Map<String, Any> {
        val info = mutableMapOf<String, Any>()
        
        try {
            val imm = context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager
            
            if (imm != null) {
                info["isInputMethodActive"] = imm.isActive
                
                // 获取已启用的输入法列表
                val enabledInputMethods = imm.enabledInputMethodList
                val inputMethodNames = enabledInputMethods.map { method ->
                    mapOf(
                        "packageName" to method.packageName,
                        "serviceName" to method.serviceName,
                        "id" to method.id,
                        "isDefault" to (method.id == android.provider.Settings.Secure.getString(
                            context.contentResolver,
                            android.provider.Settings.Secure.DEFAULT_INPUT_METHOD
                        ))
                    )
                }
                info["enabledInputMethods"] = inputMethodNames
                
                // 获取当前输入法
                val currentInputMethod = android.provider.Settings.Secure.getString(
                    context.contentResolver,
                    android.provider.Settings.Secure.DEFAULT_INPUT_METHOD
                )
                info["currentInputMethod"] = currentInputMethod ?: "unknown"
                
                // 分析输入法类型
                info["inputMethodType"] = analyzeInputMethodType(currentInputMethod)
                
                // 检测是否有第三方输入法
                val hasThirdPartyIME = enabledInputMethods.any { method ->
                    !method.packageName.startsWith("com.android.") &&
                    !method.packageName.startsWith("com.google.")
                }
                info["hasThirdPartyIME"] = hasThirdPartyIME
                
            } else {
                info["error"] = "无法获取InputMethodManager"
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "检测输入法信息失败", e)
            info["error"] = e.message ?: "unknown error"
        }
        
        return info
    }
    
    /**
     * ✅ 分析输入法类型
     */
    private fun analyzeInputMethodType(inputMethodId: String?): String {
        if (inputMethodId == null) return "unknown"
        
        return when {
            inputMethodId.contains("sogou", ignoreCase = true) -> "sogou"
            inputMethodId.contains("baidu", ignoreCase = true) -> "baidu"
            inputMethodId.contains("iflytek", ignoreCase = true) -> "iflytek"
            inputMethodId.contains("google", ignoreCase = true) -> "google"
            inputMethodId.contains("samsung", ignoreCase = true) -> "samsung"
            inputMethodId.contains("huawei", ignoreCase = true) -> "huawei"
            inputMethodId.contains("xiaomi", ignoreCase = true) -> "xiaomi"
            inputMethodId.contains("oppo", ignoreCase = true) -> "oppo"
            inputMethodId.contains("vivo", ignoreCase = true) -> "vivo"
            inputMethodId.contains("android.inputmethod", ignoreCase = true) -> "android_default"
            else -> "other"
        }
    }
    
    /**
     * ✅ 检测ROM特征
     */
    private fun detectROMFeatures(): Map<String, Any> {
        val features = mutableMapOf<String, Any>()
        
        try {
            val brand = android.os.Build.BRAND.lowercase()
            val manufacturer = android.os.Build.MANUFACTURER.lowercase()
            
            // 判断ROM类型
            features["romType"] = when {
                brand.contains("huawei") || manufacturer.contains("huawei") -> "emui"
                brand.contains("honor") || manufacturer.contains("honor") -> "magicos"
                brand.contains("xiaomi") || manufacturer.contains("xiaomi") -> "miui"
                brand.contains("oppo") || manufacturer.contains("oppo") -> "coloros"
                brand.contains("vivo") || manufacturer.contains("vivo") -> "funtouch"
                brand.contains("oneplus") || manufacturer.contains("oneplus") -> "oxygenos"
                brand.contains("samsung") || manufacturer.contains("samsung") -> "oneui"
                brand.contains("google") || manufacturer.contains("google") -> "pixel"
                else -> "aosp"
            }
            
            // 检测特殊ROM特征
            features["hasCustomSecurity"] = checkCustomSecurityFeatures()
            features["hasFloatingWindow"] = checkFloatingWindowSupport()
            features["hasSmartPermission"] = checkSmartPermissionFeatures()
            
            // 获取系统属性
            features["systemProperties"] = getSystemProperties()
            
        } catch (e: Exception) {
            Log.e(TAG, "检测ROM特征失败", e)
            features["error"] = e.message ?: "unknown error"
        }
        
        return features
    }
    
    /**
     * ✅ 检查自定义安全特征
     */
    private fun checkCustomSecurityFeatures(): Boolean {
        return try {
            // 检查是否存在厂商自定义的安全管理器
            val securityPackages = listOf(
                "com.huawei.systemmanager",
                "com.miui.securitycenter",
                "com.coloros.safecenter",
                "com.vivo.permissionmanager",
                "com.samsung.android.lool",
                "com.oneplus.security"
            )
            
            val pm = context.packageManager
            securityPackages.any { packageName ->
                try {
                    pm.getPackageInfo(packageName, 0)
                    true
                } catch (e: Exception) {
                    false
                }
            }
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * ✅ 检查悬浮窗支持
     */
    private fun checkFloatingWindowSupport(): Boolean {
        return try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                android.provider.Settings.canDrawOverlays(context)
            } else {
                true
            }
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * ✅ 检查智能权限特征
     */
    private fun checkSmartPermissionFeatures(): Boolean {
        return try {
            // 检查是否有自动权限管理功能
            val hasAutoPermissionManager = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R
            
            // 检查是否有权限使用历史
            val hasPermissionHistory = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                context.getSystemService(android.app.AppOpsManager::class.java) != null
            } else {
                false
            }
            
            hasAutoPermissionManager || hasPermissionHistory
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * ✅ 获取系统属性
     */
    private fun getSystemProperties(): Map<String, String> {
        return try {
            mapOf(
                "ro.build.version.emui" to getSystemProperty("ro.build.version.emui", ""),
                "ro.miui.ui.version.name" to getSystemProperty("ro.miui.ui.version.name", ""),
                "ro.build.version.opporom" to getSystemProperty("ro.build.version.opporom", ""),
                "ro.vivo.os.version" to getSystemProperty("ro.vivo.os.version", ""),
                "ro.build.version.oneui" to getSystemProperty("ro.build.version.oneui", ""),
                "ro.build.version.colorful" to getSystemProperty("ro.build.version.colorful", "")
            ).filter { it.value.isNotEmpty() }
        } catch (e: Exception) {
            emptyMap()
        }
    }
    
    /**
     * ✅ 获取系统属性
     */
    private fun getSystemProperty(key: String, defaultValue: String): String {
        return try {
            val systemProperties = Class.forName("android.os.SystemProperties")
            val getMethod = systemProperties.getMethod("get", String::class.java, String::class.java)
            getMethod.invoke(null, key, defaultValue) as String
        } catch (e: Exception) {
            defaultValue
        }
    }
    
    /**
     * ✅ 评估无障碍能力
     */
    private fun assessAccessibilityCapabilities(): Map<String, Any> {
        val capabilities = mutableMapOf<String, Any>()
        
        try {
            // 检查无障碍服务是否已启用
            capabilities["isAccessibilityEnabled"] = isAccessibilityServiceEnabled()
            
            // 检查可获取的窗口信息
            capabilities["windowInfoCapabilities"] = assessWindowInfoCapabilities()
            
            // 检查UI层次结构访问能力
            capabilities["uiHierarchyAccess"] = assessUIHierarchyAccess()
            
            // 检查输入模拟能力
            capabilities["inputSimulationCapabilities"] = assessInputSimulationCapabilities()
            
            // 检查屏幕捕获能力
            capabilities["screenCaptureCapabilities"] = assessScreenCaptureCapabilities()
            
        } catch (e: Exception) {
            Log.e(TAG, "评估无障碍能力失败", e)
            capabilities["error"] = e.message ?: "unknown error"
        }
        
        return capabilities
    }
    
    /**
     * ✅ 检查无障碍服务是否启用
     */
    private fun isAccessibilityServiceEnabled(): Boolean {
        return try {
            val accessibilityManager = context.getSystemService(android.content.Context.ACCESSIBILITY_SERVICE) as? android.view.accessibility.AccessibilityManager
            accessibilityManager?.isEnabled == true
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * ✅ 评估窗口信息能力
     */
    private fun assessWindowInfoCapabilities(): Map<String, Any> {
        val capabilities = mutableMapOf<String, Any>()
        
        try {
            capabilities["canAccessWindows"] = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP
            capabilities["canDetectInputMethodWindow"] = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP
            capabilities["supportsMultiWindow"] = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N
            
        } catch (e: Exception) {
            capabilities["error"] = e.message ?: "unknown error"
        }
        
        return capabilities
    }
    
    /**
     * ✅ 评估UI层次结构访问能力
     */
    private fun assessUIHierarchyAccess(): Map<String, Any> {
        val access = mutableMapOf<String, Any>()
        
        try {
            // 尝试获取根节点
            val rootNode = service?.rootInActiveWindow
            access["canAccessRootNode"] = rootNode != null
            
            if (rootNode != null) {
                access["canTraverseHierarchy"] = true
                access["canGetBounds"] = true
                access["canGetText"] = rootNode.text != null || rootNode.contentDescription != null
                access["canGetClassName"] = rootNode.className != null
                access["canGetPackageName"] = rootNode.packageName != null
                
                rootNode.recycle()
            } else {
                access["canTraverseHierarchy"] = false
                access["canGetBounds"] = false
                access["canGetText"] = false
                access["canGetClassName"] = false
                access["canGetPackageName"] = false
            }
            
        } catch (e: Exception) {
            access["error"] = e.message ?: "unknown error"
        }
        
        return access
    }
    
    /**
     * ✅ 评估输入模拟能力
     */
    private fun assessInputSimulationCapabilities(): Map<String, Any> {
        val capabilities = mutableMapOf<String, Any>()
        
        try {
            capabilities["canPerformClick"] = true // 基本能力
            capabilities["canPerformScroll"] = true // 基本能力
            capabilities["canPerformGesture"] = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N
            capabilities["canUseGlobalActions"] = true // 基本能力
            
        } catch (e: Exception) {
            capabilities["error"] = e.message ?: "unknown error"
        }
        
        return capabilities
    }
    
    /**
     * ✅ 评估屏幕捕获能力
     */
    private fun assessScreenCaptureCapabilities(): Map<String, Any> {
        val capabilities = mutableMapOf<String, Any>()
        
        try {
            capabilities["supportsMediaProjection"] = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP
            capabilities["requiresPermission"] = true
            capabilities["hasSecureScreenProtection"] = checkSecureScreenProtection()
            
        } catch (e: Exception) {
            capabilities["error"] = e.message ?: "unknown error"
        }
        
        return capabilities
    }
    
    /**
     * ✅ 检查安全屏幕保护
     */
    private fun checkSecureScreenProtection(): Boolean {
        return try {
            val windowManager = context.getSystemService(android.content.Context.WINDOW_SERVICE) as? android.view.WindowManager
            // 这里可以检查是否有安全屏幕保护，如DRM内容保护等
            false // 默认假设没有
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * ✅ 根据设备特征建议键盘检测策略
     */
    private fun suggestKeyboardDetectionStrategy(characteristics: Map<String, Any>): Map<String, Any> {
        val strategy = mutableMapOf<String, Any>()
        
        try {
            val deviceInfo = characteristics["deviceInfo"] as? Map<*, *>
            val romFeatures = characteristics["romFeatures"] as? Map<*, *>
            val inputMethodInfo = characteristics["inputMethodInfo"] as? Map<*, *>
            val accessibilityCapabilities = characteristics["accessibilityCapabilities"] as? Map<*, *>
            
            // 基于ROM类型的策略建议
            val romType = romFeatures?.get("romType") as? String ?: "aosp"
            strategy["primaryStrategy"] = when (romType) {
                "emui", "magicos" -> "window_detection_first" // 华为系优先使用窗口检测
                "miui" -> "enhanced_hierarchy_scan" // 小米系使用增强层次扫描
                "coloros", "funtouch" -> "multi_method_combined" // OPPO/vivo使用多方法结合
                "oneui" -> "samsung_optimized" // 三星优化策略
                else -> "standard_enhanced" // 标准增强策略
            }
            
            // 基于输入法类型的策略建议
            val inputMethodType = inputMethodInfo?.get("inputMethodType") as? String ?: "unknown"
            strategy["inputMethodStrategy"] = when (inputMethodType) {
                "sogou", "baidu", "iflytek" -> "third_party_ime_optimized"
                "android_default", "google" -> "standard_ime_detection"
                else -> "generic_ime_detection"
            }
            
            // 基于无障碍能力的策略建议
            val canAccessWindows = accessibilityCapabilities?.get("windowInfoCapabilities") as? Map<*, *>
            val windowAccess = canAccessWindows?.get("canAccessWindows") as? Boolean ?: false
            
            strategy["detectionMethods"] = if (windowAccess) {
                listOf("window_api", "hierarchy_scan", "position_inference")
            } else {
                listOf("hierarchy_scan", "position_inference", "resource_id_matching")
            }
            
            // 设备特异性建议
            val brand = deviceInfo?.get("brand") as? String ?: ""
            strategy["deviceSpecificTips"] = when (brand.lowercase()) {
                "huawei", "honor" -> "需要特别注意EMUI的权限限制，建议使用窗口API"
                "xiaomi" -> "MIUI可能有输入法隔离，建议使用多层次扫描"
                "oppo", "vivo" -> "ColorOS/FuntouchOS对第三方输入法友好，建议使用标准检测"
                "samsung" -> "OneUI支持较好，建议使用标准增强策略"
                else -> "使用通用检测策略"
            }
            
            // 优化参数建议
            strategy["recommendedParameters"] = mapOf(
                "maxScanDepth" to when (romType) {
                    "emui", "magicos" -> 25 // 华为系需要更深层扫描
                    "miui" -> 20 // 小米系适中
                    else -> 15 // 标准深度
                },
                "includeInvisibleElements" to when (romType) {
                    "emui", "magicos", "miui" -> true // 定制ROM需要包含不可见元素
                    else -> false
                },
                "usePositionInference" to when (inputMethodType) {
                    "third_party_ime_optimized" -> true
                    else -> false
                },
                "enableWindowDetection" to windowAccess
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "生成键盘检测策略失败", e)
            strategy["error"] = e.message ?: "unknown error"
        }
        
        return strategy
    }
} 