package com.rosetta.messenger.ui.chats.components

import com.rosetta.messenger.BuildConfig
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

object AttachmentDownloadDebugLogger {
    private val _logs = MutableStateFlow<List<String>>(emptyList())
    val logs: StateFlow<List<String>> = _logs.asStateFlow()

    private var appContext: android.content.Context? = null
    @Volatile private var forceEnabled = false

    fun isEnabled(): Boolean = BuildConfig.DEBUG || forceEnabled

    fun setEnabled(enabled: Boolean) {
        forceEnabled = enabled
    }

    fun init(context: android.content.Context) {
        appContext = context.applicationContext
    }

    fun log(message: String) {
        if (!isEnabled()) return
        val ctx = appContext ?: return
        try {
            val ts = java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.getDefault()).format(java.util.Date())
            val line = "$ts [PhotoDL] $message"
            android.util.Log.d("PhotoDL", message)
            val dir = java.io.File(ctx.filesDir, "crash_reports")
            if (!dir.exists()) dir.mkdirs()
            java.io.File(dir, "image_logs.txt").appendText("$line\n")
        } catch (_: Exception) {}
    }

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