"""OAuth client Prometheus metrics.

This module provides production-grade observability for OAuth operations.
Metrics are exported via prometheus_client and can be scraped by Prometheus.

Usage:
    from empowernow_common.oauth.metrics import (
        record_token_request,
        record_cache_hit,
        set_circuit_breaker_state,
    )
    
    # Record successful token acquisition
    record_token_request(
        client_id="my-app",
        auth_method="client_secret_basic",
        result="success",
        duration_seconds=0.234,
    )
"""

from typing import Optional
import logging

logger = logging.getLogger(__name__)

# Try to import prometheus_client - gracefully degrade if not available
try:
    from prometheus_client import Counter, Histogram, Gauge
    _PROMETHEUS_AVAILABLE = True
except ImportError:
    _PROMETHEUS_AVAILABLE = False
    logger.debug("prometheus_client not installed - metrics disabled")


# Metrics definitions (only created if prometheus_client is available)
if _PROMETHEUS_AVAILABLE:
    # Token acquisition metrics
    oauth_token_requests_total = Counter(
        "empowernow_oauth_token_requests_total",
        "Total OAuth token requests",
        ["client_id", "auth_method", "result"]
    )

    oauth_token_latency_seconds = Histogram(
        "empowernow_oauth_token_latency_seconds",
        "OAuth token acquisition latency in seconds",
        ["client_id", "auth_method"],
        buckets=[0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]
    )

    oauth_token_cache_operations_total = Counter(
        "empowernow_oauth_token_cache_operations_total",
        "OAuth token cache operations",
        ["client_id", "operation"]  # operation: hit, miss, clear
    )

    oauth_circuit_breaker_state = Gauge(
        "empowernow_oauth_circuit_breaker_state",
        "OAuth circuit breaker state (0=closed, 1=half-open, 2=open)",
        ["client_id"]
    )

    oauth_circuit_breaker_trips_total = Counter(
        "empowernow_oauth_circuit_breaker_trips_total",
        "Total times OAuth circuit breaker has tripped",
        ["client_id"]
    )

    oauth_http_requests_total = Counter(
        "empowernow_oauth_http_requests_total",
        "Total HTTP requests to OAuth endpoints",
        ["client_id", "endpoint_type", "status_code"]
    )


def record_token_request(
    client_id: str,
    auth_method: str,
    result: str,
    duration_seconds: float,
) -> None:
    """Record a token request metric.
    
    Args:
        client_id: OAuth client ID
        auth_method: Authentication method (client_secret_basic, private_key_jwt, etc.)
        result: Request result (success, error, timeout, circuit_open)
        duration_seconds: Request duration in seconds
    """
    if not _PROMETHEUS_AVAILABLE:
        return
    
    oauth_token_requests_total.labels(
        client_id=client_id,
        auth_method=auth_method,
        result=result,
    ).inc()
    
    oauth_token_latency_seconds.labels(
        client_id=client_id,
        auth_method=auth_method,
    ).observe(duration_seconds)


def record_cache_hit(client_id: str) -> None:
    """Record a token cache hit."""
    if not _PROMETHEUS_AVAILABLE:
        return
    oauth_token_cache_operations_total.labels(
        client_id=client_id,
        operation="hit",
    ).inc()


def record_cache_miss(client_id: str) -> None:
    """Record a token cache miss."""
    if not _PROMETHEUS_AVAILABLE:
        return
    oauth_token_cache_operations_total.labels(
        client_id=client_id,
        operation="miss",
    ).inc()


def record_cache_clear(client_id: str) -> None:
    """Record a token cache clear."""
    if not _PROMETHEUS_AVAILABLE:
        return
    oauth_token_cache_operations_total.labels(
        client_id=client_id,
        operation="clear",
    ).inc()


def set_circuit_breaker_state(client_id: str, state: int) -> None:
    """Set circuit breaker state gauge.
    
    Args:
        client_id: OAuth client ID
        state: 0=closed, 1=half-open, 2=open
    """
    if not _PROMETHEUS_AVAILABLE:
        return
    oauth_circuit_breaker_state.labels(client_id=client_id).set(state)


def record_circuit_breaker_trip(client_id: str) -> None:
    """Record a circuit breaker trip."""
    if not _PROMETHEUS_AVAILABLE:
        return
    oauth_circuit_breaker_trips_total.labels(client_id=client_id).inc()


def record_http_request(
    client_id: str,
    endpoint_type: str,
    status_code: int,
) -> None:
    """Record an HTTP request to an OAuth endpoint.
    
    Args:
        client_id: OAuth client ID
        endpoint_type: Type of endpoint (token, introspect, revoke, par, ciba)
        status_code: HTTP response status code
    """
    if not _PROMETHEUS_AVAILABLE:
        return
    oauth_http_requests_total.labels(
        client_id=client_id,
        endpoint_type=endpoint_type,
        status_code=str(status_code),
    ).inc()


def is_metrics_available() -> bool:
    """Check if Prometheus metrics are available."""
    return _PROMETHEUS_AVAILABLE
