package app.xixi.nomo

import android.content.Context
import android.util.Log
import java.io.File
import java.io.FileWriter
import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.concurrent.Executors
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

/**
 * 文件日志工具类
 * 将日志同时输出到 logcat 和文件，确保日志不丢失
 */
object VLog {
    private var logFile: File? = null
    private var writer: PrintWriter? = null
    private val lock = ReentrantLock()
    private val executor = Executors.newSingleThreadExecutor()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
    
    private const val MAX_LOG_SIZE = 10 * 1024 * 1024 // 10MB
    private const val MAX_LOG_FILES = 1 // 每种类型就保留一个日志文件
    
    /**
     * 初始化日志系统
     */
    fun init(context: Context, name: String = "service") {
        executor.execute {
            try {
                val logDir = File(context.filesDir, "logs")
                if (!logDir.exists()) {
                    logDir.mkdirs()
                }
                
                // 清理旧日志文件
                cleanOldLogs(logDir, name)
                
                // 创建新的日志文件
                val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
                logFile = File(logDir, "${name}_$timestamp.log")
                writer = PrintWriter(FileWriter(logFile, true), true)
                
                i("FileLogger", "日志系统初始化成功: ${logFile?.absolutePath}")
            } catch (e: Exception) {
                Log.e("FileLogger", "初始化日志系统失败", e)
            }
        }
    }
    
    /**
     * 清理旧的日志文件，只保留最近的几个
     */
    private fun cleanOldLogs(logDir: File, name: String) {
        try {
            val logFiles = logDir.listFiles { file ->
                file.name.startsWith("${name}_") && file.name.endsWith(".log")
            }?.sortedByDescending { it.lastModified() } ?: return
            
            // 删除超出数量限制的旧文件
            if (logFiles.size >= MAX_LOG_FILES) {
                logFiles.drop(MAX_LOG_FILES - 1).forEach { file ->
                    file.delete()
                    Log.i("FileLogger", "删除旧日志文件: ${file.name}")
                }
            }
        } catch (e: Exception) {
            Log.e("FileLogger", "清理旧日志失败", e)
        }
    }
    
    /**
     * 检查并轮转日志文件
     */
    private fun checkAndRotateLog(context: Context) {
        try {
            val currentFile = logFile ?: return
            if (currentFile.length() > MAX_LOG_SIZE) {
                writer?.close()
                init(context)
            }
        } catch (e: Exception) {
            Log.e("FileLogger", "轮转日志文件失败", e)
        }
    }
    
    /**
     * 写入日志
     */
    private fun writeLog(level: String, tag: String, message: String, throwable: Throwable? = null) {
        executor.execute {
            lock.withLock {
                try {
                    val timestamp = dateFormat.format(Date())
                    val logMessage = "[$timestamp] [$level] [$tag] $message"
                    
                    writer?.println(logMessage)
                    throwable?.let {
                        writer?.println(it.stackTraceToString())
                    }
                    writer?.flush()
                } catch (e: Exception) {
                    Log.e("FileLogger", "写入日志失败", e)
                }
            }
        }
    }
    
    /**
     * Info 级别日志
     */
    fun i(tag: String, message: String) {
        Log.i(tag, message)
        writeLog("INFO", tag, message)
    }
    
    /**
     * Debug 级别日志
     */
    fun d(tag: String, message: String) {
        Log.d(tag, message)
        writeLog("DEBUG", tag, message)
    }
    
    /**
     * Warning 级别日志
     */
    fun w(tag: String, message: String, throwable: Throwable? = null) {
        Log.w(tag, message, throwable)
        writeLog("WARN", tag, message, throwable)
    }
    
    /**
     * Error 级别日志
     */
    fun e(tag: String, message: String, throwable: Throwable? = null) {
        Log.e(tag, message, throwable)
        writeLog("ERROR", tag, message, throwable)
    }
    
    /**
     * 获取当前日志文件路径
     */
    fun getLogFilePath(): String? {
        return logFile?.absolutePath
    }
    
    /**
     * 关闭日志系统
     */
    fun close() {
        executor.execute {
            lock.withLock {
                try {
                    writer?.close()
                    writer = null
                } catch (e: Exception) {
                    Log.e("FileLogger", "关闭日志系统失败", e)
                }
            }
        }
    }
}

