from __future__ import annotations

from functools import lru_cache

from redis import Redis as SyncRedis
from redis.asyncio import Redis

from app.core.config import get_settings


@lru_cache(maxsize=1)
def get_redis_client() -> Redis | None:
    redis_url = get_settings().redis_url.strip()
    if not redis_url:
        return None
    return Redis.from_url(redis_url, decode_responses=True)


@lru_cache(maxsize=1)
def get_sync_redis_client() -> SyncRedis | None:
    redis_url = get_settings().redis_url.strip()
    if not redis_url:
        return None
    return SyncRedis.from_url(redis_url, decode_responses=True)


async def ping_redis() -> bool:
    client = get_redis_client()
    if client is None:
        return False
    try:
        return bool(await client.ping())
    except Exception:
        return False
