"""Redis cache helpers for retrieval results."""
from __future__ import annotations

import json
from typing import Any

from redis import asyncio as redis

from normbase.config import settings


class CacheService:
    """Thin async Redis wrapper with JSON helpers."""

    def __init__(self):
        self._client = redis.from_url(settings.redis_url, decode_responses=True)

    async def get_json(self, key: str) -> Any | None:
        value = await self._client.get(key)
        if value is None:
            return None
        return json.loads(value)

    async def set_json(self, key: str, value: Any, ttl_seconds: int) -> None:
        payload = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
        await self._client.set(key, payload, ex=ttl_seconds)

    async def delete_by_prefix(self, prefix: str) -> int:
        deleted = 0
        async for key in self._client.scan_iter(match=f"{prefix}*"):
            deleted += await self._client.delete(key)
        return deleted

