from prometheus_client import start_http_server
from altrus.core.observability.metrics import REGISTRY
from prometheus_client.exposition import make_wsgi_app
from wsgiref.simple_server import make_server
import threading


_active_servers = []

def start_metrics_server(port=8000, max_retries=10):
    app = make_wsgi_app(REGISTRY)
    server_wrapper = {"httpd": None}

    def serve():
        current_port = port
        for i in range(max_retries):
            try:
                httpd = make_server("", current_port, app)
                server_wrapper["httpd"] = httpd
                _active_servers.append(httpd)
                print(f"📊 Metrics server started on port {current_port}")
                httpd.serve_forever()
                return
            except OSError as e:
                if e.errno == 98: # Address already in use
                    current_port += 1
                else:
                    raise e

    t = threading.Thread(target=serve, daemon=True)
    t.start()
    return server_wrapper

def stop_metrics_server():
    """Stop all active metrics servers"""
    global _active_servers
    for server in _active_servers:
        try:
            server.shutdown()
            server.server_close()
        except:
            pass
    _active_servers = []
