from __future__ import annotations

from datetime import UTC, datetime, timedelta
from typing import Any


class InMemoryTTLCache:
    def __init__(self, ttl_seconds: int) -> None:
        self._ttl = timedelta(seconds=ttl_seconds)
        self._store: dict[str, tuple[datetime, Any]] = {}

    def get(self, key: str) -> Any | None:
        item = self._store.get(key)
        if item is None:
            return None
        expires_at, value = item
        if datetime.now(UTC) >= expires_at:
            self._store.pop(key, None)
            return None
        return value

    def set(self, key: str, value: Any) -> None:
        self._store[key] = (datetime.now(UTC) + self._ttl, value)

    def invalidate(self, key: str) -> None:
        self._store.pop(key, None)


_restaurant_stats_cache = InMemoryTTLCache(ttl_seconds=60)


def restaurant_stats_cache_key(restaurant_id: str) -> str:
    return f"restaurant_stats:{restaurant_id}"


def get_restaurant_stats_cached(restaurant_id: str) -> dict[str, Any] | None:
    value = _restaurant_stats_cache.get(restaurant_stats_cache_key(restaurant_id))
    if not isinstance(value, dict):
        return None
    return value


def set_restaurant_stats_cached(restaurant_id: str, value: dict[str, Any]) -> None:
    _restaurant_stats_cache.set(restaurant_stats_cache_key(restaurant_id), value)


def invalidate_restaurant_stats_cache(restaurant_id: str) -> None:
    _restaurant_stats_cache.invalidate(restaurant_stats_cache_key(restaurant_id))
