import hashlib
import json
import os
from typing import Optional

_client = None


def _get_client():
    global _client
    if _client is None:
        import redis
        url = os.environ.get("REDIS_URL", "redis://localhost:6379")
        _client = redis.from_url(url, decode_responses=True)
    return _client


def cache_key(image_bytes: bytes) -> str:
    return f"identify:{hashlib.sha256(image_bytes).hexdigest()}"


def get(image_bytes: bytes) -> Optional[list]:
    try:
        value = _get_client().get(cache_key(image_bytes))
        return json.loads(value) if value else None
    except Exception:
        return None


def set(image_bytes: bytes, results: list, ttl: int = 604800) -> None:
    try:
        _get_client().setex(cache_key(image_bytes), ttl, json.dumps(results))
    except Exception:
        pass  # cache indisponible → silencieux
