package com.system.cloudservice.util

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

object Logger {

    private const val TAG = "AiAgent"
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
    private var fileWriter: FileWriter? = null
    private var logFile: File? = null

    private val buffer = LinkedList<String>()
    private const val BUFFER_MAX = 1000
    private val bufferLock = Any()

    fun init(context: Context) {
        try {
            val dir = File(context.filesDir, "logs")
            if (!dir.exists()) dir.mkdirs()
            val today = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
            logFile = File(dir, "agent_$today.log")
            fileWriter = FileWriter(logFile, true)
        } catch (_: Exception) {}
    }

    private fun write(level: String, msg: String, t: Throwable? = null) {
        val line = "${dateFormat.format(Date())} [$level] $msg"
        synchronized(bufferLock) {
            buffer.addLast(line)
            if (t != null) buffer.addLast(t.stackTraceToString())
            while (buffer.size > BUFFER_MAX) buffer.removeFirst()
        }
        try {
            fileWriter?.apply {
                append(line + "\n")
                if (t != null) append(t.stackTraceToString() + "\n")
                flush()
            }
            logFile?.let {
                if (it.length() > 10 * 1024 * 1024) rotate()
            }
        } catch (_: Exception) {}
    }

    private fun rotate() {
        try {
            fileWriter?.close()
            logFile?.let { File("${it.absolutePath}.old").also { o -> it.renameTo(o) } }
        } catch (_: Exception) {}
    }

    fun d(msg: String, t: Throwable? = null) { Log.d(TAG, msg, t); write("D", msg, t) }
    fun i(msg: String, t: Throwable? = null) { Log.i(TAG, msg, t); write("I", msg, t) }
    fun w(msg: String, t: Throwable? = null) { Log.w(TAG, msg, t); write("W", msg, t) }
    fun e(msg: String, t: Throwable? = null) { Log.e(TAG, msg, t); write("E", msg, t) }

    fun getRecentLogs(maxLines: Int = 200): List<String> {
        synchronized(bufferLock) {
            val start = if (buffer.size > maxLines) buffer.size - maxLines else 0
            return buffer.subList(start, buffer.size).toList()
        }
    }

    fun clearBuffer() {
        synchronized(bufferLock) { buffer.clear() }
    }
}
