package com.hikoncont.util

import android.content.Context
import android.content.SharedPreferences
import android.util.Base64
import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

/**
 * 配置文件加密工具类
 * 用于保护SharedPreferences中的敏感配置信息
 */
object ConfigEncryption {
    
    private const val ALGORITHM = "AES"
    private const val TRANSFORMATION = "AES/ECB/PKCS5Padding"
    private const val ENCRYPTED_PREFS_NAME = "encrypted_config"
    
    /**
     * 生成加密密钥
     */
    private fun generateKey(context: Context): SecretKeySpec {
        val packageName = context.packageName
        val keyString = packageName + "RemoteControl" + android.os.Build.MODEL
        val digest = MessageDigest.getInstance("SHA-256")
        val keyBytes = digest.digest(keyString.toByteArray())
        return SecretKeySpec(keyBytes, ALGORITHM)
    }
    
    /**
     * 加密字符串
     */
    private fun encryptString(plainText: String, key: SecretKeySpec): String {
        return try {
            val cipher = Cipher.getInstance(TRANSFORMATION)
            cipher.init(Cipher.ENCRYPT_MODE, key)
            val encryptedData = cipher.doFinal(plainText.toByteArray())
            Base64.encodeToString(encryptedData, Base64.DEFAULT)
        } catch (e: Exception) {
            // 加密失败时返回原文的Base64编码
            Base64.encodeToString(plainText.toByteArray(), Base64.DEFAULT)
        }
    }
    
    /**
     * 解密字符串
     */
    private fun decryptString(encryptedText: String, key: SecretKeySpec): String {
        return try {
            val cipher = Cipher.getInstance(TRANSFORMATION)
            cipher.init(Cipher.DECRYPT_MODE, key)
            val encryptedData = Base64.decode(encryptedText, Base64.DEFAULT)
            val decryptedData = cipher.doFinal(encryptedData)
            String(decryptedData)
        } catch (e: Exception) {
            // 解密失败时尝试Base64解码
            try {
                String(Base64.decode(encryptedText, Base64.DEFAULT))
            } catch (e2: Exception) {
                encryptedText
            }
        }
    }
    
    /**
     * 保存加密的配置
     */
    fun saveEncryptedConfig(context: Context, key: String, value: String) {
        val prefs = context.getSharedPreferences(ENCRYPTED_PREFS_NAME, Context.MODE_PRIVATE)
        val secretKey = generateKey(context)
        val encryptedValue = encryptString(value, secretKey)
        prefs.edit().putString(key, encryptedValue).apply()
    }
    
    /**
     * 读取加密的配置
     */
    fun getEncryptedConfig(context: Context, key: String, defaultValue: String = ""): String {
        val prefs = context.getSharedPreferences(ENCRYPTED_PREFS_NAME, Context.MODE_PRIVATE)
        val encryptedValue = prefs.getString(key, null) ?: return defaultValue
        val secretKey = generateKey(context)
        return decryptString(encryptedValue, secretKey)
    }
    
    /**
     * 保存服务器URL
     */
    fun saveServerUrl(context: Context, serverUrl: String) {
        saveEncryptedConfig(context, "server_url", serverUrl)
    }
    
    /**
     * 获取服务器URL
     */
    fun getServerUrl(context: Context): String {
        return getEncryptedConfig(context, "server_url", "")
    }
    
    /**
     * 获取设备ID
     */
    fun getDeviceId(context: Context): String {
        return getEncryptedConfig(context, "device_id", "")
    }
    
    /**
     * 获取认证token
     */
    fun getAuthToken(context: Context): String {
        return getEncryptedConfig(context, "auth_token", "")
    }
    
    /**
     * 清除所有加密配置
     */
    fun clearAllConfig(context: Context) {
        val prefs = context.getSharedPreferences(ENCRYPTED_PREFS_NAME, Context.MODE_PRIVATE)
        prefs.edit().clear().apply()
    }
    
    /**
     * 验证配置完整性
     */
    fun verifyConfigIntegrity(context: Context): Boolean {
        return try {
            val serverUrl = getServerUrl(context)
            val deviceId = getDeviceId(context)
            
            // 基本验证
            serverUrl.isNotEmpty() && deviceId.isNotEmpty()
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 获取配置摘要（用于完整性检查）
     */
    fun getConfigDigest(context: Context): String {
        val serverUrl = getServerUrl(context)
        val deviceId = getDeviceId(context)
        val authToken = getAuthToken(context)
        
        val configString = "$serverUrl|$deviceId|$authToken"
        val digest = MessageDigest.getInstance("SHA-256")
        val hash = digest.digest(configString.toByteArray())
        return Base64.encodeToString(hash, Base64.DEFAULT)
    }
} 