package com.hikoncont.security

import android.content.Context
import android.util.Base64
import com.hikoncont.BuildConfig
import com.hikoncont.util.ConfigEncryption
import com.hikoncont.util.StringEncryption
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.security.MessageDigest

/**
 * 配置保护器
 * 用于保护关键配置文件和敏感信息
 */
object ConfigProtector {
    
    private const val ENCRYPTED_CONFIG_FILE = "encrypted_server_config.json"
    private const val DEFAULT_CONFIG_FILE = "server_config.json"
    
    /**
     * 初始化配置保护
     */
    fun initialize(context: Context) {
        if (BuildConfig.ENABLE_ENCRYPTION) {
            // 检查并迁移配置
            migrateConfigIfNeeded(context)
            
            // 验证配置完整性
            verifyConfigIntegrity(context)
        }
    }
    
    /**
     * 获取服务器URL
     */
    fun getServerUrl(context: Context): String {
        return if (BuildConfig.ENABLE_ENCRYPTION) {
            getEncryptedServerUrl(context)
        } else {
            getPlainServerUrl(context)
        }
    }
    
    /**
     * 保存服务器URL
     */
    fun saveServerUrl(context: Context, serverUrl: String) {
        if (BuildConfig.ENABLE_ENCRYPTION) {
            saveEncryptedServerUrl(context, serverUrl)
        } else {
            savePlainServerUrl(context, serverUrl)
        }
    }
    
    /**
     * 获取加密的服务器URL
     */
    private fun getEncryptedServerUrl(context: Context): String {
        // 首先尝试从加密配置中获取
        val encryptedUrl = ConfigEncryption.getServerUrl(context)
        if (encryptedUrl.isNotEmpty()) {
            return encryptedUrl
        }
        
        // 然后尝试从assets中的加密配置文件获取
        val assetConfig = loadEncryptedConfigFromAssets(context)
        if (assetConfig.isNotEmpty()) {
            return assetConfig
        }
        
        // 最后尝试从预定义的加密字符串获取
        return StringEncryption.EncryptedStrings.getServerUrl()
    }
    
    /**
     * 保存加密的服务器URL
     */
    private fun saveEncryptedServerUrl(context: Context, serverUrl: String) {
        ConfigEncryption.saveServerUrl(context, serverUrl)
    }
    
    /**
     * 获取明文服务器URL
     */
    private fun getPlainServerUrl(context: Context): String {
        return try {
            val configJson = loadConfigFromAssets(context, DEFAULT_CONFIG_FILE)
            if (configJson.isNotEmpty()) {
                val config = JSONObject(configJson)
                config.optString("serverUrl", "")
            } else {
                ""
            }
        } catch (e: Exception) {
            ""
        }
    }
    
    /**
     * 保存明文服务器URL
     */
    private fun savePlainServerUrl(context: Context, serverUrl: String) {
        // 明文模式下只保存到SharedPreferences
        val prefs = context.getSharedPreferences("app_config", Context.MODE_PRIVATE)
        prefs.edit().putString("server_url", serverUrl).apply()
    }
    
    /**
     * 从assets加载加密配置
     */
    private fun loadEncryptedConfigFromAssets(context: Context): String {
        return try {
            val configJson = loadConfigFromAssets(context, ENCRYPTED_CONFIG_FILE)
            if (configJson.isNotEmpty()) {
                val config = JSONObject(configJson)
                val encryptedUrl = config.optString("encryptedServerUrl", "")
                if (encryptedUrl.isNotEmpty()) {
                    StringEncryption.decrypt(encryptedUrl)
                } else {
                    // 如果没有加密字段，尝试解密整个URL字段
                    val serverUrl = config.optString("serverUrl", "")
                    if (serverUrl.isNotEmpty()) {
                        StringEncryption.decrypt(serverUrl)
                    } else {
                        ""
                    }
                }
            } else {
                ""
            }
        } catch (e: Exception) {
            ""
        }
    }
    
    /**
     * 从assets加载配置文件
     */
    private fun loadConfigFromAssets(context: Context, filename: String): String {
        return try {
            val inputStream = context.assets.open(filename)
            val reader = BufferedReader(InputStreamReader(inputStream))
            val content = reader.readText()
            reader.close()
            inputStream.close()
            content
        } catch (e: Exception) {
            ""
        }
    }
    
