package com.onthelevel.core.sensors

import kotlin.math.abs
import kotlin.math.roundToInt

/**
 * Quantizes a stable measurement to 0.1° for display, with hysteresis so the readout
 * doesn't flicker between adjacent values when the input sits on a bucket boundary
 * (BRIEF.md: "0.1° resolution and a display deadband").
 *
 * A displayed value of 0.1° owns the interval [0.05, 0.15]; the readout only moves
 * once the input leaves that interval by more than [hysteresisMarginDegrees].
 */
class DisplayDeadband(
    private val resolutionDegrees: Double = 0.1,
    private val hysteresisMarginDegrees: Double = 0.03,
) {
    private var displayed: Double? = null

    fun update(stableDegrees: Double): Double {
        val current = displayed
        val next = if (current == null ||
            abs(stableDegrees - current) > resolutionDegrees / 2 + hysteresisMarginDegrees
        ) {
            (stableDegrees / resolutionDegrees).roundToInt() * resolutionDegrees
        } else {
            current
        }
        displayed = next
        return next
    }

    fun reset() { displayed = null }
}
