"""Query normalisation and hashing."""

from __future__ import annotations

import hashlib

# All recognised XC API v3 search tag prefixes
SEARCH_TAGS: frozenset[str] = frozenset(
    {
        # Taxonomic
        "sp",
        "gen",
        "ssp",
        "fam",
        "en",
        "grp",
        # Geographic
        "area",
        "cnt",
        "loc",
        "lat",
        "lon",
        "box",
        # Temporal
        "year",
        "month",
        "since",
        # Sound
        "type",
        "sex",
        "stage",
        "q",
        "len",
        "smp",
        # Recording
        "rec",
        "nr",
        "lic",
        "dvc",
        "mic",
        "method",
        # Other
        "also",
        "rmk",
        "seen",
        "playback",
        "othertype",
    }
)


def normalise_query(query: str) -> str:
    """Normalise a query string for consistent hashing (strip, collapse whitespace)."""
    return " ".join(query.split())


def query_hash(query: str) -> str:
    """Return a hex SHA-256 hash of the normalised query string."""
    normalised = normalise_query(query)
    return hashlib.sha256(normalised.encode()).hexdigest()