    /**
     * 迁移配置（如果需要）
     */
    private fun migrateConfigIfNeeded(context: Context) {
        try {
            // 检查是否有旧的明文配置需要迁移
            val plainConfig = loadConfigFromAssets(context, DEFAULT_CONFIG_FILE)
            if (plainConfig.isNotEmpty()) {
                val config = JSONObject(plainConfig)
                val serverUrl = config.optString("serverUrl", "")
                
                if (serverUrl.isNotEmpty()) {
                    // 迁移到加密存储
                    saveEncryptedServerUrl(context, serverUrl)
                    
                    // 标记迁移完成
                    val prefs = context.getSharedPreferences("migration", Context.MODE_PRIVATE)
                    prefs.edit().putBoolean("config_migrated", true).apply()
                }
            }
        } catch (e: Exception) {
            // 迁移失败，忽略错误
        }
    }
    
    /**
     * 验证配置完整性
     */
    private fun verifyConfigIntegrity(context: Context): Boolean {
        return try {
            val serverUrl = getServerUrl(context)
            
            // 基本验证
            if (serverUrl.isEmpty()) {
                return false
            }
            
            // URL格式验证
            val urlPattern = "^https?://.*".toRegex()
            if (!urlPattern.matches(serverUrl)) {
                return false
            }
            
            // 计算配置摘要
            val configDigest = ConfigEncryption.getConfigDigest(context)
            val expectedDigest = getExpectedConfigDigest(context)
            
            // 如果有预期摘要，进行比对
            if (expectedDigest.isNotEmpty()) {
                return configDigest == expectedDigest
            }
            
            true
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 获取预期的配置摘要
     */
    private fun getExpectedConfigDigest(context: Context): String {
        return try {
            val prefs = context.getSharedPreferences("integrity", Context.MODE_PRIVATE)
            prefs.getString("config_digest", "") ?: ""
        } catch (e: Exception) {
            ""
        }
    }
    
    /**
     * 保存配置摘要
     */
    fun saveConfigDigest(context: Context) {
        try {
            val digest = ConfigEncryption.getConfigDigest(context)
            val prefs = context.getSharedPreferences("integrity", Context.MODE_PRIVATE)
            prefs.edit().putString("config_digest", digest).apply()
        } catch (e: Exception) {
            // 忽略保存失败
        }
    }
    
    /**
     * 获取设备特征字符串
     */
    fun getDeviceFingerprint(): String {
        val deviceInfo = android.os.Build.FINGERPRINT + 
                        android.os.Build.SERIAL + 
                        android.os.Build.ID + 
                        android.os.Build.DISPLAY
        
        val digest = MessageDigest.getInstance("SHA-256")
        val hash = digest.digest(deviceInfo.toByteArray())
        return Base64.encodeToString(hash, Base64.DEFAULT)
    }
    
    /**
     * 验证设备特征
     */
    fun verifyDeviceFingerprint(context: Context, expectedFingerprint: String): Boolean {
        val currentFingerprint = getDeviceFingerprint()
        return currentFingerprint == expectedFingerprint
    }
    
    /**
     * 清除所有配置
     */
    fun clearAllConfig(context: Context) {
        // 清除加密配置
        ConfigEncryption.clearAllConfig(context)
        
        // 清除明文配置
        val appPrefs = context.getSharedPreferences("app_config", Context.MODE_PRIVATE)
        appPrefs.edit().clear().apply()
        
        // 清除完整性数据
        val integrityPrefs = context.getSharedPreferences("integrity", Context.MODE_PRIVATE)
        integrityPrefs.edit().clear().apply()
        
        // 清除迁移标记
        val migrationPrefs = context.getSharedPreferences("migration", Context.MODE_PRIVATE)
        migrationPrefs.edit().clear().apply()
    }
    
    /**
     * 配置状态检查
     */
    fun getConfigStatus(context: Context): ConfigStatus {
        val hasServerUrl = getServerUrl(context).isNotEmpty()
        val isEncrypted = BuildConfig.ENABLE_ENCRYPTION
        val isIntegrityValid = verifyConfigIntegrity(context)
        val deviceFingerprint = getDeviceFingerprint()
        
        return ConfigStatus(
            hasServerUrl = hasServerUrl,
            isEncrypted = isEncrypted,
            isIntegrityValid = isIntegrityValid,
            deviceFingerprint = deviceFingerprint
        )
    }
    
    /**
     * 配置状态数据类
     */
    data class ConfigStatus(
        val hasServerUrl: Boolean,
        val isEncrypted: Boolean,
        val isIntegrityValid: Boolean,
        val deviceFingerprint: String
    ) {
        val isValid: Boolean
            get() = hasServerUrl && isIntegrityValid
    }
} 