# tests/test_metrics_exporter.py
import pytest


def test_import_without_prometheus():
    """Module must import even when prometheus_client is not installed."""
    import sys
    original = sys.modules.pop("prometheus_client", None)
    sys.modules["prometheus_client"] = None  # Simulate missing
    try:
        if "llm_guard.metrics_exporter" in sys.modules:
            del sys.modules["llm_guard.metrics_exporter"]
        from llm_guard import metrics_exporter
        assert metrics_exporter.PROMETHEUS_AVAILABLE is False
    finally:
        if original is not None:
            sys.modules["prometheus_client"] = original
        else:
            del sys.modules["prometheus_client"]
        if "llm_guard.metrics_exporter" in sys.modules:
            del sys.modules["llm_guard.metrics_exporter"]


def test_record_chain_score_noop_without_prometheus():
    """record_chain_score() must not raise even without prometheus_client."""
    if "llm_guard.metrics_exporter" in __import__("sys").modules:
        del __import__("sys").modules["llm_guard.metrics_exporter"]
    from llm_guard.metrics_exporter import record_chain_score, PROMETHEUS_AVAILABLE
    if not PROMETHEUS_AVAILABLE:
        record_chain_score(risk=0.75, tier="ALERT", latency=0.12)  # must not raise


def test_record_chain_score_with_prometheus():
    """If prometheus_client is available, calling record_chain_score() must not raise."""
    try:
        import prometheus_client  # noqa
    except ImportError:
        pytest.skip("prometheus_client not installed")
    from llm_guard.metrics_exporter import record_chain_score
    record_chain_score(risk=0.45, tier="PASS", latency=0.08)  # must not raise


def test_generate_latest_returns_bytes():
    """generate_latest() must return bytes (empty or Prometheus text)."""
    try:
        import prometheus_client  # noqa
    except ImportError:
        pytest.skip("prometheus_client not installed")
    from llm_guard.metrics_exporter import generate_latest
    output = generate_latest()
    assert isinstance(output, bytes)
    assert b"llmguard" in output
