"""结果缓存中间件"""

from __future__ import annotations

import hashlib
import json
import time
from typing import Any


class ResultCache:
    """相同 tool_id + params 的重复调用直接返回缓存"""

    def __init__(self, default_ttl: int = 300) -> None:
        self._cache: dict[str, tuple[Any, float]] = {}
        self.default_ttl = default_ttl

    def _make_key(self, tool_id: str, params: dict) -> str:
        raw = json.dumps({"tool_id": tool_id, "params": params}, sort_keys=True)
        return hashlib.sha256(raw.encode()).hexdigest()

    def get(self, tool_id: str, params: dict) -> Any | None:
        key = self._make_key(tool_id, params)
        if key in self._cache:
            value, expire_at = self._cache[key]
            if time.time() < expire_at:
                return value
            del self._cache[key]
        return None

    def set(self, tool_id: str, params: dict, result: Any, ttl: int | None = None) -> None:
        key = self._make_key(tool_id, params)
        self._cache[key] = (result, time.time() + (ttl or self.default_ttl))
