package com.hikoncont.util

import android.content.Context
import android.os.Build
import android.util.Log
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

/**
 * 小米设备文件操作工具类
 * 专门处理小米设备的文件写入问题，包括 mi_exception_log 错误修复
 */
object XiaomiFileUtils {
    
    private const val TAG = "XiaomiFileUtils"
    
    /**
     * 检查是否为小米设备
     */
    fun isXiaomiDevice(): Boolean {
        val brand = Build.BRAND.lowercase()
        val manufacturer = Build.MANUFACTURER.lowercase()
        return brand.contains("xiaomi") || brand.contains("redmi") || 
               brand.contains("poco") || manufacturer.contains("xiaomi")
    }
    
    /**
     * 安全写入文件，处理小米设备的特殊需求
     */
    fun safeWriteToFile(context: Context, fileName: String, content: String): Boolean {
        return try {
            if (isXiaomiDevice()) {
                Log.d(TAG, "🔧 检测到小米设备，使用特殊文件写入策略")
                writeToXiaomiDevice(context, fileName, content)
            } else {
                writeToNormalDevice(context, fileName, content)
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 文件写入失败: $fileName", e)
            false
        }
    }
    
    /**
     * 小米设备专用文件写入方法
     */
    private fun writeToXiaomiDevice(context: Context, fileName: String, content: String): Boolean {
        return try {
            // 优先使用应用内部存储
            val internalFile = File(context.filesDir, fileName)
            writeToInternalStorage(internalFile, content)
            
            // 如果内部存储成功，尝试写入外部存储（如果权限允许）
            if (hasExternalStoragePermission(context)) {
                val externalFile = File(context.getExternalFilesDir(null), fileName)
                writeToExternalStorage(externalFile, content)
            }
            
            true
        } catch (e: Exception) {
            Log.e(TAG, "❌ 小米设备文件写入失败", e)
            false
        }
    }
    
    /**
     * 普通设备文件写入方法
     */
    private fun writeToNormalDevice(context: Context, fileName: String, content: String): Boolean {
        return try {
            val file = File(context.filesDir, fileName)
            writeToInternalStorage(file, content)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 普通设备文件写入失败", e)
            false
        }
    }
    
    /**
     * 写入内部存储
     */
    private fun writeToInternalStorage(file: File, content: String): Boolean {
        return try {
            // 确保目录存在
            file.parentFile?.mkdirs()
            
            // 使用 try-with-resources 确保文件正确关闭
            FileWriter(file).use { writer ->
                writer.write(content)
                writer.flush()
            }
            
            Log.d(TAG, "✅ 内部存储写入成功: ${file.absolutePath}")
            true
        } catch (e: IOException) {
            Log.e(TAG, "❌ 内部存储写入失败: ${file.absolutePath}", e)
            false
        }
    }
    
    /**
     * 写入外部存储
     */
    private fun writeToExternalStorage(file: File, content: String): Boolean {
        return try {
            // 确保目录存在
            file.parentFile?.mkdirs()
            
            // 使用 try-with-resources 确保文件正确关闭
            FileWriter(file).use { writer ->
                writer.write(content)
                writer.flush()
            }
            
            Log.d(TAG, "✅ 外部存储写入成功: ${file.absolutePath}")
            true
        } catch (e: IOException) {
            Log.e(TAG, "❌ 外部存储写入失败: ${file.absolutePath}", e)
            false
        }
    }
    
    /**
     * 检查是否有外部存储权限
     */
    private fun hasExternalStoragePermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 使用新的存储权限模型
            try {
                android.os.Environment.isExternalStorageManager()
            } catch (e: Exception) {
                false
            }
        } else {
            // Android 10 及以下使用传统权限
            context.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == 
                android.content.pm.PackageManager.PERMISSION_GRANTED
        }
    }
    
    /**
     * 创建异常日志文件（修复 mi_exception_log 错误）
     */
    fun createExceptionLog(context: Context, exception: Throwable, additionalInfo: String = ""): Boolean {
        return try {
            val timestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
            val logContent = buildString {
                appendLine("=== 异常日志 ===")
                appendLine("时间: $timestamp")
                appendLine("设备: ${Build.BRAND} ${Build.MODEL}")
                appendLine("Android版本: ${Build.VERSION.RELEASE}")
                appendLine("SDK版本: ${Build.VERSION.SDK_INT}")
                appendLine("异常类型: ${exception.javaClass.simpleName}")
                appendLine("异常信息: ${exception.message}")
                if (additionalInfo.isNotEmpty()) {
                    appendLine("附加信息: $additionalInfo")
                }
                appendLine("堆栈跟踪:")
                exception.stackTrace.forEach { element ->
                    appendLine("  at $element")
                }
                appendLine("=== 日志结束 ===")
            }
            
            val fileName = "exception_log_${System.currentTimeMillis()}.txt"
            safeWriteToFile(context, fileName, logContent)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 创建异常日志失败", e)
            false
        }
    }
    
    /**
     * 清理旧的日志文件
     */
    fun cleanupOldLogs(context: Context, maxAgeDays: Int = 7) {
        try {
            val filesDir = context.filesDir
            val cutoffTime = System.currentTimeMillis() - (maxAgeDays * 24 * 60 * 60 * 1000L)
            
            filesDir.listFiles()?.forEach { file ->
                if (file.isFile && 
                    (file.name.startsWith("exception_log_") || file.name.startsWith("mi_exception_log")) &&
                    file.lastModified() < cutoffTime) {
                    if (file.delete()) {
                        Log.d(TAG, "🗑️ 已删除旧日志文件: ${file.name}")
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理旧日志失败", e)
        }
    }
    
    /**
     * 获取存储状态信息
     */
    fun getStorageStatus(context: Context): Map<String, Any> {
        return try {
            val internalStorage = context.filesDir
            val externalStorage = context.getExternalFilesDir(null)
            
            mapOf(
                "internalStorageAvailable" to internalStorage.canWrite(),
                "internalStoragePath" to internalStorage.absolutePath,
                "externalStorageAvailable" to (externalStorage?.canWrite() ?: false),
                "externalStoragePath" to (externalStorage?.absolutePath ?: "不可用"),
                "isXiaomiDevice" to isXiaomiDevice(),
                "hasExternalStoragePermission" to hasExternalStoragePermission(context)
            )
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取存储状态失败", e)
            emptyMap()
        }
    }
}
