"""Gateway-specific adaptive concurrency control.

This module provides gateway-specific wrappers around the core adaptive
concurrency limiter from _internal/concurrency. It adds:

1. Integration with gateway metrics (METRICS registry)
2. Gateway-specific configuration options
3. Re-exports for backwards compatibility

The core algorithm lives in ember._internal.concurrency and can be used
directly by OSS code (models, operators) without gateway dependencies.

For OSS usage, import from ember._internal.concurrency directly:
    from ember._internal.concurrency import (
        AdaptiveConcurrencyLimiter,
        ConcurrencyKey,
        Outcome,
    )

For gateway usage, import from this module to get metrics integration:
    from .adaptive_concurrency import (
        get_adaptive_limiter,
        ConcurrencyKey,
        Outcome,
    )
"""

from __future__ import annotations

import logging
import threading

# Re-export core types from _internal for backwards compatibility
from ember._internal.concurrency import (
    AdaptiveConcurrencyLimiter,
    AdjustmentCallback,
    ConcurrencyKey,
    Outcome,
)
from ember._internal.concurrency.limiter import outcome_from_error

__all__ = [
    "AdaptiveConcurrencyLimiter",
    "AdjustmentCallback",
    "ConcurrencyKey",
    "Outcome",
    "get_adaptive_limiter",
    "reset_adaptive_limiter",
    "outcome_from_error",
]

_LOG = logging.getLogger(__name__)


def _metrics_callback(
    key: ConcurrencyKey, old_limit: float, new_limit: float, outcome: Outcome
) -> None:
    """Callback to record concurrency adjustments in gateway metrics."""
    from .metrics import METRICS

    METRICS.record_concurrency_adjustment(
        provider=str(key),
        old_limit=old_limit,
        new_limit=new_limit,
        is_rate_limit=(outcome == Outcome.RATE_LIMITED),
    )


# Gateway-specific singleton with metrics integration
_gateway_limiter: AdaptiveConcurrencyLimiter | None = None
_limiter_lock = threading.Lock()


def get_adaptive_limiter() -> AdaptiveConcurrencyLimiter:
    """Get the gateway's adaptive concurrency limiter with metrics integration.

    This limiter is specifically for gateway use and includes:
    - Integration with gateway METRICS registry
    - Gateway-specific configuration (if any)

    For OSS usage without gateway dependencies, use:
        from ember._internal.concurrency import get_limiter

    Returns:
        The gateway AdaptiveConcurrencyLimiter instance.
    """
    global _gateway_limiter
    with _limiter_lock:
        if _gateway_limiter is None:
            _gateway_limiter = AdaptiveConcurrencyLimiter()
            _gateway_limiter.set_on_adjustment(_metrics_callback)
            _LOG.info("Initialized gateway adaptive concurrency limiter with metrics")
        return _gateway_limiter


def reset_adaptive_limiter() -> None:
    """Reset the gateway limiter. For testing only."""
    global _gateway_limiter
    with _limiter_lock:
        _gateway_limiter = None
