"""Rate limit configuration for TipSharks API.

Provides centralized rate limit definitions and a key function that supports
per-user rate limiting via the X-User-ID header, with IP fallback for anonymous clients.
"""

from fastapi import Request
from slowapi.util import get_remote_address

# Default rate limits per endpoint group (applied per-user when user ID is available)
RATE_LIMITS = {
    "default": "100/minute",
    "races_list": "200/minute",
    "race_detail": "100/minute",
    "predictions": "50/minute",
    "export": "10/minute",
    "admin": "20/minute",
}


def get_user_rate_limit_key(request: Request) -> str:
    """Generate rate limit key from user ID header or IP address.

    Uses the ``X-User-ID`` header for per-user rate limiting when the mobile
    client provides an anonymous identifier. Falls back to the client IP
    address for unauthenticated (e.g. browser) requests.

    Keys are namespaced (``user:`` / ``ip:``) to avoid accidental collisions.

    Args:
        request: FastAPI incoming request.

    Returns:
        A string suitable for use as a slowapi rate-limit key.
    """
    user_id = request.headers.get("X-User-ID")
    if user_id:
        user_id = user_id.strip()
        if user_id:
            return f"user:{user_id}"

    # Fall back to IP-based key
    return f"ip:{get_remote_address(request)}"
