import re


def sanitize_for_log(value: str, max_length: int = 1024) -> str:
    """Sanitize potentially attacker-controlled strings before logging.

    - Strip CR, LF, TAB and other ASCII control characters (0x00-0x1F, 0x7F)
    - Collapse whitespace runs to a single space
    - Truncate overly long inputs to max_length
    """
    if value is None:
        return ""
    if not isinstance(value, str):
        value = str(value)
    # Remove control characters including CR/LF/TAB
    value = re.sub(r"[\x00-\x1F\x7F]", " ", value)
    # Collapse whitespace
    value = re.sub(r"\s+", " ", value).strip()
    # Truncate
    if len(value) > max_length:
        value = value[:max_length] + "…"
    return value


