"""Shared rate-limit instance keyed by X-API-Key header.

slowapi's Limiter needs to be instantiated once and referenced wherever
we decorate endpoints. Falls back to remote IP if the header is missing
(useful for unauth'd error paths — the actual auth dep still blocks
unkeyed requests before the limiter runs).
"""
from slowapi import Limiter
from slowapi.util import get_remote_address


def _key_func(request) -> str:
    k = request.headers.get("X-API-Key")
    if k:
        return f"apikey:{k}"
    return f"ip:{get_remote_address(request)}"


limiter = Limiter(key_func=_key_func, default_limits=[])
