import functools
import pickle

import redis

# Create a Redis client (adjust host/port/db as needed)
redis_client = redis.Redis(host="localhost", port=6379, db=0)


def redis_cache(ttl=60):
    """
    A decorator that caches the function result in Redis for `ttl` seconds.
    It uses pickle for serialization.
    """

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # Construct a cache key. You might want to use a more robust hashing mechanism.
            key = f"{func.__name__}:{args}:{kwargs}"

            # Try to retrieve cached data
            cached_result = redis_client.get(key)
            if cached_result is not None:
                # Deserialize and return the cached result
                return pickle.loads(cached_result)

            # Compute the result as it's not in cache
            result = func(*args, **kwargs)

            # Serialize and cache the result in Redis with an expiration (ttl)
            redis_client.setex(key, ttl, pickle.dumps(result))
            return result

        return wrapper

    return decorator
