package com.hikoncont.service.modules

import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * 调试和分析管理器
 * 负责UI状态捕获、调试报告生成和故障排查
 * 
 * 主要功能:
 * - UI状态捕获和分析
 * - 调试报告生成
 * - 节点层次结构分析
 * - 故障排查建议
 * - 性能监控和分析
 * - 屏幕元素详细分析
 */
class DebugAnalysisManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "DebugAnalysisManager"
    }
    
    // 协程作用域
    private val analysisScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    // 调试配置
    private var isDebugModeEnabled = false
    private var maxNodeDepth = 20
    private var maxElementsToAnalyze = 100
    
    // 统计数据
    private var totalElementsAnalyzed = 0
    private var totalDebugReports = 0
    
    // 日志记录回调
    private var logRecorder: ((String, String, Map<String, Any>) -> Unit)? = null
    
    /**
     * 初始化调试分析管理器
     */
    fun initialize() {
        Log.i(TAG, "✅ 调试和分析管理器初始化完成")
    }
    
    /**
     * 设置日志记录器
     */
    fun setLogRecorder(recorder: (String, String, Map<String, Any>) -> Unit) {
        logRecorder = recorder
    }
    
    /**
     * 启用调试模式
     */
    fun enableDebugMode() {
        isDebugModeEnabled = true
        Log.i(TAG, "🔍 调试模式已启用")
        recordDebugLog("调试模式已启用")
    }
    
    /**
     * 禁用调试模式
     */
    fun disableDebugMode() {
        isDebugModeEnabled = false
        Log.i(TAG, "🔇 调试模式已禁用")
        recordDebugLog("调试模式已禁用")
    }
    
    /**
     * 捕获UI状态
     */
    fun captureUIState(): UIStateSnapshot? {
        return analysisScope.runCatching {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "❌ 无法获取根节点进行UI状态捕获")
                return@runCatching null
            }
            
            val packageName = rootNode.packageName?.toString() ?: "unknown"
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            val allElements = mutableListOf<UIElement>()
            val clickableElements = mutableListOf<UIElement>()
            val inputElements = mutableListOf<UIElement>()
            
            analyzeNodeRecursively(rootNode, allElements, clickableElements, inputElements, 0)
            
            val snapshot = UIStateSnapshot(
                timestamp = System.currentTimeMillis(),
                packageName = packageName,
                screenWidth = screenWidth,
                screenHeight = screenHeight,
                totalElements = allElements.size,
                clickableElements = clickableElements,
                inputElements = inputElements,
                allElements = allElements.take(maxElementsToAnalyze)
            )
            
            totalElementsAnalyzed += allElements.size
            rootNode.recycle()
            
            Log.i(TAG, "📸 UI状态捕获完成: 包名=$packageName, 元素=${allElements.size}个")
            recordDebugLog("UI状态捕获完成", mapOf(
                "packageName" to packageName,
                "elementCount" to allElements.size,
                "clickableCount" to clickableElements.size
            ))
            
            snapshot
            
        }.getOrElse { e ->
            Log.e(TAG, "❌ UI状态捕获失败", e)
            null
        }
    }
    
    /**
     * 生成调试报告
     */
    fun generateDebugReport(): DebugReport {
        return analysisScope.runCatching {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                return@runCatching DebugReport.empty("无法获取根节点")
            }
            
            Log.i(TAG, "📋 ===== 调试报告开始 =====")
            
            val packageName = rootNode.packageName?.toString() ?: "unknown"
            val className = rootNode.className?.toString() ?: "unknown"
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            // 1. 基本信息
            val basicInfo = mapOf(
                "packageName" to packageName,
                "className" to className,
                "screenSize" to "${screenWidth}x${screenHeight}",
                "timestamp" to System.currentTimeMillis()
            )
            
            // 2. 权限状态
            val permissionInfo = analyzePermissionStatus()
            
            // 3. 应用节点分析
            val appNodeInfo = analyzeAppNodes(rootNode)
            
            // 4. 可点击元素分析
            val clickableInfo = analyzeClickableElements(rootNode)
            
            // 5. 开关控件分析
            val switchInfo = analyzeSwitchControls(rootNode)
            
            // 6. 文本元素分析
            val textInfo = analyzeTextElements(rootNode)
            
            // 7. 性能分析
            val performanceInfo = analyzePerformance()
            
            // 8. 故障排查建议
            val troubleshootingSuggestions = provideTroubleshootingSuggestions(
                packageName, 
                permissionInfo, 
                appNodeInfo
            )
            
            rootNode.recycle()
            totalDebugReports++
            
            val report = DebugReport(
                timestamp = System.currentTimeMillis(),
                basicInfo = basicInfo,
                permissionInfo = permissionInfo,
                appNodeInfo = appNodeInfo,
                clickableInfo = clickableInfo,
                switchInfo = switchInfo,
                textInfo = textInfo,
                performanceInfo = performanceInfo,
                troubleshootingSuggestions = troubleshootingSuggestions
            )
            
            Log.i(TAG, "📋 ===== 调试报告结束 =====")
            recordDebugLog("调试报告生成完成", mapOf("reportId" to totalDebugReports))
            
            report
            
        }.getOrElse { e ->
            Log.e(TAG, "❌ 生成调试报告失败", e)
            DebugReport.empty("生成调试报告失败: ${e.message}")
        }
    }
    
    /**
     * 调试当前屏幕元素
     */
    fun debugCurrentScreenElements() {
        analysisScope.launch {
            try {
                Log.i(TAG, "🔍 开始调试当前屏幕元素")
                
                val rootNode = service.rootInActiveWindow
                if (rootNode == null) {
                    Log.w(TAG, "❌ 无法获取根节点进行调试")
                    return@launch
                }
                
                val packageName = rootNode.packageName?.toString()
                val (screenWidth, screenHeight) = getRealScreenSize()
                
                Log.i(TAG, "🔍 [调试] ==================== 屏幕元素分析开始 ====================")
                Log.i(TAG, "🔍 [调试] 屏幕尺寸: ${screenWidth}x${screenHeight}")
                Log.i(TAG, "🔍 [调试] 当前包名: $packageName")
                
                val allClickableElements = mutableListOf<ClickableElementInfo>()
                val confirmButtonCandidates = mutableListOf<ClickableElementInfo>()
                val keyboardKeys = mutableListOf<ClickableElementInfo>()
                
                // 递归分析所有节点
                analyzeNodeForDebug(rootNode, allClickableElements, confirmButtonCandidates, keyboardKeys, 0)
                
                Log.i(TAG, "🔍 [调试] 总共找到 ${allClickableElements.size} 个可点击元素")
                Log.i(TAG, "🔍 [调试] 其中 ${confirmButtonCandidates.size} 个确认按钮候选")
                Log.i(TAG, "🔍 [调试] 其中 ${keyboardKeys.size} 个键盘按键")
                
                // 输出确认按钮候选详情
                Log.i(TAG, "🔍 [调试] ========== 确认按钮候选详情 ==========")
                confirmButtonCandidates.forEachIndexed { index, element ->
                    Log.i(TAG, "🔍 [调试] 候选${index + 1}: ${element}")
                }
                
                // 输出键盘按键详情（只显示前10个）
                Log.i(TAG, "🔍 [调试] ========== 键盘按键详情(前10个) ==========")
                keyboardKeys.take(10).forEachIndexed { index, element ->
                    Log.i(TAG, "🔍 [调试] 按键${index + 1}: ${element}")
                }
                
                // 输出屏幕下半部分的所有可点击元素
                val bottomHalfElements = allClickableElements.filter { it.centerY > screenHeight * 0.6 }
                Log.i(TAG, "🔍 [调试] ========== 屏幕下半部分元素(${bottomHalfElements.size}个) ==========")
                bottomHalfElements.forEachIndexed { index, element ->
                    Log.i(TAG, "🔍 [调试] 下半${index + 1}: ${element}")
                }
                
                Log.i(TAG, "🔍 [调试] ==================== 屏幕元素分析结束 ====================")
                
                // 记录调试信息
                recordDebugLog("屏幕元素分析完成", mapOf(
                    "packageName" to (packageName ?: "unknown"),
                    "screenSize" to "${screenWidth}x${screenHeight}",
                    "clickableElementsCount" to allClickableElements.size,
                    "confirmCandidatesCount" to confirmButtonCandidates.size,
                    "keyboardKeysCount" to keyboardKeys.size
                ))
                
                rootNode.recycle()
                
            } catch (e: Exception) {
                Log.e(TAG, "🔍 [调试] 屏幕元素分析失败", e)
            }
        }
    }
    
    /**
     * 分析节点层次结构
     */
    fun analyzeNodeHierarchy(): NodeHierarchy? {
        return analysisScope.runCatching {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.w(TAG, "❌ 无法获取根节点进行层次结构分析")
                return@runCatching null
            }
            
            val hierarchy = NodeHierarchy(
                packageName = rootNode.packageName?.toString() ?: "unknown",
                rootClassName = rootNode.className?.toString() ?: "unknown",
                depth = calculateMaxDepth(rootNode),
                totalNodes = countTotalNodes(rootNode),
                nodeTree = buildNodeTree(rootNode, 0)
            )
            
            rootNode.recycle()
            
            Log.i(TAG, "🌳 节点层次结构分析完成: 深度=${hierarchy.depth}, 节点=${hierarchy.totalNodes}个")
            recordDebugLog("节点层次结构分析完成", mapOf(
                "depth" to hierarchy.depth,
                "totalNodes" to hierarchy.totalNodes
            ))
            
            hierarchy
            
        }.getOrElse { e ->
            Log.e(TAG, "❌ 节点层次结构分析失败", e)
            null
        }
    }
    
    /**
     * 打印节点层次结构
     */
    fun printNodeHierarchy() {
        analysisScope.launch {
            try {
                val rootNode = service.rootInActiveWindow
                if (rootNode == null) {
                    Log.w(TAG, "❌ 无法获取根节点进行层次结构打印")
                    return@launch
                }
                
                Log.i(TAG, "🌳 ==================== 节点层次结构 ====================")
                printNodeRecursively(rootNode, 0)
                Log.i(TAG, "🌳 ==================== 节点层次结构结束 ====================")
                
                rootNode.recycle()
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 打印节点层次结构失败", e)
            }
        }
    }
    
    /**
     * 提供故障排查建议
     */
    fun provideTroubleshootingSuggestions(
        packageName: String,
        permissionInfo: Map<String, Any>,
        appNodeInfo: Map<String, Any>
    ): List<String> {
        val suggestions = mutableListOf<String>()
        
        try {
            // 权限相关建议
            val hasOverlayPermission = permissionInfo["overlayPermission"] as? Boolean ?: false
            if (!hasOverlayPermission) {
                suggestions.add("需要授予悬浮窗权限以支持遮罩功能")
            }
            
            // 应用节点相关建议
            val foundAppNodes = appNodeInfo["foundAppNodes"] as? Int ?: 0
            if (foundAppNodes == 0) {
                suggestions.add("未找到应用节点，可能需要检查应用名称匹配")
            }
            
            // 包名相关建议
            when {
                packageName.contains("settings", ignoreCase = true) -> {
                    suggestions.add("当前在系统设置页面，可以尝试权限自动化操作")
                }
                packageName.contains("systemui", ignoreCase = true) -> {
                    suggestions.add("当前在系统UI界面，需要谨慎操作")
                }
                packageName == "unknown" -> {
                    suggestions.add("无法识别当前应用包名，可能需要等待界面加载完成")
                }
            }
            
            // 通用建议
            suggestions.add("如果自动操作失败，可以尝试手动操作")
            suggestions.add("建议在操作前检查屏幕元素是否完全加载")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 生成故障排查建议失败", e)
            suggestions.add("生成建议时出现异常，请检查系统状态")
        }
        
        return suggestions
    }
    
    // 私有辅助方法
    
    /**
     * 递归分析节点
     */
    private fun analyzeNodeRecursively(
        node: AccessibilityNodeInfo,
        allElements: MutableList<UIElement>,
        clickableElements: MutableList<UIElement>,
        inputElements: MutableList<UIElement>,
        depth: Int
    ) {
        if (depth > maxNodeDepth) return
        
        try {
            val rect = Rect()
            node.getBoundsInScreen(rect)
            
            val element = UIElement(
                className = node.className?.toString() ?: "",
                text = node.text?.toString() ?: "",
                contentDescription = node.contentDescription?.toString() ?: "",
                bounds = rect,
                isClickable = node.isClickable,
                isEditable = node.isEditable,
                isEnabled = node.isEnabled,
                isVisible = node.isVisibleToUser,
                depth = depth
            )
            
            allElements.add(element)
            
            if (node.isClickable) {
                clickableElements.add(element)
            }
            
            if (node.isEditable) {
                inputElements.add(element)
            }
            
            // 递归处理子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    analyzeNodeRecursively(it, allElements, clickableElements, inputElements, depth + 1)
                    it.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析节点失败", e)
        }
    }
    
    /**
     * 调试用节点分析
     */
    private fun analyzeNodeForDebug(
        node: AccessibilityNodeInfo,
        allClickable: MutableList<ClickableElementInfo>,
        confirmCandidates: MutableList<ClickableElementInfo>,
        keyboardKeys: MutableList<ClickableElementInfo>,
        depth: Int
    ) {
        if (depth > 20) return
        
        try {
            if (node.isClickable) {
                val text = node.text?.toString()?.trim() ?: ""
                val desc = node.contentDescription?.toString()?.trim() ?: ""
                val className = node.className?.toString() ?: ""
                
                val rect = Rect()
                node.getBoundsInScreen(rect)
                
                val elementInfo = ClickableElementInfo(
                    text = text,
                    description = desc,
                    className = className,
                    centerX = rect.centerX(),
                    centerY = rect.centerY(),
                    width = rect.width(),
                    height = rect.height()
                )
                
                allClickable.add(elementInfo)
                
                // 判断是否为键盘按键
                if (isKeyboardKey(text, desc)) {
                    keyboardKeys.add(elementInfo)
                } else {
                    // 判断是否为确认按钮候选
                    val confirmTexts = arrayOf(
                        "确认", "确定", "完成", "提交", "登录", "解锁", "继续", "下一步", "进入",
                        "ok", "done", "confirm", "submit", "enter", "go", "next", "continue", "unlock"
                    )
                    val isConfirmCandidate = confirmTexts.any { confirmText ->
                        text.contains(confirmText, ignoreCase = true) || 
                        desc.contains(confirmText, ignoreCase = true)
                    }
                    
                    if (isConfirmCandidate) {
                        confirmCandidates.add(elementInfo)
                    }
                }
            }
            
            // 递归处理子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    analyzeNodeForDebug(it, allClickable, confirmCandidates, keyboardKeys, depth + 1)
                    it.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 调试分析节点失败", e)
        }
    }
    
    /**
     * 检查是否为键盘按键
     */
    private fun isKeyboardKey(text: String, description: String): Boolean {
        val normalizedText = text.lowercase().trim()
        val normalizedDesc = description.lowercase().trim()
        
        // 单个字符检查
        if (normalizedText.length == 1) {
            val char = normalizedText[0]
            if (char.isLetterOrDigit() || char in ",.?!@#$%^&*()_+-=[]{}|;':\"<>/~`") {
                return true
            }
        }
        
        // 键盘按键关键词
        val keyboardKeywords = setOf(
            "key", "键", "keyboard", "按键", "input", "输入",
            "space", "spacebar", "空格", "backspace", "删除",
            "shift", "ctrl", "alt", "tab", "caps", "num"
        )
        
        return keyboardKeywords.any { keyword ->
            normalizedText.contains(keyword) || normalizedDesc.contains(keyword)
        }
    }
    
    /**
     * 分析权限状态
     */
    private fun analyzePermissionStatus(): Map<String, Any> {
        return try {
            val overlayPermission = android.provider.Settings.canDrawOverlays(context)
            
            mapOf(
                "overlayPermission" to overlayPermission,
                "timestamp" to System.currentTimeMillis()
            )
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析权限状态失败", e)
            mapOf("error" to (e.message ?: "未知错误"))
        }
    }
    
    /**
     * 分析应用节点
     */
    private fun analyzeAppNodes(rootNode: AccessibilityNodeInfo): Map<String, Any> {
        return try {
            val appNames = listOf("Remote Control", "Android Remote Control", "RemoteControl", "远程控制")
            var foundAppNodes = 0
            
            for (appName in appNames) {
                val appNode = findNodeByText(rootNode, appName)
                if (appNode != null) {
                    foundAppNodes++
                    appNode.recycle()
                }
            }
            
            mapOf(
                "foundAppNodes" to foundAppNodes,
                "searchedNames" to appNames
            )
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析应用节点失败", e)
            mapOf("error" to (e.message ?: "未知错误"))
        }
    }
    
    /**
     * 分析可点击元素
     */
    private fun analyzeClickableElements(rootNode: AccessibilityNodeInfo): Map<String, Any> {
        return try {
            val clickableElements = mutableListOf<AccessibilityNodeInfo>()
            collectClickableElements(rootNode, clickableElements)
            
            val result = mapOf(
                "totalClickable" to clickableElements.size,
                "hasClickableElements" to clickableElements.isNotEmpty()
            )
            
            clickableElements.forEach { it.recycle() }
            result
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析可点击元素失败", e)
            mapOf("error" to (e.message ?: "未知错误"))
        }
    }
    
    /**
     * 分析开关控件
     */
    private fun analyzeSwitchControls(rootNode: AccessibilityNodeInfo): Map<String, Any> {
        return try {
            val switchTypes = listOf(
                "android.widget.Switch",
                "android.widget.ToggleButton", 
                "androidx.appcompat.widget.SwitchCompat"
            )
            
            var totalSwitches = 0
            for (switchType in switchTypes) {
                val switches = findNodesByViewType(rootNode, switchType)
                totalSwitches += switches.size
                switches.forEach { it.recycle() }
            }
            
            mapOf(
                "totalSwitches" to totalSwitches,
                "searchedTypes" to switchTypes
            )
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析开关控件失败", e)
            mapOf("error" to (e.message ?: "未知错误"))
        }
    }
    
    /**
     * 分析文本元素
     */
    private fun analyzeTextElements(rootNode: AccessibilityNodeInfo): Map<String, Any> {
        return try {
            val textElements = mutableListOf<String>()
            collectTextElements(rootNode, textElements)
            
            mapOf(
                "totalTextElements" to textElements.size,
                "hasText" to textElements.isNotEmpty(),
                "sampleTexts" to textElements.take(10)
            )
        } catch (e: Exception) {
            Log.e(TAG, "❌ 分析文本元素失败", e)
            mapOf("error" to (e.message ?: "未知错误"))
        }
    }
    
    /**
     * 分析性能
     */
    private fun analyzePerformance(): Map<String, Any> {
        return mapOf(
            "totalElementsAnalyzed" to totalElementsAnalyzed,
            "totalDebugReports" to totalDebugReports,
            "debugModeEnabled" to isDebugModeEnabled,
            "maxNodeDepth" to maxNodeDepth,
            "maxElementsToAnalyze" to maxElementsToAnalyze
        )
    }
    
    /**
     * 获取真实屏幕尺寸
     */
    private fun getRealScreenSize(): Pair<Int, Int> {
        return try {
            val metrics = context.resources.displayMetrics
            Pair(metrics.widthPixels, metrics.heightPixels)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取屏幕尺寸失败", e)
            Pair(1080, 1920)
        }
    }
    
    /**
     * 根据文本查找节点
     */
    private fun findNodeByText(rootNode: AccessibilityNodeInfo, text: String): AccessibilityNodeInfo? {
        return try {
            if (rootNode.text?.toString()?.contains(text, ignoreCase = true) == true) {
                return rootNode
            }
            
            for (i in 0 until rootNode.childCount) {
                val child = rootNode.getChild(i)
                child?.let {
                    val result = findNodeByText(it, text)
                    if (result != null) {
                        return result
                    }
                    it.recycle()
                }
            }
            null
        } catch (e: Exception) {
            Log.e(TAG, "❌ 根据文本查找节点失败", e)
            null
        }
    }
    
    /**
     * 根据视图类型查找节点
     */
    private fun findNodesByViewType(rootNode: AccessibilityNodeInfo, viewType: String): List<AccessibilityNodeInfo> {
        val results = mutableListOf<AccessibilityNodeInfo>()
        
        try {
            if (rootNode.className?.toString() == viewType) {
                results.add(rootNode)
            }
            
            for (i in 0 until rootNode.childCount) {
                val child = rootNode.getChild(i)
                child?.let {
                    results.addAll(findNodesByViewType(it, viewType))
                    it.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 根据视图类型查找节点失败", e)
        }
        
        return results
    }
    
    /**
     * 收集可点击元素
     */
    private fun collectClickableElements(node: AccessibilityNodeInfo, results: MutableList<AccessibilityNodeInfo>) {
        try {
            if (node.isClickable) {
                results.add(node)
            }
            
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    collectClickableElements(it, results)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 收集可点击元素失败", e)
        }
    }
    
    /**
     * 收集文本元素
     */
    private fun collectTextElements(node: AccessibilityNodeInfo, results: MutableList<String>) {
        try {
            val text = node.text?.toString()
            if (!text.isNullOrEmpty()) {
                results.add(text)
            }
            
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    collectTextElements(it, results)
                    it.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 收集文本元素失败", e)
        }
    }
    
    /**
     * 计算最大深度
     */
    private fun calculateMaxDepth(node: AccessibilityNodeInfo, currentDepth: Int = 0): Int {
        var maxDepth = currentDepth
        
        try {
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    val childDepth = calculateMaxDepth(it, currentDepth + 1)
                    maxDepth = maxOf(maxDepth, childDepth)
                    it.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 计算最大深度失败", e)
        }
        
        return maxDepth
    }
    
    /**
     * 计算总节点数
     */
    private fun countTotalNodes(node: AccessibilityNodeInfo): Int {
        var count = 1
        
        try {
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    count += countTotalNodes(it)
                    it.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 计算总节点数失败", e)
        }
        
        return count
    }
    
    /**
     * 构建节点树
     */
    private fun buildNodeTree(node: AccessibilityNodeInfo, depth: Int): NodeTreeItem {
        return try {
            val item = NodeTreeItem(
                className = node.className?.toString() ?: "",
                text = node.text?.toString() ?: "",
                depth = depth,
                isClickable = node.isClickable,
                isEditable = node.isEditable,
                children = mutableListOf()
            )
            
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    item.children.add(buildNodeTree(it, depth + 1))
                    it.recycle()
                }
            }
            
            item
        } catch (e: Exception) {
            Log.e(TAG, "❌ 构建节点树失败", e)
            NodeTreeItem("error", "构建失败", depth, false, false, mutableListOf())
        }
    }
    
    /**
     * 递归打印节点
     */
    private fun printNodeRecursively(node: AccessibilityNodeInfo, depth: Int) {
        try {
            val indent = "  ".repeat(depth)
            val className = node.className?.toString() ?: "unknown"
            val text = node.text?.toString() ?: ""
            val desc = node.contentDescription?.toString() ?: ""
            
            Log.i(TAG, "${indent}🌿 $className | 文本:'$text' | 描述:'$desc' | 可点击:${node.isClickable}")
            
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                child?.let {
                    printNodeRecursively(it, depth + 1)
                    it.recycle()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 打印节点失败", e)
        }
    }
    
    /**
     * 记录调试日志
     */
    private fun recordDebugLog(message: String, data: Map<String, Any>? = null) {
        logRecorder?.invoke("DEBUG_ANALYSIS", message, data ?: emptyMap())
    }
    
    /**
     * 获取调试统计信息
     */
    fun getDebugStatistics(): Map<String, Any> {
        return mapOf(
            "debugModeEnabled" to isDebugModeEnabled,
            "totalElementsAnalyzed" to totalElementsAnalyzed,
            "totalDebugReports" to totalDebugReports,
            "maxNodeDepth" to maxNodeDepth,
            "maxElementsToAnalyze" to maxElementsToAnalyze
        )
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            Log.d(TAG, "🧹 清理调试分析管理器资源")
            
            isDebugModeEnabled = false
            logRecorder = null
            
            Log.i(TAG, "✅ 调试分析管理器清理完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理调试分析管理器失败", e)
        }
    }
    
    // 数据类定义
    
    /**
     * UI状态快照
     */
    data class UIStateSnapshot(
        val timestamp: Long,
        val packageName: String,
        val screenWidth: Int,
        val screenHeight: Int,
        val totalElements: Int,
        val clickableElements: List<UIElement>,
        val inputElements: List<UIElement>,
        val allElements: List<UIElement>
    )
    
    /**
     * UI元素信息
     */
    data class UIElement(
        val className: String,
        val text: String,
        val contentDescription: String,
        val bounds: Rect,
        val isClickable: Boolean,
        val isEditable: Boolean,
        val isEnabled: Boolean,
        val isVisible: Boolean,
        val depth: Int
    )
    
    /**
     * 可点击元素信息
     */
    data class ClickableElementInfo(
        val text: String,
        val description: String,
        val className: String,
        val centerX: Int,
        val centerY: Int,
        val width: Int,
        val height: Int
    ) {
        override fun toString(): String {
            return "文本:'$text' | 描述:'$description' | 类型:$className | 位置:($centerX,$centerY) | 大小:${width}x${height}"
        }
    }
    
    /**
     * 调试报告
     */
    data class DebugReport(
        val timestamp: Long,
        val basicInfo: Map<String, Any>,
        val permissionInfo: Map<String, Any>,
        val appNodeInfo: Map<String, Any>,
        val clickableInfo: Map<String, Any>,
        val switchInfo: Map<String, Any>,
        val textInfo: Map<String, Any>,
        val performanceInfo: Map<String, Any>,
        val troubleshootingSuggestions: List<String>
    ) {
        companion object {
            fun empty(reason: String) = DebugReport(
                timestamp = System.currentTimeMillis(),
                basicInfo = mapOf("error" to reason),
                permissionInfo = emptyMap(),
                appNodeInfo = emptyMap(),
                clickableInfo = emptyMap(),
                switchInfo = emptyMap(),
                textInfo = emptyMap(),
                performanceInfo = emptyMap(),
                troubleshootingSuggestions = listOf("无法生成调试报告: $reason")
            )
        }
    }
    
    /**
     * 节点层次结构
     */
    data class NodeHierarchy(
        val packageName: String,
        val rootClassName: String,
        val depth: Int,
        val totalNodes: Int,
        val nodeTree: NodeTreeItem
    )
    
    /**
     * 节点树项目
     */
    data class NodeTreeItem(
        val className: String,
        val text: String,
        val depth: Int,
        val isClickable: Boolean,
        val isEditable: Boolean,
        val children: MutableList<NodeTreeItem>
    )
} 