"""
Lightweight metrics HTTP server for non-FastAPI processes.

Provides a simple way to expose Prometheus metrics from consumer workers
and other background processes that don't use FastAPI.
"""

import threading
from prometheus_client import start_http_server, REGISTRY


def start_metrics_server(port: int = 80, addr: str = "0.0.0.0") -> threading.Thread:
    """
    Start a lightweight HTTP server to expose Prometheus metrics.

    This is intended for use in consumer workers and other non-FastAPI processes
    that need to expose metrics for Prometheus scraping.

    Args:
        port: Port to listen on (default: 8001)
        addr: Address to bind to (default: "0.0.0.0")

    Returns:
        The daemon thread running the metrics server

    Usage:
        from common.metrics import start_metrics_server

        if __name__ == "__main__":
            start_metrics_server(port=8001)
            # ... rest of consumer code
    """
    # start_http_server returns a tuple of (server, thread) in newer versions
    # but just starts in background in older versions - we handle both
    result = start_http_server(port, addr=addr, registry=REGISTRY)

    if isinstance(result, tuple):
        _, thread = result
        return thread

    # For older prometheus_client versions that don't return the thread,
    # we can't return it, but the server is still running
    return None
