"""Query normalisation utilities for AI response caching.

normalize_query  — collapses whitespace, lowercases, strips
query_hash       — SHA-256 hex digest of the normalised query
"""

from __future__ import annotations

import hashlib
import re


def normalize_query(text: str) -> str:
    """Return a canonical form of *text* suitable for cache key generation.

    Steps:
      1. Strip leading/trailing whitespace.
      2. Collapse internal whitespace runs to a single space.
      3. Lowercase.
    """
    text = text.strip()
    text = re.sub(r"\s+", " ", text)
    return text.lower()


def query_hash(text: str) -> str:
    """Return the SHA-256 hex digest of the normalised *text*.

    The same logical query always produces the same hash regardless of
    minor whitespace differences or capitalisation.
    """
    normalised = normalize_query(text)
    return hashlib.sha256(normalised.encode("utf-8")).hexdigest()
