"""Cache resource -- key/value cache with TTL."""

from __future__ import annotations

from typing import Any

from mcpgateway_sdk._exceptions import NotFoundError
from mcpgateway_sdk._http import HTTPClient

_ENDPOINTS = {
    "get": ("GET", "/api/v1/sdk/cache/{key}"),
    "set": ("PUT", "/api/v1/sdk/cache/{key}"),
}


class CacheResource:
    """Read and write to the gateway's SDK cache."""

    _endpoints = _ENDPOINTS

    def __init__(self, http: HTTPClient) -> None:
        self._http = http

    async def get(self, key: str) -> Any | None:
        """Retrieve a cached value by key.

        Args:
            key: The cache key.

        Returns:
            The cached value, or None if the key does not exist.
        """
        try:
            data = await self._http.request("GET", f"/api/v1/sdk/cache/{key}")
        except NotFoundError:
            return None
        return data.get("value")

    async def set(self, key: str, value: Any, ttl: int = 300) -> None:
        """Store a value in the cache.

        Args:
            key: The cache key.
            value: The value to cache (must be JSON-serializable).
            ttl: Time-to-live in seconds (default 300).
        """
        await self._http.request(
            "PUT",
            f"/api/v1/sdk/cache/{key}",
            json={"value": value, "ttl": ttl},
        )
