"""Content-addressed cache for expensive operations."""

from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Any, Optional


class ResultCache:
    """Cache keyed on content hash — same input always gets same cache hit."""

    def __init__(self, cache_dir: Path):
        self.cache_dir = cache_dir
        self.cache_dir.mkdir(parents=True, exist_ok=True)

    def get(self, key: str) -> Optional[Any]:
        path = self._path(key)
        if path.exists():
            return json.loads(path.read_text(encoding="utf-8"))
        return None

    def set(self, key: str, value: Any) -> None:
        path = self._path(key)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(
            json.dumps(value, default=str, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )

    def _path(self, key: str) -> Path:
        h = hashlib.sha256(key.encode()).hexdigest()[:12]
        return self.cache_dir / f"{h}.json"
