package com.hikoncont.service.modules

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

/**
 * 解锁管理模块
 * 负责处理锁屏解锁相关的所有功能
 */
class UnlockManager(
    private val service: AccessibilityRemoteService,
    private val context: Context,
    private val gestureController: GestureController,
    private val inputController: InputController
) {
    companion object {
        private const val TAG = "UnlockManager"
        private const val PREFS_NAME = "unlock_coords"
        private const val KEY_LEARNED_X = "learned_confirm_x"
        private const val KEY_LEARNED_Y = "learned_confirm_y"
        private const val KEY_LEARNED_WEIGHT = "learned_confirm_weight"
        private const val KEY_LEARNED_TYPE = "learned_confirm_type"
    }

    private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

    /**
     * 检测是否解锁成功
     */
    fun isUnlockSuccessful(): Boolean {
        return try {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.d(TAG, "🔍 解锁检测: 无法获取根节点")
                return false
            }
            
            val packageName = rootNode.packageName?.toString()?.lowercase() ?: ""
            Log.d(TAG, "🔍 解锁检测: 当前包名=$packageName")
            
            // 1. 检查是否还在锁屏界面（更严格的检测）
            val hasPasswordField = hasPasswordInputField(rootNode)
            val hasUnlockElements = hasUnlockScreenElements(rootNode)
            val isSystemUI = packageName.contains("systemui")
            
            // 如果在SystemUI但没有密码框和解锁元素，可能是解锁成功了
            if (isSystemUI && !hasPasswordField && !hasUnlockElements) {
                Log.d(TAG, "🔍 解锁检测: SystemUI界面但无锁屏元素，可能已解锁")
                return true
            }
            
            // 如果仍有密码框或解锁元素，说明还在锁屏
            if (isSystemUI && (hasPasswordField || hasUnlockElements)) {
                Log.d(TAG, "🔍 解锁检测: 仍在锁屏界面，解锁失败")
                return false
            }
            
            // 2. 检查是否进入了桌面或其他应用
            val isUnlocked = !isSystemUI || 
                            packageName.contains("launcher") ||
                            packageName.contains("home") ||
                            packageName.contains("desktop")
            
            // 3. 额外检查：如果包名完全不同，很可能是解锁成功了
            val isNonSystemApp = !packageName.contains("systemui") && 
                                !packageName.contains("android") &&
                                packageName.isNotEmpty()
            
            val finalResult = isUnlocked || isNonSystemApp
            
            Log.d(TAG, "🔍 解锁检测详情: SystemUI=$isSystemUI, 密码框=$hasPasswordField, 解锁元素=$hasUnlockElements")
            Log.d(TAG, "🔍 解锁检测结果: 已解锁=$finalResult")
            
            return finalResult
            
        } catch (e: Exception) {
            Log.e(TAG, "检测解锁状态失败", e)
            // 如果检测失败，保守地认为解锁成功（避免误判）
            Log.w(TAG, "🔍 解锁检测异常，保守认为解锁成功")
            return true
        }
    }

    /**
     * 检查是否有密码输入框
     */
    private fun hasPasswordInputField(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            var hasPasswordField = false
            
            fun checkPasswordField(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 30 || hasPasswordField) return
                
                val className = node.className?.toString()?.lowercase() ?: ""
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                
                // 检查是否是密码输入框
                if (className.contains("edittext") && 
                    (text.contains("password") || text.contains("密码") || 
                     desc.contains("password") || desc.contains("密码") ||
                     node.isPassword)) {
                    hasPasswordField = true
                    Log.d(TAG, "找到密码输入框: 类名='$className', 文本='$text', 描述='$desc'")
                    return
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        checkPasswordField(child, depth + 1)
                        child.recycle()
                    }
                }
            }
            
            checkPasswordField(rootNode)
            hasPasswordField
            
        } catch (e: Exception) {
            Log.e(TAG, "检查密码输入框失败", e)
            false
        }
    }

    /**
     * 检查是否有解锁屏幕元素
     */
    private fun hasUnlockScreenElements(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            var hasUnlockElements = false
            
            fun checkUnlockElements(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 30 || hasUnlockElements) return
                
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                
                // 检查解锁相关的元素
                val unlockKeywords = listOf(
                    // 中文关键词
                    "确认", "确定", "完成", "提交", "登录", "解锁", "继续", "下一步", "进入",
                    "好的", "同意", "允许", "授权", "开始", "立即", "确认解锁",
                    // 英文关键词
                    "ok", "done", "confirm", "submit", "enter", "go", "next", "continue", 
                    "login", "unlock", "agree", "allow", "start", "begin",
                    // 符号和特殊文本
                    "→", "✓", "√", "⏎", "↵", "✔",
                    // 软键盘相关
                    "发送", "send", "搜索", "search", "返回", "return",
                    "换行", "newline", "回车", "enter key", "确认键"
                )
                
                if (unlockKeywords.any { keyword ->
                    text.contains(keyword) || desc.contains(keyword)
                }) {
                    hasUnlockElements = true
                    Log.d(TAG, "找到解锁元素: 文本='$text', 描述='$desc'")
                    return
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        checkUnlockElements(child, depth + 1)
                        child.recycle()
                    }
                }
            }
            
            checkUnlockElements(rootNode)
            hasUnlockElements
            
        } catch (e: Exception) {
            Log.e(TAG, "检查解锁元素失败", e)
            false
        }
    }

    /**
     * 获取学习到的确认按钮坐标（增加验证机制）
     */
    fun getLearnedConfirmButtonCoords(): Pair<Float, Float>? {
        return try {
            val x = prefs.getFloat(KEY_LEARNED_X, -1f)
            val y = prefs.getFloat(KEY_LEARNED_Y, -1f)
            val weight = prefs.getFloat(KEY_LEARNED_WEIGHT, 0f)
            val type = prefs.getString(KEY_LEARNED_TYPE, "") ?: ""
            
            Log.i(TAG, "🧠 [获取学习坐标] 原始数据: x=$x, y=$y, weight=$weight, type='$type'")
            
            if (x <= 0 || y <= 0 || weight <= 0) {
                Log.w(TAG, "🧠 ❌ 无效的学习坐标数据: x=$x, y=$y, weight=$weight")
                return null
            }
            
            // ✅ 验证学习到的坐标是否合理（防止错误的键盘按键坐标）
            val (screenWidth, screenHeight) = getCurrentScreenSize()
            Log.i(TAG, "🧠 [坐标验证] 屏幕尺寸: ${screenWidth}x${screenHeight}")
            
            if (!isValidConfirmButtonCoords(x, y, screenWidth, screenHeight)) {
                Log.w(TAG, "🚫 学习到的坐标验证失败，清除无效坐标: ($x, $y)")
                clearLearnedConfirmButtonCoords()
                return null
            }
            
            Log.i(TAG, "🧠 ✅ 获取有效学习坐标: ($x, $y), 权重=$weight, 类型=$type")
            return Pair(x, y)
        } catch (e: Exception) {
            Log.e(TAG, "获取学习坐标失败", e)
            null
        }
    }

    /**
     * 清除学习到的确认按钮坐标
     */
    fun clearLearnedConfirmButtonCoords() {
        try {
            prefs.edit().apply {
                remove(KEY_LEARNED_X)
                remove(KEY_LEARNED_Y)
                remove(KEY_LEARNED_WEIGHT)
                remove(KEY_LEARNED_TYPE)
                apply()
            }
            Log.i(TAG, "🗑️ 已清除学习到的确认按钮坐标")
        } catch (e: Exception) {
            Log.e(TAG, "清除学习坐标失败", e)
        }
    }

    /**
     * 获取当前屏幕尺寸
     */
    private fun getCurrentScreenSize(): Pair<Int, Int> {
        return try {
            val displayMetrics = context.resources.displayMetrics
            Pair(displayMetrics.widthPixels, displayMetrics.heightPixels)
        } catch (e: Exception) {
            Log.e(TAG, "获取屏幕尺寸失败", e)
            Pair(1080, 2160) // 默认值
        }
    }

    /**
     * 验证是否为有效的确认按钮坐标（防止键盘按键误识别）
     */
    fun isValidConfirmButtonCoords(x: Float, y: Float, screenWidth: Int, screenHeight: Int, buttonText: String = "", buttonDesc: String = ""): Boolean {
        try {
            Log.d(TAG, "🔍 [坐标验证] 开始验证坐标: ($x, $y), 屏幕: ${screenWidth}x${screenHeight}, 文本: '$buttonText', 描述: '$buttonDesc'")
            
            // 查找确认按钮的常见文本
            val confirmTextLists = arrayOf(
                "确认", "确定", "OK", "完成", "解锁", "登录", "提交",
                "Enter", "Done", "Unlock", "Login", "Submit", "Continue",
                "下一步", "Next", "Go", "开始", "Start", "→", "✓", "✔",
                // ✅ 新增：软键盘确认按钮的常见文本
                "发送", "Send", "搜索", "Search", "返回", "Return",
                "换行", "newline", "回车", "enter key", "确认键",
                // ✅ 新增：可能的图标描述
                "enter", "confirm", "submit", "ok", "done"
            )
            for (confirmText in confirmTextLists) {
                if (buttonDesc.contains(confirmText, ignoreCase = true) || buttonText.contains(confirmText, ignoreCase = true)) {
                    Log.i(TAG, "[正确文本不进行坐标验证] 确认按钮: '$buttonDesc'/'$buttonDesc'")
                    return true
                }
            }
           
                    

            // 🚫 防止键盘按键误识别
            if (isKeyboardKey(buttonText, buttonDesc)) {
                Log.w(TAG, "🚫 [验证失败] 坐标($x, $y)对应键盘按键，拒绝记录: 文本='$buttonText', 描述='$buttonDesc'")
                return false
            }
            Log.d(TAG, "✅ [验证步骤1] 键盘按键检查通过")
            
            // 🚫 坐标范围检查 - ✅ 修复：允许导航栏区域的坐标
            // 某些设备的确认按钮可能位于导航栏区域，稍微超出标准屏幕范围
            val extendedHeight = screenHeight + 100 // 允许超出100px的范围（导航栏区域）
            if (x < 0 || y < 0 || x > screenWidth || y > extendedHeight) {
                Log.w(TAG, "🚫 [验证失败] 坐标($x, $y)超出扩展屏幕范围: ${screenWidth}x${extendedHeight}")
                return false
            }
            Log.d(TAG, "✅ [验证步骤2] 坐标范围检查通过 (扩展高度: $extendedHeight)")
            
            // ✅ 记录坐标范围检查结果
            if (y > screenHeight) {
                Log.i(TAG, "📍 坐标($x, $y)在导航栏区域（Y>${screenHeight}），但在允许范围内")
            }
            
            // 🚫 确认按钮应该在屏幕下半部分（避免状态栏、通知栏区域）
            val minY = screenHeight * 0.8f
            if (y < minY) {
                Log.w(TAG, "🚫 [验证失败] 坐标($x, $y)位置太高，不像确认按钮: Y需要>$minY")
                return false
            }
            Log.d(TAG, "✅ [验证步骤3] 下半部分检查通过 (Y=$y > $minY)")
            
            // 🚫 数字密码键盘区域检查（防止误识别数字键）
            // 数字键盘通常在屏幕中央偏下，我们要避开这个区域
            val keyboardLeftX = screenWidth * 0.2f
            val keyboardRightX = screenWidth * 0.8f
            val keyboardTopY = screenHeight * 0.45f
            val keyboardBottomY = screenHeight * 0.8f
            val isInNumKeyboardArea = x > keyboardLeftX && x < keyboardRightX && 
                                     y > keyboardTopY && y < keyboardBottomY
            
            Log.d(TAG, "🔍 [验证步骤4] 数字键盘区域检查: 在区域内=$isInNumKeyboardArea (X: $keyboardLeftX-$keyboardRightX, Y: $keyboardTopY-$keyboardBottomY)")
            
            if (isInNumKeyboardArea && (buttonText.length == 1 && buttonText.all { it.isDigit() })) {
                Log.w(TAG, "🚫 [验证失败] 坐标($x, $y)在数字键盘区域且为单个数字，拒绝: '$buttonText'")
                return false
            }
            Log.d(TAG, "✅ [验证步骤4] 数字键盘区域检查通过")
            
            // ✅ 特殊检查：如果是明显的数字键坐标（如266, 1146这样的数字键坐标）
            val leftThreshold = screenWidth * 0.8f
            if (x < leftThreshold && buttonText.length <= 2) {
                Log.w(TAG, "🚫 [验证失败] 坐标($x, $y)太偏左且文本简短，可能是数字键: '$buttonText' (X需要>$leftThreshold)")
                return false
            }
            Log.d(TAG, "✅ [验证步骤5] 左侧检查通过 (X=$x > $leftThreshold)")
            
            Log.i(TAG, "✅ [验证成功] 坐标($x, $y)通过所有验证，可以作为确认按钮")
            return true
            
        } catch (e: Exception) {
            Log.e(TAG, "验证确认按钮坐标失败", e)
            return false
        }
    }

    /**
     * 记录手动确认按钮坐标（增加验证机制）
     */
    fun recordManualConfirmButtonCoords(x: Float, y: Float, type: String, weight: Float, screenWidth: Int = 1080, screenHeight: Int = 2160, buttonText: String = "", buttonDesc: String = "") {
        try {
            // 🔍 首先验证坐标是否有效
            if (!isValidConfirmButtonCoords(x, y, screenWidth, screenHeight, buttonText, buttonDesc)) {
                Log.w(TAG, "🚫 拒绝记录无效的确认按钮坐标: ($x, $y)")
                return
            }
            
            // 获取当前存储的权重
            val currentWeight = prefs.getFloat(KEY_LEARNED_WEIGHT, 0f)
            
            // ✅ 修复：手动点击的坐标应该始终被优先记录
            val isManualClick = type.contains("manual", ignoreCase = true)
            val shouldUpdate = weight > currentWeight || currentWeight == 0f || isManualClick
            
            if (shouldUpdate) {
                prefs.edit().apply {
                    putFloat(KEY_LEARNED_X, x)
                    putFloat(KEY_LEARNED_Y, y)
                    putFloat(KEY_LEARNED_WEIGHT, weight)
                    putString(KEY_LEARNED_TYPE, type)
                    apply()
                }
                
                val updateReason = when {
                    isManualClick -> "手动点击优先"
                    weight > currentWeight -> "权重更高"
                    currentWeight == 0f -> "首次记录"
                    else -> "强制更新"
                }
                
                Log.i(TAG, "🧠 [学习记录] 更新确认按钮坐标: ($x, $y), 类型=$type, 权重=$weight, 原因=$updateReason, 文本='$buttonText'")
            } else {
                Log.d(TAG, "🧠 [学习记录] 权重不够高，不更新: 当前权重=$currentWeight, 新权重=$weight, 类型=$type")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "记录确认按钮坐标失败", e)
        }
    }

    /**
     * 查找学习到的确认按钮
     */
    fun findLearnedConfirmButton(rootNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            val learnedCoords = getLearnedConfirmButtonCoords()
            if (learnedCoords == null) {
                Log.d(TAG, "🧠 没有学习到的确认按钮坐标")
                return null
            }
            
            val (targetX, targetY) = learnedCoords
            Log.d(TAG, "🧠 查找学习到的确认按钮，目标坐标: ($targetX, $targetY)")
            
            var bestMatch: AccessibilityNodeInfo? = null
            var minDistance = Float.MAX_VALUE
            val tolerance = 100f // 100像素容差
            
            fun findNearestButton(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 15) return
                
                try {
                    if (node.isClickable) {
                        val bounds = Rect()
                        node.getBoundsInScreen(bounds)
                        val centerX = bounds.centerX().toFloat()
                        val centerY = bounds.centerY().toFloat()
                        
                        // 计算距离
                        val distance = kotlin.math.sqrt(
                            (centerX - targetX) * (centerX - targetX) + 
                            (centerY - targetY) * (centerY - targetY)
                        )
                        
                        if (distance < tolerance && distance < minDistance) {
                            val text = node.text?.toString() ?: ""
                            val desc = node.contentDescription?.toString() ?: ""
                            
                            // 排除明显不是确认按钮的元素
                            if (!text.contains("emergency", ignoreCase = true) &&
                                !text.contains("紧急", ignoreCase = true) &&
                                !desc.contains("emergency", ignoreCase = true)) {
                                
                                bestMatch = node
                                minDistance = distance
                                Log.d(TAG, "🧠 找到更近的候选按钮: 距离=$distance, 文本='$text', 描述='$desc'")
                            }
                        }
                    }
                    
                    // 递归检查子节点
                    for (i in 0 until node.childCount) {
                        val child = node.getChild(i)
                        if (child != null) {
                            findNearestButton(child, depth + 1)
                            child.recycle()
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "查找最近按钮失败", e)
                }
            }
            
            findNearestButton(rootNode)
            
            if (bestMatch != null) {
                Log.i(TAG, "🧠 ✅ 找到学习到的确认按钮，距离=$minDistance")
            } else {
                Log.d(TAG, "🧠 ❌ 未找到匹配的学习确认按钮")
            }
            
            bestMatch
            
        } catch (e: Exception) {
            Log.e(TAG, "查找学习确认按钮失败", e)
            null
        }
    }





    /**
     * 验证确认按钮位置是否合理
     */
    fun isValidConfirmButtonPosition(rect: Rect, screenWidth: Int, screenHeight: Int): Boolean {
        val centerX = rect.centerX()
        val centerY = rect.centerY()
        
        // ✅ 确认按钮应该在屏幕下半部分
        if (centerY <= screenHeight * 0.8) {
            Log.d(TAG, "🚫 位置太高，不在屏幕下半部分: Y=$centerY, 需要>${screenHeight * 0.8}")
            return false
        }
        
        // ✅ 确认按钮不应该在屏幕边缘
        val margin = screenWidth * 0.03 // 3%边距
        if (centerX < margin || centerX > screenWidth - margin) {
            Log.d(TAG, "🚫 位置在屏幕边缘: X=$centerX, 边距=$margin")
            return false
        }
        
        return true
    }

    /**
     * 验证确认按钮大小是否合理
     */
    fun isValidConfirmButtonSize(rect: Rect, screenWidth: Int, screenHeight: Int): Boolean {
        val buttonWidth = rect.width()
        val buttonHeight = rect.height()
        
        // ✅ 按钮不能太小（避免误识别小图标）
        val minSize = screenWidth * 0.04 // 最小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 isKeyboardKey(text: String, desc: String): Boolean {
        // 🚫 单个字符（字母、数字、符号）
        if (text.length == 1) {
            Log.d(TAG, "🚫 过滤单个字符键盘按键: '$text'")
            return true
        }
        
        // 🚫 常见键盘按键文本（包括完整单词）
        val keyboardTexts = setOf(
            // 字母键
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", 
            "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 
            "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
            // 数字键
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            // 符号键
            ".", ",", "?", "!", "'", "\"", "-", "(", ")", "@", ";", ":", "/", "&", "%", "+", "=", "*", "#",
            // 功能键
            "删除", "delete", "Delete", "DEL", "⌫", "退格", "backspace", "Backspace",
            "空格", "space", "Space", "SPACE", " ",
            "切换", "shift", "Shift", "SHIFT", "⇧",
            "符号", "123", "ABC", "?123", "符", "数字", "字母", "紧急呼叫", "紧急拨号"
        )
        
        if (text.lowercase() in keyboardTexts.map { it.lowercase() }) {
            Log.d(TAG, "🚫 过滤键盘按键文本: '$text'")
            return true
        }
        
        // 🚫 常见键盘按键描述，但排除锁屏确认按钮的情况
        val keyboardDescs = setOf(
            "delete", "backspace", "space", "shift",  "tab",
            "删除", "退格", "空格", "换行",  "制表符", "切换", "符号", "数字", "字母", "紧急呼叫", "紧急拨号"
        )
        
        for (keyDesc in keyboardDescs) {
            if (desc.contains(keyDesc, ignoreCase = true)) {
                Log.d(TAG, "🚫 过滤键盘按键描述: '$desc'")
                return true
            }
        }
        
        // ⚠️ 特殊处理：Enter按钮可能是确认按钮也可能是键盘按键
        if (desc.equals("Enter", ignoreCase = true)) {
            // 检查当前是否在锁屏界面
            val rootNode = service.rootInActiveWindow
            val currentPackage = rootNode?.packageName?.toString() ?: ""
            val isLockScreen = currentPackage.contains("systemui", ignoreCase = true) || 
                              currentPackage.contains("lockscreen", ignoreCase = true)
            
            if (isLockScreen) {
                Log.d(TAG, "✅ 锁屏界面的Enter按钮，识别为确认按钮而非键盘按键")
                return false // 不是键盘按键，是确认按钮
            } else {
                Log.d(TAG, "🚫 非锁屏界面的Enter按钮，识别为键盘按键")
                return true // 是键盘按键
            }
        }
        
        return false
    }

    /**
     * 检查是否为确认关键词
     */
    fun isConfirmKeyword(text: String): Boolean {
        val confirmKeywords = setOf(
            // 中文关键词
            "确认", "确定", "完成", "提交", "登录", "解锁", "继续", "下一步", "进入",
            "好的", "同意", "允许", "授权", "开始", "立即", "确认解锁",
            // 英文关键词
            "ok", "done", "confirm", "submit", "enter", "go", "next", "continue", 
            "login", "unlock", "agree", "allow", "start", "begin",
            // 符号和特殊文本
            "→", "✓", "√", "⏎", "↵"
        )
        return confirmKeywords.any { text.contains(it, ignoreCase = true) }
    }

    /**
     * ✅ 智能查找确认按钮 - 结合多种策略的综合方法
     */
    fun findSmartConfirmButton(rootNode: AccessibilityNodeInfo, screenWidth: Int, screenHeight: Int, passwordType: String): Pair<Float, Float>? {
        try {
            Log.d(TAG, "🤖 开始智能确认按钮查找: 密码类型=$passwordType, 屏幕=${screenWidth}x${screenHeight}")
            
            // ✅ 策略1: 优先使用学习到的坐标（最可靠），如果有则直接返回不执行后续策略
            val learnedCoords = getLearnedConfirmButtonCoords()
            if (learnedCoords != null) {
                Log.i(TAG, "✅ [保存坐标优先] 使用学习到的确认按钮坐标，跳过其他策略: (${learnedCoords.first}, ${learnedCoords.second})")
                return learnedCoords
            }
            
            // ✅ 策略2: 智能文本匹配（最准确）
            val textMatchCoords = findBestConfirmButtonByText(rootNode, screenWidth, screenHeight)
            if (textMatchCoords != null) {
                Log.i(TAG, "✅ 通过智能文本匹配找到确认按钮: (${textMatchCoords.first}, ${textMatchCoords.second})")
                // 学习这个成功的坐标
                recordManualConfirmButtonCoords(textMatchCoords.first, textMatchCoords.second, "智能文本匹配", 0.8f, screenWidth, screenHeight)
                return textMatchCoords
            }
            
            // ✅ 策略3: 根据密码类型的区域搜索（针对性强）
            val typeSpecificCoords = findConfirmButtonByPasswordType(rootNode, screenWidth, screenHeight, passwordType)
            if (typeSpecificCoords != null) {
                Log.i(TAG, "✅ 通过密码类型区域搜索找到确认按钮: (${typeSpecificCoords.first}, ${typeSpecificCoords.second})")
                // 学习这个成功的坐标
                recordManualConfirmButtonCoords(typeSpecificCoords.first, typeSpecificCoords.second, "密码类型区域", 0.7f, screenWidth, screenHeight)
                return typeSpecificCoords
            }
            
            Log.w(TAG, "⚠️ 所有策略都未找到合适的确认按钮")
            return null
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 智能确认按钮查找异常", e)
            return null
        }
    }

    /**
     * ✅ 优化：通过文本匹配查找最佳确认按钮 - 增强准确性和效率
     */
    private fun findBestConfirmButtonByText(rootNode: AccessibilityNodeInfo, screenWidth: Int, screenHeight: Int): Pair<Float, Float>? {
        val confirmButtonCandidates = mutableListOf<ConfirmButtonCandidate>()
        
        fun searchByText(node: AccessibilityNodeInfo, depth: Int = 0) {
            if (depth > 30) return // 限制递归深度提高性能
            
            try {
                if (node.isClickable) {
                    val text = node.text?.toString()?.trim() ?: ""
                    val desc = node.contentDescription?.toString()?.trim() ?: ""
                    val className = node.className?.toString() ?: ""
                    
                    // 🚫 严格过滤键盘按键 - 优化性能
                    if (isKeyboardKey(text, desc)) {
                        return
                    }
                    
                    // ✅ 明确排除紧急呼叫等非确认按钮
                    val excludeTexts = arrayOf(
                        "紧急呼叫", "Emergency", "Emergency call", "紧急电话", 
                        "取消", "Cancel", "返回", "Back", "忘记", "Forgot",
                        "相机", "Camera", "锁屏画报", "充电", "Battery"
                    )
                    for (excludeText in excludeTexts) {
                        if (text.contains(excludeText, ignoreCase = true) || desc.contains(excludeText, ignoreCase = true)) {
                            Log.d(TAG, "🚫 [搜索排除] 跳过非确认按钮: '$text'/'$desc'")
                            return
                        }
                    }
                    
                    // ✅ 优化：分层级匹配，提高准确性
                    val candidate = evaluateConfirmButtonCandidate(node, text, desc, className, screenWidth, screenHeight)
                    if (candidate != null && candidate.score > 0) {
                        confirmButtonCandidates.add(candidate)
                        Log.d(TAG, "🔍 找到确认按钮候选: '$text'/'$desc' 得分=${candidate.score} 位置=(${candidate.x}, ${candidate.y})")
                    }
                }
                
                // 递归搜索子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let { 
                        searchByText(it, depth + 1)
                        child.recycle()
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "文本匹配搜索失败", e)
            }
        }
        
        searchByText(rootNode)
        
        // ✅ 优化：按综合得分排序，选择最佳候选
        if (confirmButtonCandidates.isNotEmpty()) {
            val bestCandidate = confirmButtonCandidates.maxByOrNull { it.score }
            if (bestCandidate != null && bestCandidate.score >= 3) { // 设置最低得分门槛
                Log.i(TAG, "🎯 选择最佳确认按钮: 得分=${bestCandidate.score} 位置=(${bestCandidate.x}, ${bestCandidate.y}) 原因=${bestCandidate.reason}")
                return Pair(bestCandidate.x, bestCandidate.y)
            } else {
                Log.w(TAG, "⚠️ 最佳候选得分过低: ${bestCandidate?.score ?: 0}")
            }
        }
        
        return null
    }
    
    /**
     * ✅ 新增：确认按钮候选数据类
     */
    private data class ConfirmButtonCandidate(
        val x: Float,
        val y: Float,
        val score: Int,
        val reason: String,
        val text: String,
        val desc: String
    )
    
    /**
     * ✅ 新增：评估确认按钮候选的综合得分
     */
    private fun evaluateConfirmButtonCandidate(
        node: AccessibilityNodeInfo, 
        text: String, 
        desc: String, 
        className: String,
        screenWidth: Int, 
        screenHeight: Int
    ): ConfirmButtonCandidate? {
        try {
            val rect = android.graphics.Rect()
            node.getBoundsInScreen(rect)
            val centerX = rect.centerX().toFloat()
            val centerY = rect.centerY().toFloat()
            
            // 基础坐标验证
            if (!isValidConfirmButtonCoords(centerX, centerY, screenWidth, screenHeight, text, desc)) {
                return null
            }
            
            var score = 0
            val reasons = mutableListOf<String>()
            
            // ✅ 文本匹配评分 (最高10分)
            val textScore = evaluateTextMatch(text, desc)
            score += textScore.first
            if (textScore.second.isNotEmpty()) reasons.add(textScore.second)
            
            // ✅ 如果文本评分为负数（被明确排除），直接返回null
            if (textScore.first < 0) {
                Log.d(TAG, "🚫 [候选排除] 按钮被明确排除: '$text'/'$desc', 原因: ${textScore.second}")
                return null
            }
            
            // ✅ 位置评分 (最高5分)
            val positionScore = evaluatePosition(centerX, centerY, screenWidth, screenHeight)
            score += positionScore.first
            if (positionScore.second.isNotEmpty()) reasons.add(positionScore.second)
            
            // ✅ 尺寸评分 (最高3分)
            val sizeScore = evaluateSize(rect, screenWidth, screenHeight)
            score += sizeScore.first
            if (sizeScore.second.isNotEmpty()) reasons.add(sizeScore.second)
            
            // ✅ 类名评分 (最高2分)
            val classScore = evaluateClassName(className)
            score += classScore.first
            if (classScore.second.isNotEmpty()) reasons.add(classScore.second)
            
            return if (score > 0) {
                ConfirmButtonCandidate(centerX, centerY, score, reasons.joinToString(", "), text, desc)
            } else null
            
        } catch (e: Exception) {
            Log.e(TAG, "评估确认按钮候选失败", e)
            return null
        }
    }
    
    /**
     * ✅ 新增：文本匹配评分
     */
    private fun evaluateTextMatch(text: String, desc: String): Pair<Int, String> {
        // ✅ 首先排除明确的非确认按钮（紧急呼叫、取消等）
        val excludeTexts = arrayOf(
            "紧急呼叫", "Emergency", "Emergency call", "紧急电话", 
            "取消", "Cancel", "返回", "Back", "忘记", "Forgot",
            "相机", "Camera", "锁屏画报", "充电", "Battery"
        )
        for (excludeText in excludeTexts) {
            if (text.contains(excludeText, ignoreCase = true) || desc.contains(excludeText, ignoreCase = true)) {
                Log.d(TAG, "🚫 [文本排除] 明确排除非确认按钮: '$text'/'$desc'")
                return Pair(-10, "明确排除按钮") // 负分强制排除
            }
        }
        
        // 超高优先级 (10分)
        val ultraHighTexts = arrayOf(
            "确认", "确定", "ok", "done", "enter", "完成", "提交", "continue", "submit", "go"
        )
        for (confirmText in ultraHighTexts) {
            if (text.equals(confirmText, ignoreCase = true)) {
                return Pair(10, "超高优先级文本匹配")
            }
        }
        
        // 高优先级 (8分)
        val highTexts = arrayOf("回车","完成", "提交", "登录", "解锁", "Submit", "Login", "Unlock")
        for (confirmText in highTexts) {
            if (text.contains(confirmText, ignoreCase = true) || desc.contains(confirmText, ignoreCase = true)) {
                return Pair(8, "高优先级文本匹配")
            }
        }
        
        // 中优先级 (5分)
        val mediumTexts = arrayOf("继续", "下一步",  "Continue", "Next", "Go")
        for (confirmText in mediumTexts) {
            if (text.contains(confirmText, ignoreCase = true) || desc.contains(confirmText, ignoreCase = true)) {
                return Pair(5, "中优先级文本匹配")
            }
        }
        
        // 符号匹配 (3分)
        val symbolTexts = arrayOf("→", "✓", "√", "⏎", "↵", "▶")
        for (symbol in symbolTexts) {
            if (text.contains(symbol) || desc.contains(symbol)) {
                return Pair(3, "符号匹配")
            }
        }
        
        // 无明确文本但可能是图标按钮 (1分)
        if (text.isEmpty() && desc.isEmpty()) {
            return Pair(1, "可能图标按钮")
        }
        
        return Pair(0, "")
    }
    
    /**
     * ✅ 新增：位置评分
     */
    private fun evaluatePosition(x: Float, y: Float, screenWidth: Int, screenHeight: Int): Pair<Int, String> {
        var score = 0
        val reasons = mutableListOf<String>()
        
        // 垂直位置评分
        if (y > screenHeight * 0.85) {
            score += 3
            reasons.add("在屏幕底部")
        } else if (y > screenHeight * 0.7) {
            score += 2
            reasons.add("在屏幕下方")
        }
        
        // 水平位置评分
        if (x > screenWidth * 0.7) {
            score += 2
            reasons.add("在屏幕右侧")
        } else if (x > screenWidth * 0.3 && x < screenWidth * 0.7) {
            score += 1
            reasons.add("在屏幕中央")
        }
        
        return Pair(score, reasons.joinToString(", "))
    }
    
    /**
     * ✅ 新增：尺寸评分
     */
    private fun evaluateSize(rect: android.graphics.Rect, screenWidth: Int, screenHeight: Int): Pair<Int, String> {
        val width = rect.width()
        val height = rect.height()
        val area = width * height
        val screenArea = screenWidth * screenHeight
        val areaRatio = area.toFloat() / screenArea
        
        return when {
            areaRatio > 0.02 && areaRatio < 0.1 -> Pair(3, "尺寸适中")
            areaRatio > 0.01 && areaRatio < 0.15 -> Pair(2, "尺寸合理")
            areaRatio > 0.005 && areaRatio < 0.2 -> Pair(1, "尺寸可接受")
            else -> Pair(0, "尺寸不合适")
        }
    }
    
    /**
     * ✅ 新增：类名评分
     */
    private fun evaluateClassName(className: String): Pair<Int, String> {
        return when {
            className.contains("Button", ignoreCase = true) -> Pair(2, "Button类")
            className.contains("ImageButton", ignoreCase = true) -> Pair(2, "ImageButton类")
            className.contains("TextView", ignoreCase = true) -> Pair(1, "TextView类")
            else -> Pair(0, "")
        }
    }

    /**
     * ✅ 根据密码类型查找特定位置的确认按钮
     */
    private fun findConfirmButtonByPasswordType(rootNode: AccessibilityNodeInfo, screenWidth: Int, screenHeight: Int, passwordType: String): Pair<Float, Float>? {
        when (passwordType) {
            "numeric" -> {
                // 数字密码：查找屏幕下方中央的确认按钮
                return findConfirmButtonInArea(rootNode, screenWidth, screenHeight, 0.4f, 0.6f, 0.75f, 1.0f)
            }
            "mixed" -> {
                // 混合密码：查找屏幕右下角的确认按钮
                return findConfirmButtonInArea(rootNode, screenWidth, screenHeight, 0.6f, 1.0f, 0.7f, 1.0f)
            }
            "text" -> {
                // 文本密码：查找屏幕右下角的确认按钮
                return findConfirmButtonInArea(rootNode, screenWidth, screenHeight, 0.5f, 1.0f, 0.6f, 1.0f)
            }
            else -> {
                // 通用：查找屏幕下半部分的确认按钮
                return findConfirmButtonInArea(rootNode, screenWidth, screenHeight, 0.2f, 0.8f, 0.5f, 1.0f)
            }
        }
    }

    /**
     * ✅ 在指定区域查找确认按钮
     */
    private fun findConfirmButtonInArea(
        rootNode: AccessibilityNodeInfo, 
        screenWidth: Int, 
        screenHeight: Int,
        leftRatio: Float, 
        rightRatio: Float, 
        topRatio: Float, 
        bottomRatio: Float
    ): Pair<Float, Float>? {
        val leftBound = screenWidth * leftRatio
        val rightBound = screenWidth * rightRatio
        val topBound = screenHeight * topRatio
        val bottomBound = screenHeight * bottomRatio
        
        val confirmButtonsInArea = mutableListOf<Pair<Float, Float>>()
        
        fun searchInArea(node: AccessibilityNodeInfo) {
            try {
                if (node.isClickable) {
                    val text = node.text?.toString()?.trim() ?: ""
                    val desc = node.contentDescription?.toString()?.trim() ?: ""
                    
                    // 🚫 过滤键盘按键
                    if (isKeyboardKey(text, desc)) {
                        return
                    }
                    
                    // ✅ 明确排除紧急呼叫等非确认按钮
                    val excludeTexts = arrayOf(
                        "紧急呼叫", "Emergency", "Emergency call", "紧急电话", 
                        "取消", "Cancel", "返回", "Back", "忘记", "Forgot",
                        "相机", "Camera", "锁屏画报", "充电", "Battery"
                    )
                    for (excludeText in excludeTexts) {
                        if (text.contains(excludeText, ignoreCase = true) || desc.contains(excludeText, ignoreCase = true)) {
                            Log.d(TAG, "🚫 [区域排除] 跳过非确认按钮: '$text'/'$desc'")
                            return
                        }
                    }
                    
                    // 检查是否为确认按钮
                    val confirmTexts = arrayOf(
                        "确认", "确定", "完成", "提交", "登录", "解锁", "继续", "下一步",
                        "Done", "Go", "Enter", "OK", "Submit", "Login", "Unlock", "Continue", "Next",
                        "→", "✓", "√", "⏎", "↵"
                    )
                    
                    val isConfirmCandidate = confirmTexts.any { confirmText ->
                        text.contains(confirmText, ignoreCase = true) || 
                        desc.contains(confirmText, ignoreCase = true)
                    }
                    
                    if (isConfirmCandidate) {
                        val rect = android.graphics.Rect()
                        node.getBoundsInScreen(rect)
                        val centerX = rect.centerX().toFloat()
                        val centerY = rect.centerY().toFloat()
                        
                        // 检查是否在指定区域内
                        if (centerX >= leftBound && centerX <= rightBound && 
                            centerY >= topBound && centerY <= bottomBound) {
                            
                            // 验证坐标有效性
                            if (isValidConfirmButtonCoords(centerX, centerY, screenWidth, screenHeight, text)) {
                                confirmButtonsInArea.add(Pair(centerX, centerY))
                                Log.d(TAG, "🔍 在指定区域找到确认按钮: '$text'/'$desc' 位置=($centerX, $centerY)")
                            }
                        }
                    }
                }
                
                // 递归搜索子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    child?.let { searchInArea(it) }
                }
            } catch (e: Exception) {
                Log.e(TAG, "区域搜索失败", e)
            }
        }
        
        searchInArea(rootNode)
        
        // 如果找到候选，返回第一个
        if (confirmButtonsInArea.isNotEmpty()) {
            val bestCandidate = confirmButtonsInArea.first()
            Log.i(TAG, "🎯 在指定区域选择确认按钮: (${bestCandidate.first}, ${bestCandidate.second})")
            return bestCandidate
        }
        
        return null
    }


    /**
     * 清除学习到的坐标
     */
    fun clearLearnedCoords() {
        try {
            prefs.edit().clear().apply()
            Log.i(TAG, "🧠 已清除学习到的确认按钮坐标")
        } catch (e: Exception) {
            Log.e(TAG, "清除学习坐标失败", e)
        }
    }
} 