package com.hikoncont.service.modules

import android.content.Context
import android.content.SharedPreferences
import android.util.Log

/**
 * 配置管理模块
 * 负责处理设备配置、坐标配置、键盘布局、适配参数、预设数据等
 */
class ConfigManager(
    private val context: Context
) {
    companion object {
        private const val TAG = "ConfigManager"
        private const val PREFS_CONFIRM_BUTTON = "confirm_button_learning"
        private const val PREFS_DEVICE_CONFIG = "device_config"
        private const val PREFS_KEYBOARD_LAYOUT = "keyboard_layout"
    }

    private val confirmButtonPrefs: SharedPreferences = 
        context.getSharedPreferences(PREFS_CONFIRM_BUTTON, Context.MODE_PRIVATE)
    private val deviceConfigPrefs: SharedPreferences = 
        context.getSharedPreferences(PREFS_DEVICE_CONFIG, Context.MODE_PRIVATE)
    private val keyboardLayoutPrefs: SharedPreferences = 
        context.getSharedPreferences(PREFS_KEYBOARD_LAYOUT, Context.MODE_PRIVATE)

    /**
     * 获取屏幕配置信息
     */
    fun getScreenConfig(): ScreenConfig {
        val displayMetrics = context.resources.displayMetrics
        return ScreenConfig(
            width = displayMetrics.widthPixels,
            height = displayMetrics.heightPixels,
            density = displayMetrics.density,
            densityDpi = displayMetrics.densityDpi
        )
    }

    /**
     * 获取设备特征标识
     */
    fun getDeviceKey(): String {
        val config = getScreenConfig()
        return "${config.width}x${config.height}_${config.density}"
    }

    /**
     * 获取学习到的确认按钮坐标
     */
    fun getLearnedConfirmButtonCoords(): Pair<Float, Float>? {
        return try {
            val screenKey = getScreenKey()
            val learnedX = confirmButtonPrefs.getFloat("learned_x_$screenKey", -1f)
            val learnedY = confirmButtonPrefs.getFloat("learned_y_$screenKey", -1f)
            
            if (learnedX > 0 && learnedY > 0) {
                val learnCount = confirmButtonPrefs.getInt("learn_count_$screenKey", 0)
                Log.i(TAG, "🧠 获取学习坐标: ($learnedX, $learnedY), 学习次数: $learnCount")
                
                if (learnCount > 0) {
                    return Pair(learnedX, learnedY)
                } else {
                    Log.i(TAG, "🧠 学习次数为0，忽略学习坐标")
                }
            }
            
            null
        } catch (e: Exception) {
            Log.e(TAG, "获取学习坐标失败", e)
            null
        }
    }

    /**
     * 记录确认按钮坐标（支持不同来源和权重）
     */
    fun recordConfirmButtonCoords(x: Float, y: Float, source: String, confidence: Float) {
        try {
            val screenKey = getScreenKey()
            val currentCount = confirmButtonPrefs.getInt("learn_count_$screenKey", 0)
            val newCount = currentCount + 1
            
            // 使用加权平均来更新学习坐标，根据来源调整权重
            val currentX = confirmButtonPrefs.getFloat("learned_x_$screenKey", x)
            val currentY = confirmButtonPrefs.getFloat("learned_y_$screenKey", y)
            
            // 根据来源和置信度调整权重
            val baseWeight = when (source) {
                "manual" -> 0.4f        // 手动点击权重最高
                "accessibility" -> 0.25f // 无障碍检测权重较低
                "learned" -> 0.2f       // 学习坐标成功权重最低（避免自我强化）
                else -> 0.3f
            }
            val weight = baseWeight * confidence // 应用置信度
            
            val newX = if (currentCount == 0) x else currentX * (1 - weight) + x * weight
            val newY = if (currentCount == 0) y else currentY * (1 - weight) + y * weight
            
            confirmButtonPrefs.edit()
                .putFloat("learned_x_$screenKey", newX)
                .putFloat("learned_y_$screenKey", newY)
                .putInt("learn_count_$screenKey", newCount)
                .putLong("last_learn_time_$screenKey", System.currentTimeMillis())
                .apply()
            
            Log.i(TAG, "🧠 记录确认按钮坐标: ($newX, $newY), 来源=$source, 置信度=$confidence, 权重=$weight, 次数=$newCount")
            
        } catch (e: Exception) {
            Log.e(TAG, "记录确认按钮坐标失败", e)
        }
    }

   
    /**
     * 生成自适应数字键盘布局方案
     */
    fun generateAdaptiveKeypadLayouts(): List<Pair<String, Map<String, Pair<Float, Float>>>> {
        val config = getScreenConfig()
        val layouts = mutableListOf<Pair<String, Map<String, Pair<Float, Float>>>>()
        
        // 计算屏幕特征
        val aspectRatio = config.height.toFloat() / config.width.toFloat()
        val isLongScreen = aspectRatio > 2.0f  // 长屏设备（如18:9, 19:9等）
        val isWideScreen = aspectRatio < 1.8f  // 宽屏设备（如16:9等）
        
        Log.i(TAG, "🔍 屏幕特征分析: ${config.width}x${config.height}, 比例=${String.format("%.2f", aspectRatio)}, 长屏=$isLongScreen, 宽屏=$isWideScreen, 密度=${config.density}")
        
        // 方案1：基于屏幕比例的标准布局
        val standardLayout = generateStandardLayout(config, aspectRatio)
        layouts.add("标准自适应布局" to standardLayout)
        
        // 方案2：紧凑布局（适用于键盘位置较高的设备）
        val compactLayout = generateCompactLayout(config, aspectRatio)
        layouts.add("紧凑布局" to compactLayout)
        
        // 方案3：扩展布局（适用于键盘位置较低的设备）
        val extendedLayout = generateExtendedLayout(config, aspectRatio)
        layouts.add("扩展布局" to extendedLayout)
        
        // 方案4：基于密度的微调布局
        val densityAdjustedLayout = generateDensityAdjustedLayout(config)
        layouts.add("密度调整布局" to densityAdjustedLayout)
        
        // 方案5：边距优化布局（适用于不同宽度的设备）
        val marginOptimizedLayout = generateMarginOptimizedLayout(config, isWideScreen)
        layouts.add("边距优化布局" to marginOptimizedLayout)
        
        return layouts
    }

    /**
     * 检查是否为键盘按键
     */
    fun isKeyboardKey(text: String, desc: String): Boolean {
        // 单个字符（字母、数字、符号）
        if (text.length == 1) {
            Log.d(TAG, "🚫 过滤单个字符键盘按键: '$text'")
            return true
        }
        
        // 常见键盘按键文本（包括完整单词）
        val keyboardTexts = setOf(
            // 字母键
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", 
            "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 
            "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
            // 数字键
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            // 符号键
            ".", ",", "?", "!", "'", "\"", "-", "(", ")", "@", ";", ":", "/", "&", "%", "+", "=", "*", "#",
            // 功能键
            "删除", "delete", "Delete", "DEL", "⌫", "退格", "backspace", "Backspace",
            "空格", "space", "Space", "SPACE", " ",
            "换行", "return", "Return", "RETURN", "回车",
            "切换", "shift", "Shift", "SHIFT", "⇧",
            "符号", "123", "ABC", "?123", "符", "数字", "字母"
        )
        
        if (text.lowercase() in keyboardTexts.map { it.lowercase() }) {
            Log.d(TAG, "🚫 过滤键盘按键文本: '$text'")
            return true
        }
        
        // 常见键盘按键描述，但排除锁屏确认按钮的情况
        val keyboardDescs = setOf(
            "delete", "backspace", "space", "shift", "return", "tab",
            "删除", "退格", "空格", "换行", "回车", "制表符", "切换", "符号", "数字", "字母"
        )
        
        if (desc.lowercase() in keyboardDescs.map { it.lowercase() }) {
            Log.d(TAG, "🚫 过滤键盘按键描述: '$desc'")
            return true
        }
        
        return false
    }

    /**
     * 保存设备配置
     */
    fun saveDeviceConfig(key: String, value: String) {
        try {
            deviceConfigPrefs.edit()
                .putString(key, value)
                .apply()
            Log.d(TAG, "💾 保存设备配置: $key = $value")
        } catch (e: Exception) {
            Log.e(TAG, "保存设备配置失败", e)
        }
    }

    /**
     * 获取设备配置
     */
    fun getDeviceConfig(key: String, defaultValue: String = ""): String {
        return try {
            deviceConfigPrefs.getString(key, defaultValue) ?: defaultValue
        } catch (e: Exception) {
            Log.e(TAG, "获取设备配置失败", e)
            defaultValue
        }
    }

    /**
     * 清除所有学习数据
     */
    fun clearAllLearningData() {
        try {
            confirmButtonPrefs.edit().clear().apply()
            keyboardLayoutPrefs.edit().clear().apply()
            Log.i(TAG, "🧠 已清除所有学习数据")
        } catch (e: Exception) {
            Log.e(TAG, "清除学习数据失败", e)
        }
    }

    // 私有辅助方法
    private fun getScreenKey(): String {
        val config = getScreenConfig()
        return "${config.width}x${config.height}"
    }

    private fun generateStandardLayout(config: ScreenConfig, aspectRatio: Float): Map<String, Pair<Float, Float>> {
        // 根据屏幕比例调整键盘起始位置
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.50f  // 超长屏，键盘位置更靠上
            aspectRatio > 2.0f -> 0.55f  // 长屏
            aspectRatio > 1.8f -> 0.60f  // 标准屏
            else -> 0.65f                // 宽屏，键盘位置更靠下
        }
        
        val rowSpacing = 0.08f  // 行间距
        
        return mapOf(
            "1" to Pair(config.width * 0.25f, config.height * keyboardStartY),
            "2" to Pair(config.width * 0.50f, config.height * keyboardStartY),
            "3" to Pair(config.width * 0.75f, config.height * keyboardStartY),
            "4" to Pair(config.width * 0.25f, config.height * (keyboardStartY + rowSpacing)),
            "5" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing)),
            "6" to Pair(config.width * 0.75f, config.height * (keyboardStartY + rowSpacing)),
            "7" to Pair(config.width * 0.25f, config.height * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(config.width * 0.75f, config.height * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing * 3))
        )
    }

    private fun generateCompactLayout(config: ScreenConfig, aspectRatio: Float): Map<String, Pair<Float, Float>> {
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.45f
            aspectRatio > 2.0f -> 0.50f
            aspectRatio > 1.8f -> 0.55f
            else -> 0.60f
        }
        
        val rowSpacing = 0.07f  // 更紧凑的行间距
        
        return mapOf(
            "1" to Pair(config.width * 0.25f, config.height * keyboardStartY),
            "2" to Pair(config.width * 0.50f, config.height * keyboardStartY),
            "3" to Pair(config.width * 0.75f, config.height * keyboardStartY),
            "4" to Pair(config.width * 0.25f, config.height * (keyboardStartY + rowSpacing)),
            "5" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing)),
            "6" to Pair(config.width * 0.75f, config.height * (keyboardStartY + rowSpacing)),
            "7" to Pair(config.width * 0.25f, config.height * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(config.width * 0.75f, config.height * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing * 3))
        )
    }

    private fun generateExtendedLayout(config: ScreenConfig, aspectRatio: Float): Map<String, Pair<Float, Float>> {
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.60f
            aspectRatio > 2.0f -> 0.65f
            aspectRatio > 1.8f -> 0.70f
            else -> 0.75f
        }
        
        val rowSpacing = 0.09f  // 更大的行间距
        
        return mapOf(
            "1" to Pair(config.width * 0.25f, config.height * keyboardStartY),
            "2" to Pair(config.width * 0.50f, config.height * keyboardStartY),
            "3" to Pair(config.width * 0.75f, config.height * keyboardStartY),
            "4" to Pair(config.width * 0.25f, config.height * (keyboardStartY + rowSpacing)),
            "5" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing)),
            "6" to Pair(config.width * 0.75f, config.height * (keyboardStartY + rowSpacing)),
            "7" to Pair(config.width * 0.25f, config.height * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(config.width * 0.75f, config.height * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(config.width * 0.50f, config.height * (keyboardStartY + rowSpacing * 3))
        )
    }

    private fun generateDensityAdjustedLayout(config: ScreenConfig): Map<String, Pair<Float, Float>> {
        // 根据屏幕密度微调位置
        val densityOffset = when {
            config.density >= 3.0f -> 0.02f   // 高密度屏幕，稍微向上调整
            config.density >= 2.0f -> 0.00f   // 标准密度
            else -> -0.02f             // 低密度屏幕，稍微向下调整
        }
        
        val baseY = 0.58f + densityOffset
        val rowSpacing = 0.08f
        
        return mapOf(
            "1" to Pair(config.width * 0.25f, config.height * baseY),
            "2" to Pair(config.width * 0.50f, config.height * baseY),
            "3" to Pair(config.width * 0.75f, config.height * baseY),
            "4" to Pair(config.width * 0.25f, config.height * (baseY + rowSpacing)),
            "5" to Pair(config.width * 0.50f, config.height * (baseY + rowSpacing)),
            "6" to Pair(config.width * 0.75f, config.height * (baseY + rowSpacing)),
            "7" to Pair(config.width * 0.25f, config.height * (baseY + rowSpacing * 2)),
            "8" to Pair(config.width * 0.50f, config.height * (baseY + rowSpacing * 2)),
            "9" to Pair(config.width * 0.75f, config.height * (baseY + rowSpacing * 2)),
            "0" to Pair(config.width * 0.50f, config.height * (baseY + rowSpacing * 3))
        )
    }

    private fun generateMarginOptimizedLayout(config: ScreenConfig, isWideScreen: Boolean): Map<String, Pair<Float, Float>> {
        // 根据屏幕宽度调整左右边距
        val leftMargin = if (isWideScreen) 0.20f else 0.25f
        val rightMargin = if (isWideScreen) 0.80f else 0.75f
        val centerX = 0.50f
        
        val baseY = 0.58f
        val rowSpacing = 0.08f
        
        return mapOf(
            "1" to Pair(config.width * leftMargin, config.height * baseY),
            "2" to Pair(config.width * centerX, config.height * baseY),
            "3" to Pair(config.width * rightMargin, config.height * baseY),
            "4" to Pair(config.width * leftMargin, config.height * (baseY + rowSpacing)),
            "5" to Pair(config.width * centerX, config.height * (baseY + rowSpacing)),
            "6" to Pair(config.width * rightMargin, config.height * (baseY + rowSpacing)),
            "7" to Pair(config.width * leftMargin, config.height * (baseY + rowSpacing * 2)),
            "8" to Pair(config.width * centerX, config.height * (baseY + rowSpacing * 2)),
            "9" to Pair(config.width * rightMargin, config.height * (baseY + rowSpacing * 2)),
            "0" to Pair(config.width * centerX, config.height * (baseY + rowSpacing * 3))
        )
    }

    /**
     * 屏幕配置数据类
     */
    data class ScreenConfig(
        val width: Int,
        val height: Int,
        val density: Float,
        val densityDpi: Int
    )
} 