from __future__ import annotations

import re

_ws_re = re.compile(r"\s+")


def normalize_thread_key(thread_key: str) -> str:
    """
    Client-side normalization to match backend intent.
    Backend canonicalization:
      - strip
      - non-empty
      - max length (you enforce 512)
    """
    if thread_key is None:
        raise ValueError("thread_key is required")

    k = thread_key.strip()
    if not k:
        raise ValueError("thread_key must be non-empty")

    if len(k) > 512:
        raise ValueError("thread_key must be <= 512 characters")

    # Keep stable semantics for "weird whitespace"
    return _ws_re.sub(" ", k)