# tests/test_metrics_exporter.py
import pytest


def test_import_without_prometheus():
    """Module must import even when prometheus_client is not installed."""
    import sys
    import importlib
    original_prom = sys.modules.pop("prometheus_client", None)
    original_mod = sys.modules.pop("llm_guard.monitoring.metrics_exporter", None)
    sys.modules["prometheus_client"] = None  # Simulate missing

    # Also evict the cached attribute from the llm_guard package namespace so
    # that the reimport actually re-executes the module code (not just returns
    # the already-bound attribute from a prior full-suite import).
    import llm_guard as _pkg
    saved_attr = getattr(_pkg, "metrics_exporter", _SENTINEL := object())
    had_attr = saved_attr is not _SENTINEL
    if had_attr:
        delattr(_pkg, "metrics_exporter")

    try:
        metrics_exporter = importlib.import_module("llm_guard.monitoring.metrics_exporter")
        assert metrics_exporter.PROMETHEUS_AVAILABLE is False
    finally:
        if original_prom is not None:
            sys.modules["prometheus_client"] = original_prom
        else:
            sys.modules.pop("prometheus_client", None)
        if original_mod is not None:
            sys.modules["llm_guard.monitoring.metrics_exporter"] = original_mod
        else:
            sys.modules.pop("llm_guard.monitoring.metrics_exporter", None)
        if had_attr:
            _pkg.metrics_exporter = saved_attr


def test_record_chain_score_noop_without_prometheus():
    """record_chain_score() must not raise even without prometheus_client."""
    if "llm_guard.monitoring.metrics_exporter" in __import__("sys").modules:
        del __import__("sys").modules["llm_guard.monitoring.metrics_exporter"]
    from llm_guard.monitoring.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.monitoring.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.monitoring.metrics_exporter import generate_latest
    output = generate_latest()
    assert isinstance(output, bytes)
    assert b"llmguard" in output
