package com.hikoncont.service.modules.vivo

import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.service.AccessibilityRemoteService

/**
 * Vivo权限状态检测监控
 * 参照n.java的权限状态检测逻辑
 */
object VivoPermissionMonitor {
    private const val TAG = "VivoPermissionMonitor"
    
    /**
     * 权限监控配置
     */
    data class PermissionMonitorConfig(
        val permissionType: String,
        val keywords: List<String> = emptyList(),
        val timeoutMs: Long = 10000L,
        val checkIntervalMs: Long = 500L
    )
    
    /**
     * 检查当前是否在应用信息页面
     * 参照n.java的页面检测逻辑
     */
    fun isAppInfoPage(service: AccessibilityRemoteService): Boolean {
        val root = service.rootInActiveWindow ?: return false
        val texts = collectAllTexts(root)
        
        val appInfoKeywords = listOf(
            "应用信息", "版本", "强行停止", "卸载", "存储", 
            "电量", "流量", "通知", "权限", "默认打开"
        )
        val matchCount = appInfoKeywords.count { keyword -> 
            texts.any { it.contains(keyword, true) }
        }
        
        Log.d(TAG, "🔍 应用信息页面检测: 匹配关键词 $matchCount/${appInfoKeywords.size}")
        Log.d(TAG, "🔍 页面文本内容: ${texts.take(10).joinToString(", ")}") // 显示前10个文本
        
        // 降低阈值，只要有2个关键词匹配就认为是应用信息页面
        return matchCount >= 2
    }
    
    /**
     * 检查当前是否在权限页面
     * 参照n.java的权限页面检测逻辑
     */
    fun isPermissionPage(service: AccessibilityRemoteService): Boolean {
        val root = service.rootInActiveWindow ?: return false
        val texts = collectAllTexts(root)
        
        // 扩展权限关键词，包含更多Vivo系统特有的权限名称
        val permissionKeywords = listOf(
            "自启动", "关联启动", "悬浮窗", "桌面快捷方式", 
            "锁屏显示", "后台弹出界面", "使用摄像头", "录音", 
            "允许通知", "静默通知", "智能静默", "悬浮通知", "锁屏通知",
            "后台运行", "电池优化", "省电管理", "应用权限", "权限管理",
            "应用管理", "相机", "麦克风", "位置", "存储", "联系人", "通话记录",
            "传感器", "电话", "短信", "相册", "媒体", "日历", "文件"
        )
        
        val matchCount = permissionKeywords.count { keyword -> 
            texts.any { it.contains(keyword, true) }
        }
        
        // 检查是否包含"权限"相关标题或描述文本
        val hasPermissionContext = texts.any { text ->
            text.contains("权限", true) || text.contains("Permission", true)
        }
        
        // 检查是否包含"设置"或"管理"相关文本
        val hasManagementContext = texts.any { text ->
            text.contains("设置", true) || text.contains("管理", true) || 
            text.contains("Manager", true) || text.contains("Setting", true)
        }
        
        Log.d(TAG, "🔍 权限页面检测: 匹配关键词 $matchCount/${permissionKeywords.size}")
        Log.d(TAG, "🔍 包含权限上下文: $hasPermissionContext")
        Log.d(TAG, "🔍 包含管理上下文: $hasManagementContext")
        Log.d(TAG, "🔍 页面文本内容: ${texts.take(15).joinToString(", ")}")
        
        // 更严格的检测：权限关键词数量 + 上下文验证
        val hasEnoughKeywords = matchCount >= 1
        val hasRelevantContext = hasPermissionContext || hasManagementContext
        
        val result = hasEnoughKeywords && hasRelevantContext
        Log.d(TAG, "✅ 权限页面最终检测结果: $result")
        return result
    }
    
    /**
     * 检查当前是否在Vivo权限管理器页面
     */
    fun isVivoPermissionManagerPage(service: AccessibilityRemoteService): Boolean {
        val root = service.rootInActiveWindow ?: return false
        val packageName = root.packageName?.toString() ?: ""
        
        val isVivoPermissionManager = packageName.contains("permissionmanager", true) &&
                                     packageName.contains("vivo", true)
        
        Log.d(TAG, "🔍 Vivo权限管理器页面检测: $isVivoPermissionManager, 包名: $packageName")
        return isVivoPermissionManager
    }
    
