"""Tests for neonlink.metrics.OTelMetrics."""

import pytest


def _has_otel() -> bool:
    try:
        import opentelemetry.metrics  # noqa: F401
        return True
    except ImportError:
        return False


needs_otel = pytest.mark.skipif(not _has_otel(), reason="opentelemetry-api not installed")


@needs_otel
class TestOTelMetrics:
    def test_construction(self):
        from opentelemetry.metrics import get_meter
        from neonlink.metrics import OTelMetrics

        meter = get_meter("test")
        m = OTelMetrics("testservice", meter=meter)
        assert m is not None

    def test_all_methods_callable(self):
        from opentelemetry.metrics import get_meter
        from neonlink.metrics import OTelMetrics

        meter = get_meter("test")
        m = OTelMetrics("testservice", meter=meter)

        m.publish_success("topic", 0.05)
        m.publish_error("topic", Exception("err"))
        m.consume_success("topic", 0, 0.1)
        m.consume_error("topic", 0, Exception("err"))
        m.poison_pill_detected("topic", 0, 100)
        m.poison_pill_blocked("topic", 0, 100)
        m.consumer_lag("topic", 0, 50)
        m.circuit_breaker_state_change("neonlink:consumer", "closed", "open")
        m.dlq_routed("topic", Exception("err"))

    def test_default_meter(self):
        from neonlink.metrics import OTelMetrics

        m = OTelMetrics("testservice")
        assert m is not None

    def test_instrument_names(self):
        from opentelemetry.metrics import get_meter
        from neonlink.metrics import OTelMetrics

        m = OTelMetrics("findata", meter=get_meter("test"))
        assert m._publish_duration.name == "mcfo_findata_broker_publish_duration_seconds"
        assert m._consume_duration.name == "mcfo_findata_broker_consume_duration_seconds"


class TestOTelMetricsWithoutOTel:
    def test_import_error_without_otel(self, monkeypatch):
        import sys

        monkeypatch.setitem(sys.modules, "opentelemetry", None)
        monkeypatch.setitem(sys.modules, "opentelemetry.metrics", None)

        from neonlink.metrics import OTelMetrics

        with pytest.raises(ImportError, match="opentelemetry-api is required"):
            OTelMetrics("testservice")
