"""SHA256-based STL conversion cache using MinIO."""
from __future__ import annotations
import hashlib
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

CACHE_PREFIX = "conversion-cache"


def compute_step_hash(file_path: str) -> str:
    """Compute SHA256 hash of a STEP file."""
    h = hashlib.sha256()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def _cache_key(step_hash: str, quality: str) -> str:
    return f"{CACHE_PREFIX}/{step_hash}_{quality}.stl"


def check_stl_cache(step_hash: str, quality: str) -> bytes | None:
    """Return STL bytes from MinIO cache if present, else None."""
    from app.core.storage import get_storage
    storage = get_storage()
    key = _cache_key(step_hash, quality)
    try:
        if storage.exists(key):
            return storage.download_bytes(key)
        return None
    except Exception as exc:
        logger.warning("Cache check failed for %s: %s", key, exc)
        return None


def store_stl_cache(step_hash: str, quality: str, stl_path: str) -> None:
    """Upload local STL file to MinIO cache."""
    from app.core.storage import get_storage
    storage = get_storage()
    key = _cache_key(step_hash, quality)
    try:
        storage.upload(Path(stl_path), key)
        logger.info("Stored STL cache: %s", key)
    except Exception as exc:
        logger.warning("Failed to store STL cache %s: %s", key, exc)
