from prometheus_client import Counter, Histogram, Gauge, start_http_server
import time

# Define global metrics
auth_attempts = Counter('auth_attempts_total', 'Authentication attempts', ['result'])
session_duration = Histogram('session_duration_seconds', 'Session lifespan')
challenge_rate = Gauge('challenge_rate', 'Rate of challenges encountered')
extraction_throughput = Counter('extraction_requests_total', 'API extractions', ['status'])

class MetricsCollector:
    _server_started = False

    @classmethod
    def start_server(cls, port=8000):
        if not cls._server_started:
            start_http_server(port)
            cls._server_started = True

    @staticmethod
    def record_auth_success():
        auth_attempts.labels(result='success').inc()
    
    @staticmethod
    def record_auth_failure(reason: str):
        auth_attempts.labels(result=reason).inc()
    
    @staticmethod
    def record_session_lifetime(duration: float):
        session_duration.observe(duration)
    
    @staticmethod
    def update_challenge_rate(rate: float):
        challenge_rate.set(rate)
        
    @staticmethod
    def record_extraction(status: str):
        extraction_throughput.labels(status=status).inc()
