import base64
import hashlib
import time

from django.core.cache import cache

DEFAULT_BLOB_TTL_SECONDS = 60 * 20


def _blob_cache_key(service, digest):
    return f"gia:media:{service}:{digest}"


def put_blob(service, content, filename, content_type, ttl=DEFAULT_BLOB_TTL_SECONDS):
    if not content:
        return None
    digest = hashlib.sha1(content).hexdigest()
    key = _blob_cache_key(service, digest)
    cache.set(
        key,
        {
            "filename": filename or "attachment.bin",
            "content_type": content_type or "application/octet-stream",
            "content_b64": base64.b64encode(content).decode("utf-8"),
            "size": len(content),
            "stored_at": int(time.time()),
        },
        timeout=ttl,
    )
    return key


def get_blob(key):
    row = cache.get(key)
    if not row:
        return None
    try:
        content = base64.b64decode(row.get("content_b64", ""))
    except Exception:
        return None
    return {
        "content": content,
        "filename": row.get("filename") or "attachment.bin",
        "content_type": row.get("content_type") or "application/octet-stream",
        "size": row.get("size") or len(content),
        "stored_at": row.get("stored_at"),
    }
