package com.fmdxconnector

import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

// Datenklassen hier definieren, damit sie überall verfügbar sind
enum class LogLevel {
    INFO, SUCCESS, WARNING, ERROR
}

data class LogEntry(
    val timestamp: String,
    val level: LogLevel,
    val message: String
)

/**
 * Zentraler Logger mit Ringpuffer und StateFlow.
 */
object LogCenter {

    private const val TAG = "LogCenter"
    private const val CAPACITY = 1000

    private val timeFmt = SimpleDateFormat("HH:mm:ss", Locale.getDefault())

    private val _logs = MutableStateFlow<List<LogEntry>>(emptyList())
    val logs: StateFlow<List<LogEntry>> = _logs.asStateFlow()

    @JvmOverloads
    fun log(msg: String, level: LogLevel = LogLevel.INFO, alsoAndroidLog: Boolean = true) {
        if (alsoAndroidLog) {
            when (level) {
                LogLevel.INFO    -> Log.i(TAG, msg)
                LogLevel.SUCCESS -> Log.i(TAG, "✅ $msg")
                LogLevel.WARNING -> Log.w(TAG, "⚠️ $msg")
                LogLevel.ERROR   -> Log.e(TAG, "❌ $msg")
            }
        }

        val entry = LogEntry(
            timestamp = timeFmt.format(Date()),
            level = level,
            message = msg
        )

        val newList = buildList {
            addAll(_logs.value)
            add(entry)
            val overflow = size - CAPACITY
            if (overflow > 0) subList(0, overflow).clear()
        }
        _logs.value = newList
    }

    fun info(msg: String)    = log(msg, LogLevel.INFO)
    fun success(msg: String) = log(msg, LogLevel.SUCCESS)
    fun warn(msg: String)    = log(msg, LogLevel.WARNING)
    fun error(msg: String)   = log(msg, LogLevel.ERROR)

    fun clear() { _logs.value = emptyList() }
}