package com.hikoncont.service.modules.vivo

import android.util.Log

/**
 * Vivo权限配置数据结构
 * 参照p.java的权限操作配置类
 */
object VivoPermissionConfig {
    private const val TAG = "VivoPermissionConfig"
    
    /**
     * 权限操作结果
     */
    data class PermissionResult(
        val success: Boolean,
        val permissionType: String,
        val message: String = "",
        val details: Map<String, Any> = emptyMap()
    )
    
    /**
     * 权限请求状态
     */
    enum class PermissionStatus {
        PENDING,        // 等待中
        GRANTED,        // 已授予
        DENIED,         // 已拒绝
        FAILED,         // 失败
        TIMEOUT         // 超时
    }
    
    /**
     * 权限类型枚举
     */
    enum class PermissionType(val value: String, val displayName: String) {
        AUTO_START("auto_start", "自启动"),
        BACKGROUND_RUN("background_run", "后台运行"),
        NOTIFICATION("notification", "通知管理"),
        FLOAT_WINDOW("float_window", "悬浮窗"),
        LOCK_SCREEN_DISPLAY("lock_screen_display", "锁屏显示"),
        BACKGROUND_POPUP("background_popup", "后台弹出界面"),
        ASSOCIATED_START("associated_start", "关联启动"),
        WIFI_DISCONNECT("wifi_disconnect", "熄屏断网"),
        SLEEP_OPTIMIZATION("sleep_optimization", "睡眠优化"),
        GALLERY("gallery", "相册权限"),
        CAMERA("camera", "摄像头权限"),
        MICROPHONE("microphone", "麦克风权限"),
        SMS("sms", "短信权限")
    }
    
    /**
     * 设备信息
     */
    data class DeviceInfo(
        val model: String,
        val androidVersion: Int,
        val vivoOsVersion: String,
        val vivoBuildId: String,
        val isOriginOS: Boolean,
        val isSpecificDevice: Boolean
    )
    
    /**
     * 权限配置项
     */
    data class PermissionConfigItem(
        val type: PermissionType,
        val strategy: List<VivoPermissionStrategy.PermissionConfig>,
        val priority: Int = 0,
        val required: Boolean = true,
        val timeoutMs: Long = 30000L
    )
    
    /**
     * 运行时权限位图ID
     */
    object RuntimePermissionIDs {
        // Vivo权限ID（参照原始代码中的ID）
        const val AUTO_START_ID = 42203
        const val ASSOCIATED_START_ID = 1931
        const val BACKGROUND_POPUP_ID = 1931
        const val PERMISSION_DETAIL_ID = 42203
        
        // 运行时权限
        const val CAMERA_PERMISSION = "android.permission.CAMERA"
        const val RECORD_AUDIO_PERMISSION = "android.permission.RECORD_AUDIO"
        const val READ_EXTERNAL_STORAGE_PERMISSION = "android.permission.READ_EXTERNAL_STORAGE"
        const val WRITE_EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE"
        const val READ_SMS_PERMISSION = "android.permission.READ_SMS"
        const val SEND_SMS_PERMISSION = "android.permission.SEND_SMS"
        const val SYSTEM_ALERT_WINDOW_PERMISSION = "android.permission.SYSTEM_ALERT_WINDOW"
        const val WRITE_SETTINGS_PERMISSION = "android.permission.WRITE_SETTINGS"
    }
    
    /**
     * 页面检测配置
     */
    object PageDetectionConfig {
        val APP_INFO_KEYWORDS = listOf(
            "应用信息", "版本", "强行停止", "卸载", "存储", 
            "电量", "流量", "通知", "权限", "默认打开"
        )
        
        val PERMISSION_PAGE_KEYWORDS = listOf(
            "自启动", "关联启动", "悬浮窗", "桌面快捷方式", 
            "锁屏显示", "后台弹出界面", "使用摄像头", "录音", 
            "允许通知", "静默通知", "智能静默", "悬浮通知", "锁屏通知"
        )
        
        val DIALOG_KEYWORDS = listOf(
            "允许", "允许全部", "禁止", "拒绝", "取消", "确定", 
            "同意", "不同意", "OK", "Cancel", "Yes", "No"
        )
    }
    
