"""Tests for metrics."""

from dvgateway.observability.logger import create_logger
from dvgateway.observability.metrics import Counter, Histogram, PipelineMetrics


class TestHistogram:
    def test_observe_and_percentiles(self) -> None:
        h = Histogram([10, 50, 100, 200])
        for _ in range(50):
            h.observe(30)  # bucket: 50
        for _ in range(50):
            h.observe(150)  # bucket: 200

        p = h.percentiles()
        assert p["p50"] == 50
        assert p["p95"] == 200
        assert p["mean"] == 90.0

    def test_empty_percentiles(self) -> None:
        h = Histogram()
        p = h.percentiles()
        assert p["p50"] == 0.0
        assert p["mean"] == 0.0

    def test_prometheus_format(self) -> None:
        h = Histogram([10, 50, 100])
        h.observe(5)
        h.observe(75)
        text = h.to_prometheus("test_metric")
        assert 'test_metric_bucket{le="10"} 1' in text
        assert 'test_metric_bucket{le="50"} 1' in text
        assert 'test_metric_bucket{le="100"} 2' in text
        assert 'test_metric_bucket{le="+Inf"} 2' in text
        assert "test_metric_sum 80.0" in text
        assert "test_metric_count 2" in text


class TestCounter:
    def test_increment(self) -> None:
        c = Counter()
        assert c.get() == 0
        c.increment()
        assert c.get() == 1
        c.increment(5)
        assert c.get() == 6

    def test_reset(self) -> None:
        c = Counter()
        c.increment(10)
        c.reset()
        assert c.get() == 0


class TestPipelineMetrics:
    def test_start_timer(self) -> None:
        logger = create_logger(level="error")
        m = PipelineMetrics(logger)
        stop = m.start_timer()
        elapsed = stop()
        assert elapsed >= 0

    def test_to_prometheus(self) -> None:
        logger = create_logger(level="error")
        m = PipelineMetrics(logger)
        m.stt_latency.observe(100)
        m.transcripts_total.increment()
        text = m.to_prometheus()
        assert "dvgw_stt_latency_ms" in text
        assert "dvgw_transcripts_total 1" in text
