"""Shared LLM cache for all B-series analyzers.

Caches LLM responses by SHA256 hash of the prompt text.
"""

from __future__ import annotations

import hashlib
import json
import os

CACHE_DIR = os.path.join(os.path.dirname(__file__), ".llm_cache")


def cache_key(prompt: str) -> str:
    return hashlib.sha256(prompt.encode()).hexdigest()


def get_cached(prompt: str) -> dict | None:
    path = os.path.join(CACHE_DIR, f"{cache_key(prompt)}.json")
    if os.path.exists(path):
        with open(path) as f:
            return json.load(f)
    return None


def set_cache(prompt: str, result: dict):
    os.makedirs(CACHE_DIR, exist_ok=True)
    path = os.path.join(CACHE_DIR, f"{cache_key(prompt)}.json")
    with open(path, "w") as f:
        json.dump(result, f, indent=2)
