from __future__ import annotations

import json
import logging
from typing import Any

import redis.asyncio as redis

from app.config import REDIS_URL

logger = logging.getLogger(__name__)
_client: redis.Redis | None = None


async def init_redis() -> None:
    global _client
    try:
        _client = redis.from_url(REDIS_URL, decode_responses=True)
        await _client.ping()
        logger.info("Redis connected")
    except Exception as exc:
        logger.warning("Redis unavailable, running without Redis cache: %s", exc)
        _client = None


async def close_redis() -> None:
    global _client
    if _client is not None:
        await _client.aclose()
        _client = None


def redis_available() -> bool:
    return _client is not None


async def cache_get(key: str) -> Any | None:
    if _client is None:
        return None
    raw = await _client.get(key)
    if raw is None:
        return None
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return raw


async def cache_set(key: str, value: Any, ttl_seconds: int) -> None:
    if _client is None:
        return
    await _client.set(key, json.dumps(value), ex=ttl_seconds)


async def flush_cache() -> None:
    if _client is not None:
        await _client.flushdb()
