package com.onthelevel.core.sensors

import kotlin.math.exp

/**
 * Time-constant-based exponential moving average — the "stable calibrated measurement"
 * filter (BRIEF.md value 2 of 3). Using a time constant instead of a fixed alpha keeps
 * smoothing identical across devices with different sensor rates.
 */
class Ema(private val tauSeconds: Double) {
    private var value: Double? = null

    fun update(sample: Double, dtSeconds: Double): Double {
        val prev = value
        val next = if (prev == null || dtSeconds <= 0.0) {
            sample
        } else {
            val alpha = 1.0 - exp(-dtSeconds / tauSeconds)
            prev + alpha * (sample - prev)
        }
        value = next
        return next
    }

    fun reset() { value = null }
}
