# -*- coding: utf-8 -*-

import logging

from slowapi import Limiter
from slowapi.util import get_remote_address

from odoo_api.core.config import get_settings

logger = logging.getLogger(__name__)

limiter = Limiter(
    key_func=get_remote_address,
    storage_uri=get_settings().limiter_storage_uri,
    in_memory_fallback_enabled=True,
)

_overrides: dict[str, str] = {}

_KNOWN_ROUTES = {
    "/api/login",
    "/api/models/{model}/{record_id}",
    "/api/models/{model}/search",
    "/api/models/{model}",
    "/api/models/{model}/execute/{func_name}",
}


def set_rate_limits(overrides: dict[str, str]):
    for path in overrides:
        if path not in _KNOWN_ROUTES:
            logger.warning(
                "Rate limit override key %r does not match any known route template. "
                "Valid keys: %s",
                path,
                ", ".join(sorted(_KNOWN_ROUTES)),
            )
    _overrides.update(overrides)


def route_limit(path: str):
    """Returns a callable for @limiter.limit() that resolves the limit at request time."""
    def _resolve() -> str:
        return _overrides.get(path, get_settings().rate_limit)
    return _resolve
