package com.hikoncont.service.modules

import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.service.AccessibilityRemoteService
import kotlinx.coroutines.delay

/**
 * 权限管理模块
 * 负责处理各种权限的申请、检查和管理
 */
class PermissionManager(
    private val service: AccessibilityRemoteService,
    private val context: Context
) {
    companion object {
        private const val TAG = "PermissionManager"
    }

    /**
     * 检查悬浮窗权限页面是否有效
     */
    fun checkOverlayPermissionPageValid(): Boolean {
        return try {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.d(TAG, "无法获取根节点，可能不在权限页面")
                return false
            }

            val packageName = rootNode.packageName?.toString()?.lowercase() ?: ""
            Log.d(TAG, "当前页面包名: $packageName")

            // 检查是否在设置相关页面
            val isSettingsPage = packageName.contains("settings") ||
                                packageName.contains("systemui") ||
                                packageName.contains("permissioncontroller")

            if (!isSettingsPage) {
                Log.d(TAG, "不在设置页面，当前包名: $packageName")
                return false
            }

            // 检查页面是否包含权限相关内容
            val hasPermissionContent = hasPermissionRelatedContent(rootNode)
            
            Log.d(TAG, "权限页面检查结果: 设置页面=$isSettingsPage, 权限内容=$hasPermissionContent")
            return hasPermissionContent

        } catch (e: Exception) {
            Log.e(TAG, "检查悬浮窗权限页面失败", e)
            false
        }
    }

    /**
     * 检查是否有权限相关内容
     */
    private fun hasPermissionRelatedContent(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            var hasContent = false
            
            fun checkPermissionContent(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || hasContent) return
                
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                
                // 检查权限相关关键词
                val permissionKeywords = listOf(
                    "permission", "权限", "overlay", "悬浮", "display", "显示",
                    "allow", "允许", "enable", "启用", "grant", "授权"
                )
                
                if (permissionKeywords.any { keyword ->
                    text.contains(keyword) || desc.contains(keyword)
                }) {
                    hasContent = true
                    Log.d(TAG, "找到权限相关内容: 文本='$text', 描述='$desc'")
                    return
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        checkPermissionContent(child, depth + 1)
                        child.recycle()
                    }
                }
            }
            
            checkPermissionContent(rootNode)
            hasContent
            
        } catch (e: Exception) {
            Log.e(TAG, "检查权限内容失败", e)
            false
        }
    }

    /**
     * 确保跳转到主应用（带重试机制）
     */
    suspend fun ensureJumpToMainActivity() {
        try {
            Log.d(TAG, "开始确保跳转到主应用")
            
            var retryCount = 0
            val maxRetries = 3
            
            while (retryCount < maxRetries) {
                val currentPackage = getCurrentForegroundPackage()
                Log.d(TAG, "当前前台应用: $currentPackage, 重试次数: $retryCount")
                
                if (currentPackage == context.packageName) {
                    Log.d(TAG, "已在主应用，跳转成功")
                    return
                }
                
                // 尝试跳转到主应用
                jumpToMainActivity()
                
                // 等待跳转完成
                delay(2000)
                retryCount++
            }
            
            Log.w(TAG, "经过 $maxRetries 次重试仍未成功跳转到主应用")
            
        } catch (e: Exception) {
            Log.e(TAG, "确保跳转到主应用失败", e)
        }
    }

    /**
     * 跳转到主应用
     */
    private fun jumpToMainActivity() {
        try {
            Log.d(TAG, "尝试跳转到主应用")
            
            val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
            if (intent != null) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                context.startActivity(intent)
                Log.d(TAG, "已发送跳转到主应用的Intent")
            } else {
                Log.e(TAG, "无法获取主应用的启动Intent")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "跳转到主应用失败", e)
        }
    }

    /**
     * 获取当前前台应用包名
     */
    private fun getCurrentForegroundPackage(): String? {
        return try {
            val rootNode = service.rootInActiveWindow
            val packageName = rootNode?.packageName?.toString()
            rootNode?.recycle()
            packageName
        } catch (e: Exception) {
            Log.e(TAG, "获取前台应用包名失败", e)
            null
        }
    }

    /**
     * 检查是否在权限上下文中
     */
    fun isInPermissionContext(actionNode: AccessibilityNodeInfo, permissionTexts: List<String>): Boolean {
        return try {
            val rootNode = service.rootInActiveWindow ?: return false
            
            // 检查当前页面是否包含权限相关文本
            var hasPermissionContext = false
            
            fun checkContext(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 8 || hasPermissionContext) return
                
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                
                // 检查是否包含权限相关文本
                if (permissionTexts.any { permText ->
                    text.contains(permText.lowercase()) || desc.contains(permText.lowercase())
                }) {
                    hasPermissionContext = true
                    Log.d(TAG, "找到权限上下文: 文本='$text', 描述='$desc'")
                    return
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        checkContext(child, depth + 1)
                        child.recycle()
                    }
                }
            }
            
            checkContext(rootNode)
            hasPermissionContext
            
        } catch (e: Exception) {
            Log.e(TAG, "检查权限上下文失败", e)
            false
        }
    }

    /**
     * 尝试查找权限操作容器
     */
    fun tryFindPermissionActionContainer(
        rootNode: AccessibilityNodeInfo, 
        permissionTexts: List<String>, 
        actionTexts: List<String>
    ): Boolean {
        return try {
            var foundAction = false
            
            fun findActionContainer(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || foundAction) return
                
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                
                // 检查是否是权限相关的操作按钮
                val isPermissionRelated = permissionTexts.any { permText ->
                    text.contains(permText.lowercase()) || desc.contains(permText.lowercase())
                }
                
                val isActionButton = actionTexts.any { actionText ->
                    text.contains(actionText.lowercase()) || desc.contains(actionText.lowercase())
                }
                
                if ((isPermissionRelated || isActionButton) && node.isClickable) {
                    Log.d(TAG, "找到权限操作按钮: 文本='$text', 描述='$desc'")
                    
                    // 尝试点击
                    val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    if (success) {
                        Log.d(TAG, "成功点击权限操作按钮")
                        foundAction = true
                        return
                    }
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        findActionContainer(child, depth + 1)
                        child.recycle()
                    }
                }
            }
            
            findActionContainer(rootNode)
            foundAction
            
        } catch (e: Exception) {
            Log.e(TAG, "查找权限操作容器失败", e)
            false
        }
    }

    /**
     * 打开悬浮窗权限设置页面
     */
    fun openOverlayPermissionSettings() {
        try {
            Log.d(TAG, "尝试打开悬浮窗权限设置页面")
            
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply {
                data = Uri.parse("package:${context.packageName}")
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            
            context.startActivity(intent)
            Log.d(TAG, "已发送打开悬浮窗权限设置的Intent")
            
        } catch (e: Exception) {
            Log.e(TAG, "打开悬浮窗权限设置失败", e)
        }
    }
} 