package app.closer.analytics

import android.util.Log
import java.security.MessageDigest
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Minimal retention analytics interface.
 *
 * Implementations must only handle [RetentionEvent] metadata. They must never
 * receive answer text, prompts, or decrypted content.
 */
interface RetentionAnalytics {
    fun track(event: RetentionEvent)
    fun setEnabled(enabled: Boolean)
}

/**
 * Logs retention events to Logcat at DEBUG level.
 *
 * Safe for production builds: Logcat DEBUG logs are stripped by ProGuard/R8 in release
 * builds, and only metadata (feature name, event type, category hash, couple ID hash,
 * timestamp) is emitted — never answer text or prompt content.
 */
@Singleton
class LogcatRetentionAnalytics @Inject constructor() : RetentionAnalytics {

    private val tag = "Retention"
    private var enabled = true

    override fun track(event: RetentionEvent) {
        if (!enabled) return
        Log.d(
            tag,
            buildString {
                append("feature=${event.featureName}")
                append(", event=${event.eventType}")
                event.categoryId?.let { append(", category_hash=${hashForAnalytics(it)}") }
                event.coupleIdHash?.let { append(", couple_hash=${it}") }
                append(", timestamp=${event.timestamp}")
            }
        )
    }

    override fun setEnabled(enabled: Boolean) {
        this.enabled = enabled
    }

    private fun hashForAnalytics(value: String): String {
        if (value.isBlank()) return "empty"
        return try {
            MessageDigest.getInstance("SHA-256")
                .digest(value.toByteArray(Charsets.UTF_8))
                .joinToString("", limit = 8, truncated = "") { "%02x".format(it) }
        } catch (e: Exception) {
            "hash_error"
        }
    }
}