    /**
     * 监控权限获取进度
     * 参照n.java的进度监控逻辑
     */
    suspend fun monitorPermissionProgress(
        service: AccessibilityRemoteService,
        config: PermissionMonitorConfig
    ): Boolean {
        return try {
            Log.d(TAG, "🔍 [权限监控] 开始监控权限: ${config.permissionType}")
            
            val startTime = System.currentTimeMillis()
            
            while (System.currentTimeMillis() - startTime < config.timeoutMs) {
                val root = service.rootInActiveWindow ?: return false
                
                // 检查权限页面状态
                val isPermissionPage = isPermissionPage(service)
                if (!isPermissionPage) {
                    Log.d(TAG, "🔍 [权限监控] 不在权限页面，等待中...")
                    kotlinx.coroutines.delay(config.checkIntervalMs)
                    continue
                }
                
                // 检查关键字匹配
                val texts = collectAllTexts(root)
                val keywordMatched = config.keywords.any { keyword ->
                    texts.any { it.contains(keyword, true) }
                }
                
                if (keywordMatched) {
                    Log.d(TAG, "✅ [权限监控] 发现目标关键字: ${config.permissionType}")
                    return true
                }
                
                Log.d(TAG, "🔍 [权限监控] 等待关键字出现，文本内容: ${texts.take(5).joinToString(", ")}")
                kotlinx.coroutines.delay(config.checkIntervalMs)
            }
            
            Log.w(TAG, "⚠️ [权限监控] 监控超时: ${config.permissionType}")
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限监控] 监控权限获取异常", e)
            false
        }
    }
    
    /**
     * 检查权限获取异常
     * 参照n.java的异常检测逻辑
     */
    fun detectPermissionException(service: AccessibilityRemoteService): Boolean {
        return try {
            val root = service.rootInActiveWindow ?: return false
            val texts = collectAllTexts(root)
            
            val exceptionKeywords = listOf(
                "错误", "失败", "无法", "拒绝", "禁止", 
                "权限被拒", "访问被拒", "操作失败"
            )
            
            val hasException = exceptionKeywords.any { keyword ->
                texts.any { it.contains(keyword, true) }
            }
            
            if (hasException) {
                Log.w(TAG, "⚠️ [权限异常检测] 发现异常关键字")
                Log.w(TAG, "⚠️ [权限异常检测] 页面文本: ${texts.joinToString(", ")}")
                return true
            }
            
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限异常检测] 检测异常", e)
            false
        }
    }
    
    /**
     * 等待权限页面加载完成
     */
    suspend fun waitForPermissionPageLoad(
        service: AccessibilityRemoteService,
        timeoutMs: Long = 5000L
    ): Boolean {
        val startTime = System.currentTimeMillis()
        
        while (System.currentTimeMillis() - startTime < timeoutMs) {
            if (isPermissionPage(service)) {
                Log.d(TAG, "✅ [页面等待] 权限页面加载完成")
                return true
            }
            
            kotlinx.coroutines.delay(500L)
        }
        
        Log.w(TAG, "⚠️ [页面等待] 权限页面加载超时")
        return false
    }
    
    /**
     * 等待对话框出现
     */
    suspend fun waitForDialog(
        service: AccessibilityRemoteService,
        dialogKeywords: List<String>,
        timeoutMs: Long = 3000L
    ): Boolean {
        val startTime = System.currentTimeMillis()
        
        while (System.currentTimeMillis() - startTime < timeoutMs) {
            val root = service.rootInActiveWindow ?: continue
            val texts = collectAllTexts(root)
            
            val dialogFound = dialogKeywords.any { keyword ->
                texts.any { it.contains(keyword, true) }
            }
            
            if (dialogFound) {
                Log.d(TAG, "✅ [对话框等待] 发现对话框")
                return true
            }
            
            kotlinx.coroutines.delay(200L)
        }
        
        Log.w(TAG, "⚠️ [对话框等待] 对话框等待超时")
        return false
    }
    
    /**
     * 收集所有文本内容
     */
    fun collectAllTexts(node: AccessibilityNodeInfo): List<String> {
        val texts = mutableListOf<String>()
        
        try {
            // 添加节点文本
            node.text?.toString()?.let { texts.add(it) }
            node.contentDescription?.toString()?.let { texts.add(it) }
            
            // 递归收集子节点文本
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    texts.addAll(collectAllTexts(child))
                    child.recycle()
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 收集文本失败", e)
        }
        
        return texts.filter { it.isNotBlank() }
    }
}

