"""Cache key generation."""
from __future__ import annotations

import hashlib
import json
from typing import Any


class CacheKeyBuilder:
    """Builds deterministic cache keys."""

    def exact(
        self,
        *,
        model: str,
        system_prompt: str | None,
        messages: list[dict[str, Any]],
        tools: list[dict] | None,
    ) -> str:
        """Build an exact-match cache key."""
        data = {
            "model": model,
            "system_prompt": system_prompt,
            "messages": messages,
            "tools": sorted(tools, key=lambda t: json.dumps(t, sort_keys=True))
            if tools
            else None,
        }
        raw = json.dumps(data, sort_keys=True, ensure_ascii=False)
        return hashlib.sha256(raw.encode()).hexdigest()

    def scope_hash(
        self,
        *,
        model: str,
        system_prompt: str | None,
        tools: list[dict] | None,
    ) -> str:
        """Build a scope hash for namespace isolation in semantic search."""
        data = {
            "model": model,
            "system_prompt": system_prompt,
            "tools": sorted(tools, key=lambda t: json.dumps(t, sort_keys=True))
            if tools
            else None,
        }
        raw = json.dumps(data, sort_keys=True, ensure_ascii=False)
        return hashlib.sha256(raw.encode()).hexdigest()