    /**
     * 坐标点击配置
     */
    object CoordinateClickConfig {
        // 默认屏幕尺寸基准（1080x2186）
        const val BASE_WIDTH = 1080
        const val BASE_HEIGHT = 2186
        
        // 各种权限弹框的坐标（相对于基准屏幕）
        val ALLOW_BUTTON_COORDINATES = listOf(
            Pair(540, 1913),   // 中心偏下 (0.50, 0.875)
            Pair(486, 1913),   // 左侧偏下 (0.45, 0.875)
            Pair(594, 1913),   // 右侧偏下 (0.55, 0.875)
            Pair(378, 1924),   // 左侧更下 (0.35, 0.88)
            Pair(702, 1924),   // 右侧更下 (0.65, 0.88)
            Pair(540, 1967)    // 中心最下 (0.50, 0.90)
        )
        
        val CAMERA_PERMISSION_COORDINATES = listOf(
            Pair(504, 1755)   // 摄像头权限特定坐标
        )
        
        val GALLERY_PERMISSION_COORDINATES = listOf(
            Pair(504, 1920)   // 相册权限特定坐标
        )
        
        val MICROPHONE_PERMISSION_COORDINATES = listOf(
            Pair(504, 1755)   // 麦克风权限特定坐标
        )
        
        val SMS_PERMISSION_COORDINATES = listOf(
            Pair(504, 1755),  // 短信权限坐标（需要点击两次）
            Pair(504, 1755)
        )
    }
    
    /**
     * 行为类型常量（参照原始代码）
     */
    object ActionTypes {
        const val NAVIGATE = 0        // 导航
        const val CLICK = 27          // 点击
        const val FIND = 81          // 查找
        const val SWITCH = 1931      // 开关操作
        const val WAIT = 30564        // 等待
        const val SPECIAL_PERMISSION = 42203  // 特殊权限
        const val OPEN_APP_DETAILS = -1       // 打开应用详情页面（安全策略）
    }
    
    /**
     * ViewId模板
     */
    object ViewIdTemplates {
        const val VIVO_PERMISSION_MANAGER_BASE = "com.vivo.permissionmanager:id/"
        
        fun permissionSwitchId(permissionId: Int) = "${VIVO_PERMISSION_MANAGER_BASE}$permissionId"
        fun permissionItemId(permissionId: Int) = "${VIVO_PERMISSION_MANAGER_BASE}permission_$permissionId"
        fun switchId(permissionId: Int) = "${VIVO_PERMISSION_MANAGER_BASE}switch_$permissionId"
        fun itemId(permissionId: Int) = "${VIVO_PERMISSION_MANAGER_BASE}item_$permissionId"
    }
    
    /**
     * 设备特定配置
     */
    object DeviceSpecificConfig {
        // OriginOS 1.0设备
        val OriginOS_10_Models = listOf(
            "V2061A", "V1962A", "V2106A", "V2054A"
        )
        
        // Android 14+设备优化配置
        val Android14Plus_Priority = mapOf(
            PermissionType.AUTO_START to 1,
            PermissionType.BACKGROUND_RUN to 2,
            PermissionType.NOTIFICATION to 3
        )
        
        // 特殊开关处理顺序
        val SpecialSwitchOrder = listOf(
            PermissionType.AUTO_START,
            PermissionType.FLOAT_WINDOW,
            PermissionType.LOCK_SCREEN_DISPLAY,
            PermissionType.BACKGROUND_POPUP,
            PermissionType.ASSOCIATED_START
        )
    }
    
    /**
     * 调试配置
     */
    object DebugConfig {
        const val ENABLE_DETAILED_LOGGING = true
        const val ENABLE_PERFORMANCE_TRACKING = true
        const val ENABLE_NODE_SEARCH_STATS = true
        
        // 性能阈值（毫秒）
        const val NODE_SEARCH_TIMEOUT = 10000L
        const val CLICK_OPERATION_TIMEOUT = 3000L
        const val PAGE_LOAD_TIMEOUT = 10000L
        const val DIALOG_WAIT_TIMEOUT = 5000L
        
        // 重试配置
        const val MAX_RETRY_COUNT = 3
        const val RETRY_DELAY_MS = 1000L
        const val MAX_SCROLL_ATTEMPTS = 15
    }
    
