package com.hikoncont.service.modules

import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.graphics.Rect
import android.os.Build
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.manager.GestureController
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.*

/**
 * UI分析管理器
 * 负责UI分析和智能识别
 * 
 * 主要职责:
 * - 确认按钮查找逻辑
 * - UI元素智能分析
 * - 键盘按键检测和过滤
 * - 布局分析和理解
 * - 节点遍历和搜索
 * - 启发式UI识别
 */
class UIAnalysisManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "UIAnalysisManager"
    }
    
    // 依赖项
    private lateinit var gestureController: GestureController
    
    // 协程作用域
    private val analysisScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    // 状态变量
    private var isInitialized = 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分析管理器资源")
            
            analysisScope.cancel()
            isInitialized = false
            
            Log.d(TAG, "✅ UI分析管理器资源清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理UI分析管理器资源失败", e)
        }
    }
    
    /**
     * 智能查找并点击确认按钮 - 主入口
     */
    fun findAndClickConfirmButton(): Boolean {
        return try {
            Log.i(TAG, "🎯 开始智能查找确认按钮")
            
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "❌ 无法获取根节点")
                return false
            }
            
            var success = false
            
            // 策略1: 使用学习到的确认按钮坐标（最高优先级）
            val learnedButton = findLearnedConfirmButton(rootNode)
            if (learnedButton != null) {
                Log.i(TAG, "✅ 策略1成功：使用学习坐标")
                success = clickConfirmButtonWithLog(learnedButton, "学习坐标")
                learnedButton.recycle()
            }
            
            // 策略2: 文本匹配查找确认按钮
            if (!success) {
                val confirmTexts = getConfirmButtonTexts()
                val textButton = findNodeByTexts(rootNode, confirmTexts)
                if (textButton != null) {
                    Log.i(TAG, "✅ 策略2成功：文本匹配")
                    success = clickConfirmButtonWithLog(textButton, "文本匹配")
                    textButton.recycle()
                }
            }
            
            // 策略3: 锁屏界面特殊处理
            if (!success) {
                success = findLockScreenConfirmButton(rootNode)
                if (success) {
                    Log.i(TAG, "✅ 策略3成功：锁屏按钮")
                }
            }
            
            // 策略4: 软键盘确认按钮
            if (!success) {
                val keyboardButton = findSoftKeyboardConfirmButton(rootNode)
                if (keyboardButton != null) {
                    Log.i(TAG, "✅ 策略4成功：软键盘按钮")
                    success = clickConfirmButtonWithLog(keyboardButton, "软键盘按钮")
                    keyboardButton.recycle()
                }
            }
            
            // 策略5: 启发式按钮识别
            if (!success) {
                val heuristicButton = findButtonByHeuristics(rootNode)
                if (heuristicButton != null) {
                    Log.i(TAG, "✅ 策略5成功：启发式识别")
                    success = clickConfirmButtonWithLog(heuristicButton, "启发式识别")
                    heuristicButton.recycle()
                }
            }
            
            rootNode.recycle()
            
            if (success) {
                Log.i(TAG, "🎉 确认按钮查找成功")
            } else {
                Log.w(TAG, "⚠️ 所有策略都失败，未找到确认按钮")
            }
            
            success
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找确认按钮失败", e)
            false
        }
    }
    
    /**
     * 获取确认按钮文本列表
     */
    private fun getConfirmButtonTexts(): List<String> {
        return listOf(
            // 中文确认文本
            "确认", "确定", "完成", "提交", "登录", "解锁", "继续", "下一步",
            "发送", "开始", "进入", "同意", "允许", "授权", "确认解锁",
            
            // 英文确认文本
            "Done", "Go", "Enter", "OK", "Submit", "Login", "Unlock", "Continue", "Next",
            "Send", "Start", "Begin", "Agree", "Allow", "Grant", "Confirm",
            
            // 符号和图标
            "→", "✓", "√", "⏎", "↵", "➤", "▶",
            
            // 可能的键盘确认键
            "return", "enter", "send", "search", "go", "done"
        )
    }
    
    /**
     * 查找学习到的确认按钮
     */
    private fun findLearnedConfirmButton(rootNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            // TODO: 实现学习坐标查找逻辑
            // 这里可以调用LearningManager的相关方法
            Log.d(TAG, "🧠 查找学习到的确认按钮坐标")
            null
        } catch (e: Exception) {
            Log.e(TAG, "查找学习按钮失败", e)
            null
        }
    }
    
    /**
     * 通过文本列表查找节点
     */
    private fun findNodeByTexts(rootNode: AccessibilityNodeInfo, texts: List<String>): AccessibilityNodeInfo? {
        for (text in texts) {
            val node = findNodeByText(rootNode, text)
            if (node != null && isValidConfirmButton(node)) {
                Log.d(TAG, "🎯 找到文本匹配的确认按钮: '$text'")
                return node
            }
            node?.recycle()
        }
        return null
    }
    
    /**
     * 通过单个文本查找节点
     */
    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.equals(targetText, ignoreCase = true) || 
                     desc.contains(targetText, ignoreCase = true)) && 
                    node.isClickable) {
                    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 isValidConfirmButton(button: AccessibilityNodeInfo): Boolean {
        return try {
            // 必须可点击
            if (!button.isClickable) {
                return false
            }
            
            // 排除键盘按键
            val buttonText = button.text?.toString()?.trim() ?: ""
            if (isKeyboardKey(buttonText, button.contentDescription?.toString() ?: "")) {
                Log.d(TAG, "🚫 排除键盘按键: '$buttonText'")
                return false
            }
            
            // 获取按钮位置和尺寸
            val rect = Rect()
            button.getBoundsInScreen(rect)
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            // 位置检查：确认按钮通常在屏幕下半部分
            if (rect.centerY() < screenHeight * 0.3) {
                Log.d(TAG, "🚫 位置过高，不太可能是确认按钮: Y=${rect.centerY()}")
                return false
            }
            
            // 尺寸检查：按钮应该有合理的大小
            val buttonWidth = rect.width()
            val buttonHeight = rect.height()
            if (buttonWidth < 30 || buttonHeight < 20) {
                Log.d(TAG, "🚫 按钮太小: ${buttonWidth}x${buttonHeight}")
                return false
            }
            
            if (buttonWidth > screenWidth * 0.8 || buttonHeight > screenHeight * 0.3) {
                Log.d(TAG, "🚫 按钮太大: ${buttonWidth}x${buttonHeight}")
                return false
            }
            
            Log.d(TAG, "✅ 有效确认按钮: 文本='$buttonText', 位置=(${rect.centerX()},${rect.centerY()}), 大小=${buttonWidth}x${buttonHeight}")
            return true
            
        } catch (e: Exception) {
            Log.e(TAG, "验证确认按钮失败", e)
            false
        }
    }
    
    /**
     * 检查是否为键盘按键
     */
    fun isKeyboardKey(text: String, description: String): Boolean {
        val normalizedText = text.lowercase().trim()
        val normalizedDesc = description.lowercase().trim()
        
        // 单个字符检查
        if (normalizedText.length == 1) {
            val char = normalizedText[0]
            // 字母、数字、基本符号
            if (char.isLetterOrDigit() || char in ",.?!@#$%^&*()_+-=[]{}|;':\"<>/~`") {
                return true
            }
        }
        
        // 键盘按键关键词
        val keyboardKeywords = setOf(
            "key", "键", "keyboard", "按键", "input", "输入",
            "space", "spacebar", "空格", "backspace", "删除",
            "shift", "ctrl", "alt", "tab", "caps", "num"
        )
        
        return keyboardKeywords.any { keyword ->
            normalizedText.contains(keyword) || normalizedDesc.contains(keyword)
        }
    }
    
    /**
     * 查找锁屏界面的确认按钮
     */
    private fun findLockScreenConfirmButton(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "🔒 查找锁屏确认按钮")
            
            // 尝试数字键盘确认按钮
            if (findNumericKeypadConfirmButton(rootNode)) {
                return true
            }
            
            // 尝试文本键盘确认按钮
            if (findTextKeyboardConfirmButton(rootNode)) {
                return true
            }
            
            // 尝试通用锁屏确认按钮
            findGenericLockScreenConfirmButton(rootNode)
            
        } catch (e: Exception) {
            Log.e(TAG, "查找锁屏确认按钮失败", e)
            false
        }
    }
    
    /**
     * 查找数字键盘确认按钮
     */
    private fun findNumericKeypadConfirmButton(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "🔢 查找数字键盘确认按钮")
            
            val (screenWidth, screenHeight) = getRealScreenSize()
            val confirmTexts = arrayOf(
                "确认", "确定", "完成", "ok", "done", "enter", "submit", "continue", "✓", "→"
            )
            
            fun searchConfirmButton(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
                try {
                    if (node.isClickable) {
                        val text = node.text?.toString()?.trim() ?: ""
                        val desc = node.contentDescription?.toString()?.trim() ?: ""
                        
                        // 排除键盘按键
                        if (isKeyboardKey(text, desc)) {
                            return null
                        }
                        
                        // 检查文本匹配
                        for (confirmText in confirmTexts) {
                            if (text.equals(confirmText, ignoreCase = true) || 
                                desc.contains(confirmText, ignoreCase = true)) {
                                
                                val rect = Rect()
                                node.getBoundsInScreen(rect)
                                
                                // 位置和大小验证
                                if (isValidConfirmButtonPosition(rect, screenWidth, screenHeight) &&
                                    isValidConfirmButtonSize(rect, screenWidth, screenHeight)) {
                                    Log.d(TAG, "🎯 找到数字键盘确认按钮: '$text'/'$desc'")
                                    return node
                                }
                            }
                        }
                    }
                    
                    // 递归搜索子节点
                    for (i in 0 until node.childCount) {
                        val child = node.getChild(i)
                        child?.let {
                            val result = searchConfirmButton(it)
                            if (result != null) return result
                            it.recycle()
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "搜索数字键盘确认按钮失败", e)
                }
                return null
            }
            
            val confirmButton = searchConfirmButton(rootNode)
            if (confirmButton != null) {
                val success = clickConfirmButtonWithLog(confirmButton, "数字键盘确认")
                confirmButton.recycle()
                return success
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "查找数字键盘确认按钮失败", e)
            false
        }
    }
    
    /**
     * 查找文本键盘确认按钮
     */
    private fun findTextKeyboardConfirmButton(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "📝 查找文本键盘确认按钮")
            
            val confirmTexts = arrayOf(
                "确认", "确定", "完成", "提交", "继续", "done", "go", "enter", "submit", "continue", "→", "✓"
            )
            
            fun searchTextConfirmButton(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
                try {
                    if (node.isClickable) {
                        val text = node.text?.toString()?.trim() ?: ""
                        val desc = node.contentDescription?.toString()?.trim() ?: ""
                        
                        if (isKeyboardKey(text, desc)) {
                            return null
                        }
                        
                        for (confirmText in confirmTexts) {
                            if (text.equals(confirmText, ignoreCase = true) || 
                                desc.contains(confirmText, ignoreCase = true)) {
                                
                                val rect = Rect()
                                node.getBoundsInScreen(rect)
                                val (screenWidth, screenHeight) = getRealScreenSize()
                                
                                if (isValidConfirmButtonPosition(rect, screenWidth, screenHeight) &&
                                    isValidConfirmButtonSize(rect, screenWidth, screenHeight)) {
                                    Log.d(TAG, "🎯 找到文本键盘确认按钮: '$text'/'$desc'")
                                    return node
                                }
                            }
                        }
                    }
                    
                    for (i in 0 until node.childCount) {
                        val child = node.getChild(i)
                        child?.let {
                            val result = searchTextConfirmButton(it)
                            if (result != null) return result
                            it.recycle()
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "搜索文本键盘确认按钮失败", e)
                }
                return null
            }
            
            val confirmButton = searchTextConfirmButton(rootNode)
            if (confirmButton != null) {
                val success = clickConfirmButtonWithLog(confirmButton, "文本键盘确认")
                confirmButton.recycle()
                return success
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "查找文本键盘确认按钮失败", e)
            false
        }
    }
    
    /**
     * 查找通用锁屏确认按钮
     */
    private fun findGenericLockScreenConfirmButton(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "🔍 查找通用锁屏确认按钮")
            
            // 使用通用的确认按钮查找逻辑
            val button = findButtonByHeuristics(rootNode)
            if (button != null) {
                val success = clickConfirmButtonWithLog(button, "通用锁屏确认")
                button.recycle()
                return success
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "查找通用锁屏确认按钮失败", e)
            false
        }
    }
    
    /**
     * 查找软键盘确认按钮
     */
    private fun findSoftKeyboardConfirmButton(rootNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            Log.d(TAG, "⌨️ 查找软键盘确认按钮")
            
            val candidates = mutableListOf<AccessibilityNodeInfo>()
            findAllClickableNodes(rootNode, candidates)
            
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            // 查找密码输入框位置
            val passwordFieldY = findPasswordFieldPosition(rootNode)
            val keyboardAreaThreshold = if (passwordFieldY > 0) {
                passwordFieldY + 200 // 密码框下方200px开始是键盘区域
            } else {
                screenHeight * 0.6f // 默认屏幕60%作为键盘区域
            }
            
            Log.d(TAG, "密码框位置: $passwordFieldY, 键盘区域阈值: $keyboardAreaThreshold")
            
            // 过滤软键盘确认按钮候选
            val softKeyboardCandidates = candidates.filter { node ->
                val rect = Rect()
                node.getBoundsInScreen(rect)
                val nodeText = node.text?.toString() ?: ""
                val nodeDesc = node.contentDescription?.toString() ?: ""
                
                val isInKeyboardArea = rect.centerY() > keyboardAreaThreshold
                val hasReasonableSize = rect.width() > 50 && rect.height() > 30 && 
                                       rect.width() < screenWidth / 3
                val isSoftKeyboardButton = !isKeyboardKey(nodeText, nodeDesc)
                val isInRightArea = rect.centerX() > screenWidth * 0.7
                val isInBottomArea = rect.centerY() > screenHeight * 0.85
                
                // 排除明显不是确认按钮的文本
                val excludeTexts = arrayOf("Emergency", "紧急", "取消", "Cancel", "返回", "Back")
                val isNotExcluded = excludeTexts.none { excludeText ->
                    nodeText.contains(excludeText, ignoreCase = true) || 
                    nodeDesc.contains(excludeText, ignoreCase = true)
                }
                
                val hasConfirmIndicator = nodeText.contains("确认", ignoreCase = true) ||
                                         nodeText.contains("OK", ignoreCase = true) ||
                                         nodeText.contains("Done", ignoreCase = true) ||
                                         nodeDesc.contains("confirm", ignoreCase = true)
                
                isInKeyboardArea && hasReasonableSize && isSoftKeyboardButton && 
                isNotExcluded && (isInRightArea || isInBottomArea || hasConfirmIndicator)
            }
            
            Log.d(TAG, "找到 ${softKeyboardCandidates.size} 个软键盘确认按钮候选")
            
            if (softKeyboardCandidates.isEmpty()) {
                candidates.forEach { it.recycle() }
                return null
            }
            
            // 优先级选择策略
            var bestCandidate: AccessibilityNodeInfo? = null
            
            // 1. 优先选择有明确确认文本的按钮
            val confirmKeywords = arrayOf(
                "确认", "确定", "完成", "提交", "继续", "ok", "done", "enter", "go", "send", "submit", "continue"
            )
            bestCandidate = softKeyboardCandidates.find { node ->
                val nodeText = node.text?.toString() ?: ""
                val nodeDesc = node.contentDescription?.toString() ?: ""
                confirmKeywords.any { keyword ->
                    nodeText.contains(keyword, ignoreCase = true) || 
                    nodeDesc.contains(keyword, ignoreCase = true)
                }
            }
            
            if (bestCandidate != null) {
                Log.d(TAG, "✅ 找到有确认文本的软键盘按钮")
                // 回收其他候选节点
                candidates.filter { it != bestCandidate }.forEach { it.recycle() }
                return bestCandidate
            }
            
            // 2. 选择最右下角的按钮
            bestCandidate = softKeyboardCandidates.maxByOrNull { node ->
                val rect = Rect()
                node.getBoundsInScreen(rect)
                rect.centerX() + rect.centerY()
            }
            
            if (bestCandidate != null) {
                Log.d(TAG, "✅ 选择最右下角的软键盘按钮")
            }
            
            // 回收其他候选节点
            candidates.filter { it != bestCandidate }.forEach { it.recycle() }
            return bestCandidate
            
        } catch (e: Exception) {
            Log.e(TAG, "查找软键盘确认按钮失败", e)
            null
        }
    }
    
    /**
     * 查找所有可点击节点
     */
    private fun findAllClickableNodes(rootNode: AccessibilityNodeInfo, candidates: MutableList<AccessibilityNodeInfo>) {
        try {
            fun collectClickableNodes(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 15) return
                
                if (node.isClickable) {
                    candidates.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)
        }
    }
    
    /**
     * 查找密码输入框位置
     */
    private fun findPasswordFieldPosition(rootNode: AccessibilityNodeInfo): Float {
        return try {
            var passwordFieldY = 0f
            
            fun findPasswordField(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || passwordFieldY > 0) return
                
                val className = node.className?.toString()?.lowercase() ?: ""
                val isEditText = className.contains("edittext")
                val isPassword = node.isPassword
                
                if (isEditText || isPassword) {
                    val rect = Rect()
                    node.getBoundsInScreen(rect)
                    passwordFieldY = rect.centerY().toFloat()
                    Log.d(TAG, "找到密码输入框位置: Y=$passwordFieldY")
                    return
                }
                
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let {
                        findPasswordField(it, depth + 1)
                        it.recycle()
                    }
                }
            }
            
            findPasswordField(rootNode)
            passwordFieldY
            
        } catch (e: Exception) {
            Log.e(TAG, "查找密码输入框位置失败", e)
            0f
        }
    }
    
    /**
     * 启发式按钮识别
     */
    private fun findButtonByHeuristics(rootNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            Log.d(TAG, "🧠 启发式按钮识别")
            
            val candidates = mutableListOf<AccessibilityNodeInfo>()
            findAllClickableNodes(rootNode, candidates)
            
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            // 评分机制选择最佳候选
            var bestCandidate: AccessibilityNodeInfo? = null
            var bestScore = 0
            
            for (node in candidates) {
                val score = calculateConfirmButtonScore(node, screenWidth, screenHeight)
                if (score > bestScore && score > 30) { // 最低阈值
                    bestCandidate?.recycle()
                    bestCandidate = node
                    bestScore = score
                } else {
                    node.recycle()
                }
            }
            
            if (bestCandidate != null) {
                Log.d(TAG, "✅ 启发式识别找到最佳候选，得分: $bestScore")
            }
            
            bestCandidate
            
        } catch (e: Exception) {
            Log.e(TAG, "启发式按钮识别失败", e)
            null
        }
    }
    
    /**
     * 计算确认按钮得分
     */
    private fun calculateConfirmButtonScore(node: AccessibilityNodeInfo, screenWidth: Int, screenHeight: Int): Int {
        var score = 0
        
        try {
            val text = node.text?.toString()?.lowercase() ?: ""
            val desc = node.contentDescription?.toString()?.lowercase() ?: ""
            val className = node.className?.toString()?.lowercase() ?: ""
            
            val rect = Rect()
            node.getBoundsInScreen(rect)
            
            // 1. 文本匹配得分 (40分)
            val confirmKeywords = listOf(
                "确认", "确定", "完成", "提交", "继续", "下一步", "ok", "done", "enter", "go", "submit", "continue", "next"
            )
            if (confirmKeywords.any { keyword -> text.contains(keyword) || desc.contains(keyword) }) {
                score += 40
            }
            
            // 2. 位置得分 (25分)
            val centerY = rect.centerY()
            when {
                centerY > screenHeight * 0.7 -> score += 25 // 下半部分
                centerY > screenHeight * 0.5 -> score += 15 // 中下部分
                centerY > screenHeight * 0.3 -> score += 5  // 中部
            }
            
            // 3. 控件类型得分 (20分)
            when {
                className.contains("button") -> score += 20
                className.contains("imageview") -> score += 15
                className.contains("textview") -> score += 10
            }
            
            // 4. 尺寸合理性得分 (10分)
            val width = rect.width()
            val height = rect.height()
            if (width > 50 && height > 30 && width < screenWidth * 0.6 && height < screenHeight * 0.2) {
                score += 10
            }
            
            // 5. 位置偏好得分 (5分)
            val centerX = rect.centerX()
            if (centerX > screenWidth * 0.6) { // 偏右位置
                score += 5
            }
            
            // 减分项
            if (isKeyboardKey(text, desc)) {
                score -= 50 // 严重减分
            }
            
            val excludeKeywords = listOf("emergency", "紧急", "cancel", "取消", "back", "返回")
            if (excludeKeywords.any { keyword -> text.contains(keyword) || desc.contains(keyword) }) {
                score -= 30
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "计算按钮得分失败", e)
            return 0
        }
        
        return maxOf(0, score)
    }
    
    /**
     * 验证确认按钮位置是否合理
     */
    private fun isValidConfirmButtonPosition(rect: Rect, screenWidth: Int, screenHeight: Int): Boolean {
        return rect.centerY() > screenHeight * 0.3 && 
               rect.centerY() < screenHeight * 0.95 &&
               rect.centerX() > screenWidth * 0.05 &&
               rect.centerX() < screenWidth * 0.95
    }
    
    /**
     * 验证确认按钮尺寸是否合理
     */
    private fun isValidConfirmButtonSize(rect: Rect, screenWidth: Int, screenHeight: Int): Boolean {
        val width = rect.width()
        val height = rect.height()
        return width > 30 && height > 20 && 
               width < screenWidth * 0.8 && height < screenHeight * 0.3
    }
    
    /**
     * 点击确认按钮并记录日志
     */
    private fun clickConfirmButtonWithLog(button: AccessibilityNodeInfo, method: String): Boolean {
        return try {
            val rect = Rect()
            button.getBoundsInScreen(rect)
            val centerX = rect.centerX().toFloat()
            val centerY = rect.centerY().toFloat()
            
            Log.d(TAG, "🎯 点击确认按钮: 方法=$method, 位置=($centerX, $centerY)")
            
            if (::gestureController.isInitialized) {
                gestureController.performClick(centerX, centerY)
                
                // 记录操作日志
                recordOperationLog("CLICK", "确认按钮", mapOf(
                    "x" to centerX,
                    "y" to centerY,
                    "text" to (button.text?.toString() ?: ""),
                    "method" to method
                ))
                
                return true
            } else {
                Log.w(TAG, "⚠️ GestureController未初始化")
                return false
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "点击确认按钮失败", e)
            false
        }
    }
    
    /**
     * 记录操作日志
     */
    private fun recordOperationLog(action: String, target: String, data: Map<String, Any>) {
        try {
            // TODO: 调用LoggingManager记录日志
            Log.d(TAG, "📝 操作日志: 动作=$action, 目标=$target, 数据=$data")
        } catch (e: Exception) {
            Log.e(TAG, "记录操作日志失败", e)
        }
    }
    
    /**
     * 获取真实屏幕尺寸
     */
    private fun getRealScreenSize(): Pair<Int, Int> {
        return try {
            val metrics = context.resources.displayMetrics
            Pair(metrics.widthPixels, metrics.heightPixels)
        } catch (e: Exception) {
            Log.e(TAG, "获取屏幕尺寸失败", e)
            Pair(1080, 1920) // 默认值
        }
    }
    
    /**
     * 调试当前屏幕元素
     */
    fun debugCurrentScreenElements() {
        analysisScope.launch {
            try {
                Log.i(TAG, "🔍 开始调试当前屏幕元素")
                
                val rootNode = service.rootInActiveWindow
                if (rootNode == null) {
                    Log.w(TAG, "❌ 无法获取根节点进行调试")
                    return@launch
                }
                
                val allClickable = mutableListOf<ClickableElementInfo>()
                val confirmCandidates = mutableListOf<ClickableElementInfo>()
                val keyboardKeys = mutableListOf<ClickableElementInfo>()
                
                analyzeNodeForDebug(rootNode, allClickable, confirmCandidates, keyboardKeys)
                
                Log.i(TAG, "📊 调试统计:")
                Log.i(TAG, "  总可点击元素: ${allClickable.size}")
                Log.i(TAG, "  确认按钮候选: ${confirmCandidates.size}")
                Log.i(TAG, "  键盘按键: ${keyboardKeys.size}")
                
                // 详细输出确认按钮候选
                Log.i(TAG, "🎯 确认按钮候选详情:")
                confirmCandidates.forEachIndexed { index, element ->
                    Log.i(TAG, "  候选${index + 1}: $element")
                }
                
                rootNode.recycle()
                
            } catch (e: Exception) {
                Log.e(TAG, "调试屏幕元素失败", e)
            }
        }
    }
    
    /**
     * 分析节点用于调试
     */
    private fun analyzeNodeForDebug(
        node: AccessibilityNodeInfo,
        allClickable: MutableList<ClickableElementInfo>,
        confirmCandidates: MutableList<ClickableElementInfo>,
        keyboardKeys: MutableList<ClickableElementInfo>,
        depth: Int = 0
    ) {
        if (depth > 15) return
        
        try {
            if (node.isClickable) {
                val text = node.text?.toString()?.trim() ?: ""
                val desc = node.contentDescription?.toString()?.trim() ?: ""
                val className = node.className?.toString() ?: ""
                
                val rect = Rect()
                node.getBoundsInScreen(rect)
                
                val elementInfo = ClickableElementInfo(
                    text = text,
                    description = desc,
                    className = className,
                    centerX = rect.centerX(),
                    centerY = rect.centerY(),
                    width = rect.width(),
                    height = rect.height()
                )
                
                allClickable.add(elementInfo)
                
                // 分类元素
                if (isKeyboardKey(text, desc)) {
                    keyboardKeys.add(elementInfo)
                } else {
                    // 判断是否为确认按钮候选
                    val confirmTexts = getConfirmButtonTexts()
                    val isConfirmCandidate = confirmTexts.any { confirmText ->
                        text.contains(confirmText, ignoreCase = true) || 
                        desc.contains(confirmText, ignoreCase = true)
                    }
                    
                    val isLikelyConfirmButton = isLikelyConfirmButtonByPosition(elementInfo)
                    
                    if (isConfirmCandidate || isLikelyConfirmButton) {
                        confirmCandidates.add(elementInfo)
                    }
                }
            }
            
            // 递归处理子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    analyzeNodeForDebug(it, allClickable, confirmCandidates, keyboardKeys, depth + 1)
                    it.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "分析节点失败", e)
        }
    }
    
    /**
     * 通过位置和大小启发式判断是否可能是确认按钮
     */
    private fun isLikelyConfirmButtonByPosition(element: ClickableElementInfo): Boolean {
        val (screenWidth, screenHeight) = getRealScreenSize()
        
        // 排除明确不是确认按钮的文本
        val excludeTexts = arrayOf("Emergency", "紧急", "取消", "Cancel", "返回", "Back", "关闭", "Close")
        if (excludeTexts.any { excludeText ->
            element.text.contains(excludeText, ignoreCase = true) || 
            element.description.contains(excludeText, ignoreCase = true)
        }) {
            return false
        }
        
        // 1. 必须在屏幕下半部分
        if (element.centerY <= screenHeight * 0.6) {
            return false
        }
        
        // 2. 不能是单个字符（避免键盘按键）
        if (element.text.length == 1) {
            return false
        }
        
        // 3. 大小合理
                    val minSize = screenWidth * 0.04 // 最小4%屏幕宽度（降低门槛以捕获数字按钮）
        val maxWidth = screenWidth * 0.6 // 最大60%屏幕宽度
        val maxHeight = screenHeight * 0.2 // 最大20%屏幕高度
        
        if (element.width < minSize || element.height < minSize * 0.5) {
            return false
        }
        
        if (element.width > maxWidth || element.height > maxHeight) {
            return false
        }
        
        // 4. 类名判断：Button类型更可能是确认按钮
        val isButtonType = element.className.lowercase().let { className ->
            className.contains("button") || 
            className.contains("imageview") ||
            className.contains("textview")
        }
        
        return isButtonType
    }
    
    /**
     * 可点击元素信息数据类
     */
    data class ClickableElementInfo(
        val text: String,
        val description: String,
        val className: String,
        val centerX: Int,
        val centerY: Int,
        val width: Int,
        val height: Int
    ) {
        override fun toString(): String {
            return "文本='$text', 描述='$description', 类名='$className', 位置=($centerX,$centerY), 大小=${width}x${height}"
        }
    }
    
    /**
     * 获取UI分析管理器状态
     */
    fun isInitialized(): Boolean = isInitialized
    
    /**
     * 分析UI布局
     */
    fun analyzeUILayout(): Map<String, Any> {
        return try {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                return mapOf("error" to "无法获取根节点")
            }
            
            val result = mutableMapOf<String, Any>()
            
            // 统计可点击元素
            val clickableElements = mutableListOf<AccessibilityNodeInfo>()
            findAllClickableNodes(rootNode, clickableElements)
            result["clickableCount"] = clickableElements.size
            
            // 统计输入框
            var editTextCount = 0
            fun countEditTexts(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10) return
                
                if (node.className?.toString()?.contains("EditText") == true) {
                    editTextCount++
                }
                
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let {
                        countEditTexts(it, depth + 1)
                        it.recycle()
                    }
                }
            }
            countEditTexts(rootNode)
            result["editTextCount"] = editTextCount
            
            // 获取页面信息
            result["packageName"] = rootNode.packageName?.toString() ?: ""
            result["className"] = rootNode.className?.toString() ?: ""
            
            clickableElements.forEach { it.recycle() }
            rootNode.recycle()
            
            result.toMap()
            
        } catch (e: Exception) {
            Log.e(TAG, "分析UI布局失败", e)
            mapOf("error" to (e.message ?: "未知错误"))
        }
    }
    
    /**
     * ✅ 方案一：增强UI层次结构分析 - 专门针对键盘检测优化
     */
    fun analyzeUIHierarchyEnhanced(includeInvisible: Boolean = false, includeNonInteractive: Boolean = true, maxDepth: Int = 15): org.json.JSONObject? {
        return try {
            Log.i(TAG, "🔍 UIAnalysisManager: 开始增强UI分析（键盘检测优化）")
            
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "❌ 无法获取根节点进行增强UI分析")
                return null
            }
            
            val hierarchy = org.json.JSONObject()
            
            // 1. 基础UI层次结构
            hierarchy.put("root", convertNodeToJSONEnhanced(rootNode, includeInvisible, includeNonInteractive, maxDepth, 0))
            hierarchy.put("timestamp", System.currentTimeMillis())
            hierarchy.put("screenWidth", context.resources.displayMetrics.widthPixels)
            hierarchy.put("screenHeight", context.resources.displayMetrics.heightPixels)
            hierarchy.put("packageName", rootNode.packageName?.toString() ?: "unknown")
            
            // 2. 键盘专项检测
            val keyboardDetection = detectKeyboardElementsSpecially(rootNode)
            hierarchy.put("keyboardElements", keyboardDetection)
            
            // 3. 数字按钮专项扫描
            val digitButtons = detectDigitButtonsComprehensively(rootNode)
            hierarchy.put("digitButtons", digitButtons)
            
            // 4. 输入法窗口检测
            val inputMethodWindows = detectInputMethodWindows()
            hierarchy.put("inputMethodWindows", inputMethodWindows)
            
            // 5. 计算键盘检测置信度
            val confidence = calculateKeyboardConfidence(keyboardDetection, digitButtons, inputMethodWindows)
            hierarchy.put("keyboardConfidence", confidence)
            
            // 6. 添加增强标识
            hierarchy.put("enhanced", true)
            hierarchy.put("version", "UIAnalysisManager_v1.0")
            
            rootNode.recycle()
            
            Log.i(TAG, "✅ 增强UI分析完成，键盘置信度: $confidence")
            hierarchy
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 增强UI分析失败", e)
            null
        }
    }
    
    /**
     * ✅ 增强版节点转JSON - 对键盘元素更敏感
     */
    private fun convertNodeToJSONEnhanced(
        node: AccessibilityNodeInfo,
        includeInvisible: Boolean,
        includeNonInteractive: Boolean,
        maxDepth: Int,
        currentDepth: Int
    ): org.json.JSONObject {
        val jsonNode = org.json.JSONObject()
        
        try {
            val rect = android.graphics.Rect()
            node.getBoundsInScreen(rect)
            
            val text = node.text?.toString() ?: ""
            val desc = node.contentDescription?.toString() ?: ""
            val className = node.className?.toString() ?: ""
            val packageName = node.packageName?.toString() ?: ""
            
            // 基本信息
            jsonNode.put("id", "${node.hashCode()}_$currentDepth")
            jsonNode.put("type", className)
            jsonNode.put("text", text)
            jsonNode.put("description", desc)
            jsonNode.put("packageName", packageName)
            
            // 位置信息
            jsonNode.put("bounds", org.json.JSONObject().apply {
                put("left", rect.left)
                put("top", rect.top)
                put("right", rect.right)
                put("bottom", rect.bottom)
                put("width", rect.width())
                put("height", rect.height())
                put("centerX", rect.centerX())
                put("centerY", rect.centerY())
            })
            
            // 属性信息
            jsonNode.put("clickable", node.isClickable)
            jsonNode.put("scrollable", node.isScrollable)
            jsonNode.put("focusable", node.isFocusable)
            jsonNode.put("enabled", node.isEnabled)
            jsonNode.put("visible", node.isVisibleToUser)
            jsonNode.put("editable", node.isEditable)
            jsonNode.put("checkable", node.isCheckable)
            
            // ✅ 键盘相关增强检测
            jsonNode.put("isKeyboardElement", isKeyboardRelatedElement(node, text, desc, className, packageName))
            jsonNode.put("isDigitButton", isDigitButton(text, desc))
            jsonNode.put("keyboardType", determineKeyboardType(node, text, desc, className))
            jsonNode.put("confidence", calculateElementConfidence(node, text, desc, className))
            
            // 子节点处理 - 对键盘元素使用更宽松的条件
            val children = org.json.JSONArray()
            if (currentDepth < maxDepth) {
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        try {
                            val childText = child.text?.toString() ?: ""
                            val childDesc = child.contentDescription?.toString() ?: ""
                            val childClass = child.className?.toString() ?: ""
                            
                            // ✅ 更宽松的包含条件，特别针对键盘元素
                            val shouldInclude = shouldIncludeChildEnhanced(
                                child, childText, childDesc, childClass, 
                                includeInvisible, includeNonInteractive
                            )
                            
                            if (shouldInclude) {
                                children.put(convertNodeToJSONEnhanced(child, includeInvisible, includeNonInteractive, maxDepth, currentDepth + 1))
                            }
                        } catch (e: Exception) {
                            Log.w(TAG, "处理子节点失败: ${e.message}")
                        } finally {
                            child.recycle()
                        }
                    }
                }
            }
            jsonNode.put("children", children)
            
        } catch (e: Exception) {
            Log.e(TAG, "转换节点到JSON失败", e)
        }
        
        return jsonNode
    }
    
    /**
     * ✅ 更宽松的子节点包含条件 - 键盘优化
     */
    private fun shouldIncludeChildEnhanced(
        child: AccessibilityNodeInfo,
        text: String,
        desc: String,
        className: String,
        includeInvisible: Boolean,
        includeNonInteractive: Boolean
    ): Boolean {
        // 数字按钮和键盘元素无条件包含
        if (isDigitButton(text, desc) || isKeyboardRelatedElement(child, text, desc, className, "")) {
            return true
        }
        
        // 可能的键盘相关类名也包含
        if (className.lowercase().let { cls ->
            cls.contains("key") || cls.contains("button") || cls.contains("input") ||
            cls.contains("keyboard") || cls.contains("ime") || cls.contains("edit")
        }) {
            return true
        }
        
        // 原有的标准条件
        if (!includeInvisible && !child.isVisibleToUser) return false
        if (!includeNonInteractive && !child.isClickable && !child.isScrollable && !child.isFocusable) return false
        
        return true
    }
    
    /**
     * ✅ 键盘元素专项检测
     */
    private fun detectKeyboardElementsSpecially(rootNode: AccessibilityNodeInfo): org.json.JSONArray {
        val keyboardElements = org.json.JSONArray()
        
        try {
            scanForKeyboardElements(rootNode, keyboardElements, 0, 20) // 增加扫描深度
            Log.i(TAG, "🎹 专项检测到 ${keyboardElements.length()} 个键盘元素")
        } catch (e: Exception) {
            Log.e(TAG, "键盘元素专项检测失败", e)
        }
        
        return keyboardElements
    }
    
    /**
     * ✅ 递归扫描键盘元素
     */
    private fun scanForKeyboardElements(
        node: AccessibilityNodeInfo, 
        results: org.json.JSONArray, 
        depth: Int, 
        maxDepth: Int
    ) {
        if (depth > maxDepth) return
        
        try {
            val text = node.text?.toString() ?: ""
            val desc = node.contentDescription?.toString() ?: ""
            val className = node.className?.toString() ?: ""
            val packageName = node.packageName?.toString() ?: ""
            
            if (isKeyboardRelatedElement(node, text, desc, className, packageName)) {
                val rect = android.graphics.Rect()
                node.getBoundsInScreen(rect)
                
                val element = org.json.JSONObject().apply {
                    put("id", "${node.hashCode()}_kb_$depth")
                    put("text", text)
                    put("description", desc)
                    put("className", className)
                    put("packageName", packageName)
                    put("bounds", org.json.JSONObject().apply {
                        put("centerX", rect.centerX())
                        put("centerY", rect.centerY())
                        put("width", rect.width())
                        put("height", rect.height())
                    })
                    put("clickable", node.isClickable)
                    put("detectionMethod", "keyboard_special_scan")
                    put("keyboardType", determineKeyboardType(node, text, desc, className))
                    put("confidence", calculateElementConfidence(node, text, desc, className))
                }
                
                results.put(element)
                Log.d(TAG, "🎹 发现键盘元素: '$text' ($className)")
            }
            
            // 递归扫描子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    scanForKeyboardElements(it, results, depth + 1, maxDepth)
                    it.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "扫描键盘元素失败", e)
        }
    }
    
    /**
     * ✅ 数字按钮全面检测
     */
    private fun detectDigitButtonsComprehensively(rootNode: AccessibilityNodeInfo): org.json.JSONArray {
        val digitButtons = org.json.JSONArray()
        
        try {
            // 1. 标准数字检测
            scanForDigitButtons(rootNode, digitButtons, 0, 20)
            
            // 2. 模糊数字检测（处理显示为"•"或"*"的密码输入）
            scanForMaskedDigitButtons(rootNode, digitButtons, 0, 15)
            
            Log.i(TAG, "🔢 全面检测到 ${digitButtons.length()} 个数字按钮")
        } catch (e: Exception) {
            Log.e(TAG, "数字按钮全面检测失败", e)
        }
        
        return digitButtons
    }
    
    /**
     * ✅ 扫描数字按钮
     */
    private fun scanForDigitButtons(
        node: AccessibilityNodeInfo,
        results: org.json.JSONArray,
        depth: Int,
        maxDepth: Int
    ) {
        if (depth > maxDepth) return
        
        try {
            val text = node.text?.toString() ?: ""
            val desc = node.contentDescription?.toString() ?: ""
            
            if (isDigitButton(text, desc)) {
                val rect = android.graphics.Rect()
                node.getBoundsInScreen(rect)
                
                val digit = extractDigit(text, desc)
                if (digit != null) {
                    val button = org.json.JSONObject().apply {
                        put("digit", digit)
                        put("text", text)
                        put("description", desc)
                        put("centerX", rect.centerX())
                        put("centerY", rect.centerY())
                        put("width", rect.width())
                        put("height", rect.height())
                        put("clickable", node.isClickable)
                        put("detectionMethod", "comprehensive_digit_scan")
                        put("confidence", if (text == digit) 0.95 else 0.8)
                    }
                    
                    results.put(button)
                    Log.d(TAG, "🔢 发现数字按钮: '$digit' at (${rect.centerX()}, ${rect.centerY()})")
                }
            }
            
            // 递归扫描
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    scanForDigitButtons(it, results, depth + 1, maxDepth)
                    it.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "扫描数字按钮失败", e)
        }
    }
    
    /**
     * ✅ 扫描被遮盖的数字按钮
     */
    private fun scanForMaskedDigitButtons(
        node: AccessibilityNodeInfo,
        results: org.json.JSONArray,
        depth: Int,
        maxDepth: Int
    ) {
        if (depth > maxDepth) return
        
        try {
            val className = node.className?.toString() ?: ""
            val rect = android.graphics.Rect()
            node.getBoundsInScreen(rect)
            
            // 检测可能是数字按钮的特征（大小、位置、类型）
            if (isPotentialDigitButton(node, rect, className)) {
                val button = org.json.JSONObject().apply {
                    put("text", node.text?.toString() ?: "")
                    put("description", node.contentDescription?.toString() ?: "")
                    put("className", className)
                    put("centerX", rect.centerX())
                    put("centerY", rect.centerY())
                    put("width", rect.width())
                    put("height", rect.height())
                    put("clickable", node.isClickable)
                    put("detectionMethod", "masked_digit_detection")
                    put("confidence", 0.6) // 较低的置信度，因为是推测
                    put("isPotentialDigit", true)
                }
                
                results.put(button)
                Log.d(TAG, "🔢 发现潜在数字按钮: $className at (${rect.centerX()}, ${rect.centerY()})")
            }
            
            // 递归扫描
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    scanForMaskedDigitButtons(it, results, depth + 1, maxDepth)
                    it.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "扫描遮盖数字按钮失败", e)
        }
    }
    
    /**
     * ✅ 判断是否为潜在的数字按钮
     */
    private fun isPotentialDigitButton(node: AccessibilityNodeInfo, rect: android.graphics.Rect, className: String): Boolean {
        val screenWidth = context.resources.displayMetrics.widthPixels
        val screenHeight = context.resources.displayMetrics.heightPixels
        
        // 1. 必须可点击
        if (!node.isClickable) return false
        
        // 2. 大小合理（典型的按钮大小）
        val minSize = screenWidth * 0.08 // 最小8%屏幕宽度
        val maxSize = screenWidth * 0.3  // 最大30%屏幕宽度
        if (rect.width() < minSize || rect.height() < minSize || 
            rect.width() > maxSize || rect.height() > maxSize) {
            return false
        }
        
        // 3. 位置在屏幕下半部分（键盘通常在这里）
        if (rect.centerY() < screenHeight * 0.4) return false
        
        // 4. 类名包含按钮相关的词
        val isButtonLike = className.lowercase().let { cls ->
            cls.contains("button") || cls.contains("image") || cls.contains("text")
        }
        
        return isButtonLike
    }
    
    /**
     * ✅ 检测输入法窗口
     */
    private fun detectInputMethodWindows(): org.json.JSONArray {
        val windows = org.json.JSONArray()
        
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                // 尝试通过反射获取窗口信息
                try {
                    val serviceClass = android.accessibilityservice.AccessibilityService::class.java
                    val getWindowsMethod = serviceClass.getDeclaredMethod("getWindows")
                    getWindowsMethod.isAccessible = true
                    
                    @Suppress("UNCHECKED_CAST")
                    val windowList = getWindowsMethod.invoke(service) as? List<android.view.accessibility.AccessibilityWindowInfo>
                    
                    windowList?.forEach { window ->
                        if (window.type == android.view.accessibility.AccessibilityWindowInfo.TYPE_INPUT_METHOD) {
                            val windowInfo = org.json.JSONObject().apply {
                                put("type", "INPUT_METHOD")
                                put("id", window.id)
                                put("title", window.title?.toString() ?: "")
                                put("detectionMethod", "accessibility_window_api")
                            }
                            
                            // 尝试获取窗口内容
                            window.root?.let { root ->
                                val elements = extractElementsFromInputMethodWindow(root)
                                if (elements.length() > 0) {
                                    windowInfo.put("elements", elements)
                                }
                                root.recycle()
                            }
                            
                            windows.put(windowInfo)
                            Log.i(TAG, "🪟 发现输入法窗口: ${window.title}")
                        }
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "通过API检测输入法窗口失败", e)
                }
            }
            
            // 备用检测方法：通过系统服务
            val imm = context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager
            if (imm?.isActive == true) {
                val backupWindow = org.json.JSONObject().apply {
                    put("type", "INPUT_METHOD")
                    put("detectionMethod", "input_method_manager")
                    put("isActive", true)
                }
                windows.put(backupWindow)
                Log.i(TAG, "🪟 通过IMM检测到活跃输入法")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "检测输入法窗口失败", e)
        }
        
        return windows
    }
    
    /**
     * ✅ 从输入法窗口提取元素
     */
    private fun extractElementsFromInputMethodWindow(root: AccessibilityNodeInfo): org.json.JSONArray {
        val elements = org.json.JSONArray()
        
        try {
            extractElementsRecursively(root, elements, 0, 10)
        } catch (e: Exception) {
            Log.e(TAG, "从输入法窗口提取元素失败", e)
        }
        
        return elements
    }
    
    /**
     * ✅ 递归提取元素
     */
    private fun extractElementsRecursively(
        node: AccessibilityNodeInfo,
        results: org.json.JSONArray,
        depth: Int,
        maxDepth: Int
    ) {
        if (depth > maxDepth) return
        
        try {
            val text = node.text?.toString() ?: ""
            val desc = node.contentDescription?.toString() ?: ""
            val className = node.className?.toString() ?: ""
            
            if (node.isClickable || text.isNotEmpty() || desc.isNotEmpty()) {
                val rect = android.graphics.Rect()
                node.getBoundsInScreen(rect)
                
                val element = org.json.JSONObject().apply {
                    put("text", text)
                    put("description", desc)
                    put("className", className)
                    put("centerX", rect.centerX())
                    put("centerY", rect.centerY())
                    put("clickable", node.isClickable)
                    put("source", "input_method_window")
                }
                
                results.put(element)
            }
            
            // 递归处理子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    extractElementsRecursively(it, results, depth + 1, maxDepth)
                    it.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "递归提取元素失败", e)
        }
    }
    
    /**
     * ✅ 计算键盘检测置信度
     */
    private fun calculateKeyboardConfidence(
        keyboardElements: org.json.JSONArray,
        digitButtons: org.json.JSONArray,
        inputMethodWindows: org.json.JSONArray
    ): Double {
        var confidence = 0.0
        
        // 输入法窗口存在 +0.4
        if (inputMethodWindows.length() > 0) {
            confidence += 0.4
        }
        
        // 键盘元素存在 +0.3
        if (keyboardElements.length() > 0) {
            confidence += 0.3
        }
        
        // 数字按钮完整性检查
        val digitCount = digitButtons.length()
        when {
            digitCount >= 10 -> confidence += 0.3 // 完整数字键盘
            digitCount >= 5 -> confidence += 0.2  // 部分数字键盘
            digitCount >= 1 -> confidence += 0.1  // 有数字按钮
        }
        
        return kotlin.math.min(1.0, confidence)
    }
    
    /**
     * ✅ 辅助方法：判断是否为键盘相关元素
     */
    private fun isKeyboardRelatedElement(
        node: AccessibilityNodeInfo,
        text: String,
        desc: String,
        className: String,
        packageName: String
    ): Boolean {
        // 包名检查
        val keyboardPackages = listOf("inputmethod", "keyboard", "sogou", "baidu", "iflytek", "android.inputmethod")
        if (keyboardPackages.any { packageName.lowercase().contains(it) }) {
            return true
        }
        
        // 类名检查
        val keyboardClasses = listOf("keyboard", "inputmethod", "keyboardview", "inputview", "key")
        if (keyboardClasses.any { className.lowercase().contains(it) }) {
            return true
        }
        
        // 文本内容检查
        if (isDigitButton(text, desc)) {
            return true
        }
        
        return false
    }
    
    /**
     * ✅ 辅助方法：确定键盘类型
     */
    private fun determineKeyboardType(node: AccessibilityNodeInfo, text: String, desc: String, className: String): String {
        return when {
            isDigitButton(text, desc) -> "numeric"
            className.lowercase().contains("qwerty") -> "qwerty"
            className.lowercase().contains("t9") -> "t9"
            className.lowercase().contains("pin") -> "pin"
            else -> "unknown"
        }
    }
    
    /**
     * ✅ 辅助方法：计算元素置信度
     */
    private fun calculateElementConfidence(node: AccessibilityNodeInfo, text: String, desc: String, className: String): Double {
        var confidence = 0.0
        
        if (isDigitButton(text, desc)) confidence += 0.4
        if (node.isClickable) confidence += 0.2
        if (className.lowercase().contains("button")) confidence += 0.2
        if (node.isVisibleToUser) confidence += 0.1
        if (node.isEnabled) confidence += 0.1
        
        return kotlin.math.min(1.0, confidence)
    }
    
    /**
     * ✅ 辅助方法：提取数字
     */
    private fun extractDigit(text: String, desc: String): String? {
        val digitRegex = Regex("[0-9]")
        return digitRegex.find(text)?.value ?: digitRegex.find(desc)?.value
    }
    
    /**
     * ✅ 辅助方法：判断是否为数字按钮
     */
    private fun isDigitButton(text: String, desc: String): Boolean {
        return text.matches(Regex("^[0-9]$")) || desc.matches(Regex("^[0-9]$"))
    }
} 