/**
 * Vivo开关状态监控
 * 参照n.java的开关状态检测逻辑
 */
object VivoSwitchMonitor {
    private const val TAG = "VivoSwitchMonitor"
    
    /**
     * 检查开关状态（优化版：提高准确性）
     * 参照n.java的状态检测逻辑
     */
    fun checkSwitchState(switchNode: AccessibilityNodeInfo): Boolean {
        return try {
            // 方法1: 检查isChecked属性（最可靠）
            val isChecked = switchNode.isChecked
            
            // 方法2: 检查stateDescription (Android 12+ 常用于无障碍状态播报)
            val stateDesc = switchNode.stateDescription?.toString() ?: ""
            val isOnByStateDesc = stateDesc.contains("开", true) ||
                                 stateDesc.contains("已开启", true) ||
                                 stateDesc.contains("on", true) ||
                                 stateDesc.contains("启用", true)
            
            // 方法3: 检查contentDescription
            val contentDesc = switchNode.contentDescription?.toString() ?: ""
            val isOnByDesc = contentDesc.contains("开", true) || 
                             contentDesc.contains("已开启", true) ||
                             contentDesc.contains("on", true) ||
                             contentDesc.contains("允许", true) ||
                             contentDesc.contains("启用", true)
            
            // 方法4: 检查文本内容
            val text = switchNode.text?.toString() ?: ""
            val isOnByText = text.contains("开", true) || 
                             text.contains("已开启", true) ||
                             text.contains("on", true) ||
                             text.contains("允许", true) ||
                             text.contains("启用", true)
            
            // 方法5: 部分控件会使用selected表征
            val isSelected = switchNode.isSelected
            
            // 方法6: 检查className（某些开关控件的类名可能包含状态信息）
            val className = switchNode.className?.toString() ?: ""
            val isOnByClassName = className.contains("checked", true) ||
                                 className.contains("selected", true)
            
            // 综合判断（优化权重）
            val isOn = isChecked || isOnByStateDesc || isOnByDesc || isOnByText || isSelected || isOnByClassName
            
            // 详细日志
            Log.d(TAG, "🔍 开关状态检查详情:")
            Log.d(TAG, "   - checked: $isChecked")
            Log.d(TAG, "   - stateDesc: '$stateDesc' -> $isOnByStateDesc")
            Log.d(TAG, "   - contentDesc: '$contentDesc' -> $isOnByDesc")
            Log.d(TAG, "   - text: '$text' -> $isOnByText")
            Log.d(TAG, "   - selected: $isSelected")
            Log.d(TAG, "   - className: '$className' -> $isOnByClassName")
            Log.d(TAG, "   - 最终结果: $isOn")
            
            isOn
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 开关状态检查失败", e)
            false
        }
    }
    
    /**
     * 检查开关文本（用于识别开关类型）
     */
    fun getSwitchText(node: AccessibilityNodeInfo): String? {
        return try {
            node.text?.toString() ?: node.contentDescription?.toString()
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 获取开关文本失败", e)
            null
        }
    }
    
    /**
     * 检查开关类型
     */
    fun getSwitchType(node: AccessibilityNodeInfo): String? {
        val className = node.className?.toString() ?: ""
        val text = getSwitchText(node) ?: ""
        
        return when {
            className.contains("Switch", true) -> "Switch"
            className.contains("Toggle", true) -> "Toggle"
            className.contains("CheckBox", true) -> "CheckBox"
            className.contains("CompoundButton", true) -> "CompoundButton"
            node.isCheckable && node.isClickable -> "CustomSwitch"
            text.contains("开启", true) || text.contains("关闭", true) -> "TextSwitch"
            else -> "Unknown"
        }
    }
}