    /**
     * 获取设备信息
     */
    fun getDeviceInfo(): DeviceInfo {
        val model = android.os.Build.MODEL ?: "unknown"
        val androidVersion = android.os.Build.VERSION.SDK_INT
        val vivoOsVersion = VivoPermissionStrategy.getVivoOsVersion()
        val vivoBuildId = VivoPermissionStrategy.getVivoBuildId()
        
        val isOriginOS = VivoPermissionStrategy.isOriginOS10() || VivoPermissionStrategy.isOriginOS4()
        val isSpecificDevice = VivoPermissionStrategy.isSpecificVivoDevice(model)
        
        return DeviceInfo(
            model = model,
            androidVersion = androidVersion,
            vivoOsVersion = vivoOsVersion,
            vivoBuildId = vivoBuildId,
            isOriginOS = isOriginOS,
            isSpecificDevice = isSpecificDevice
        )
    }
    
    /**
     * 根据设备信息获取权限配置
     */
    fun getPermissionConfigForDevice(): List<PermissionConfigItem> {
        val deviceInfo = getDeviceInfo()
        
        return when {
            // OriginOS 1.0设备
            VivoPermissionStrategy.isOriginOS10() -> {
                Log.d(TAG, "🔧 [权限配置] OriginOS 1.0设备配置")
                createOriginOS10PermissionConfig()
            }
            
            // Android 14+设备
            deviceInfo.androidVersion >= 34 -> {
                Log.d(TAG, "🔧 [权限配置] Android 14+设备配置")
                createAndroid14PlusPermissionConfig()
            }
            
            // 其他设备
            else -> {
                Log.d(TAG, "🔧 [权限配置] 通用设备配置")
                createDefaultPermissionConfig()
            }
        }
    }
    
    /**
     * OriginOS 1.0权限配置
     */
    private fun createOriginOS10PermissionConfig(): List<PermissionConfigItem> {
        return listOf(
            PermissionConfigItem(
                type = PermissionType.AUTO_START,
                strategy = VivoPermissionStrategy.createAutoStartStrategy().filter { 
                    it.actionType in listOf(ActionTypes.NAVIGATE, ActionTypes.WAIT)
                }
            ),
            PermissionConfigItem(
                type = PermissionType.NOTIFICATION,
                strategy = VivoPermissionStrategy.createNotificationStrategy()
            )
        )
    }
    
    /**
     * Android 14+权限配置
     */
    private fun createAndroid14PlusPermissionConfig(): List<PermissionConfigItem> {
        return listOf(
            PermissionConfigItem(
                type = PermissionType.BACKGROUND_RUN,
                strategy = VivoPermissionStrategy.createBackgroundRunStrategy(),
                priority = 1,
                timeoutMs = 45000L
            ),
            PermissionConfigItem(
                type = PermissionType.AUTO_START,
                strategy = VivoPermissionStrategy.createAutoStartStrategy(),
                priority = 2,
                timeoutMs = 45000L
            ),
            PermissionConfigItem(
                type = PermissionType.NOTIFICATION,
                strategy = VivoPermissionStrategy.createNotificationStrategy(),
                priority = 3,
                timeoutMs = 30000L
            )
        )
    }
    
    /**
     * 默认权限配置
     */
    private fun createDefaultPermissionConfig(): List<PermissionConfigItem> {
        return listOf(
            PermissionConfigItem(
                type = PermissionType.AUTO_START,
                strategy = VivoPermissionStrategy.createAutoStartStrategy(),
                priority = 1
            ),
            PermissionConfigItem(
                type = PermissionType.BACKGROUND_RUN,
                strategy = VivoPermissionStrategy.createBackgroundRunStrategy(),
                priority = 2
            ),
            PermissionConfigItem(
                type = PermissionType.NOTIFICATION,
                strategy = VivoPermissionStrategy.createNotificationStrategy(),
                priority = 3
            )
        )
    }

    
    /**
     * 检查权限配置是否有效
     */
    fun validatePermissionConfig(config: PermissionConfigItem): Boolean {
        return try {
            config.strategy.isNotEmpty() && config.timeoutMs > 0
        } catch (e: Exception) {
            Log.e(TAG, "❌ [权限配置验证] 配置验证失败", e)
            false
        }
    }
}
