"""Sanitize raw strings before writing them to log output.

``data_sanitizer.py`` handles dict-key redaction (e.g. stripping API keys
from structured data). This module handles a different concern: making a
single *string value* safe to include in a log line by removing
non-printable characters and truncating to a reasonable length.
"""

import re

# Strip C0/C1 control characters and dangerous Unicode format characters,
# but preserve visible Unicode (accented, CJK, emoji, etc.)
_UNSAFE_CHAR_RE = re.compile(
    r"[\x00-\x1f\x7f-\x9f"  # C0/C1 control chars
    r"\u061c"  # Arabic letter mark
    r"\u200b-\u200f"  # Zero-width chars + LTR/RTL marks
    r"\u202a-\u202e"  # Embedding/override (incl. RLO)
    r"\u2060-\u2064"  # Word joiner + math invisible operators
    r"\u2066-\u2069"  # Isolate chars
    r"\u206a-\u206f"  # Digit shape controls
    r"\ufeff"  # BOM / zero-width no-break space
    r"]"
)


def strip_control_chars(value: str) -> str:
    """Remove control and format characters from *value*, preserving visible Unicode."""
    return _UNSAFE_CHAR_RE.sub("", value)


def sanitize_for_log(value: str, max_length: int = 50) -> str:
    """Return a log-safe version of *value*.

    * Control and format characters are stripped; valid Unicode is preserved.
    * The result is truncated to *max_length* characters.
    """
    cleaned = strip_control_chars(value)
    if len(cleaned) > max_length:
        cleaned = (
            cleaned[: max_length - 3] + "..."
            if max_length > 3
            else cleaned[:max_length]
        )
    return cleaned
