from __future__ import annotations

import json
from typing import Any

from app.services.redis_client import get_redis_client


async def redis_get_text(key: str) -> str | None:
    client = get_redis_client()
    if client is None:
        return None
    try:
        value = await client.get(key)
    except Exception:
        return None
    return value if isinstance(value, str) else None


async def redis_set_text(key: str, value: str, ttl_seconds: int) -> None:
    client = get_redis_client()
    if client is None:
        return
    try:
        await client.set(key, value, ex=ttl_seconds)
    except Exception:
        return


async def redis_get_json(key: str) -> Any | None:
    value = await redis_get_text(key)
    if not value:
        return None
    try:
        return json.loads(value)
    except json.JSONDecodeError:
        return None


async def redis_set_json(key: str, value: Any, ttl_seconds: int) -> None:
    try:
        payload = json.dumps(value, ensure_ascii=False)
    except (TypeError, ValueError):
        return
    await redis_set_text(key, payload, ttl_seconds)
