"""Rate limiting через CacheStorageProtocol."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ui_router.schema import ThrottleConfig, ThrottleScope
    from ui_router.services.shared import CacheStorageProtocol


class ThrottleChecker:
    """Проверяет rate limit через CacheStorageProtocol."""

    def __init__(self, cache_storage: CacheStorageProtocol) -> None:
        self._cache = cache_storage

    async def check(
        self,
        handler_name: str,
        throttle: ThrottleConfig,
        user_id: int | None,
        chat_id: int | None,
    ) -> bool:
        """True если запрос разрешён, False если throttled."""
        key = self._build_key(handler_name, throttle.scope, user_id, chat_id)
        count = await self._cache.get(key)
        if count is not None and int(count) >= throttle.max_calls:
            return False
        new_count = (int(count) if count else 0) + 1
        await self._cache.set(key, str(new_count), ttl=throttle.period_seconds)
        return True

    @staticmethod
    def _build_key(
        handler_name: str,
        scope: ThrottleScope,
        user_id: int | None,
        chat_id: int | None,
    ) -> str:
        from ui_router.schema import ThrottleScope as ThrottleScopeEnum

        if scope == ThrottleScopeEnum.USER:
            return f"throttle:user:{handler_name}:{user_id}"
        if scope == ThrottleScopeEnum.CHAT:
            return f"throttle:chat:{handler_name}:{chat_id}"
        return f"throttle:global:{handler_name}"
