"""应用缓存模拟，不涉及模型提供方的 Prompt 前缀缓存。"""
from dataclasses import dataclass


@dataclass(frozen=True)
class Key:
    tenant: str
    user: str
    task_revision: int
    policy_version: str
    auth_epoch: int
    strategy: str
    query: str


class Cache:
    def __init__(self) -> None:
        self.entries: dict[Key, tuple[float, str]] = {}

    def put(self, key: Key, value: str, *, now: float, ttl: float) -> None:
        if ttl <= 0:
            raise ValueError("TTL 必须大于零")
        self.entries[key] = (now + ttl, value)

    def get(self, key: Key, *, now: float, currently_authorized: bool) -> str | None:
        # 先检查本次授权，不能因为以前写入时有权限就永远允许读取。
        if not currently_authorized:
            return None
        entry = self.entries.get(key)
        if entry is None:
            return None
        expires_at, value = entry
        if now >= expires_at:
            del self.entries[key]
            return None
        return value


if __name__ == "__main__":
    from dataclasses import replace
    cache = Cache()
    key = Key("shop-a", "user-417", 4, "v2", 7, "consultation-v3", "A1042运费")
    cache.put(key, "演示上下文", now=0, ttl=60)
    print(cache.get(key, now=10, currently_authorized=True))
    print(cache.get(replace(key, policy_version="v3"), now=10, currently_authorized=True))
    print(cache.get(key, now=10, currently_authorized=False))
    print(cache.get(key, now=61, currently_authorized=True))
