"""进程内缓存后端: dict + 过期时刻;测试与无 Redis 场景使用。"""

from __future__ import annotations

import time
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from collections.abc import Callable


class InMemoryCache:
    """笨 KV(CacheBackend 契约);容量不设限——库内默认 TTL 必填防无界增长。"""

    def __init__(self, now: Callable[[], float] = time.monotonic) -> None:
        self._now = now
        self._store: dict[str, tuple[float, str]] = {}

    async def get(self, key: str) -> str | None:
        item = self._store.get(key)
        if item is None:
            return None
        expires_at, value = item
        if self._now() >= expires_at:
            del self._store[key]
            return None
        return value

    async def set(self, key: str, value: str, ttl_s: int) -> None:
        self._store[key] = (self._now() + ttl_s, value)
