import json
import redis as redis_lib
from app.config import REDIS_URL

_client = None


def get_redis():
    global _client
    if _client is None:
        _client = redis_lib.from_url(REDIS_URL, decode_responses=True)
    return _client


def cache_get(key):
    r = get_redis()
    data = r.get(key)
    if data is not None:
        return json.loads(data)
    return None


def cache_set(key, value, ttl):
    r = get_redis()
    r.set(key, json.dumps(value), ex=ttl)


def cache_health():
    try:
        r = get_redis()
        r.ping()
        return True
    except Exception:
        return False
