"""Input sanitization for LLM context."""

from __future__ import annotations

import re

# Maximum input length (characters) to prevent context stuffing
MAX_INPUT_LENGTH = 32_000


def sanitize_input(text: str, max_length: int = MAX_INPUT_LENGTH) -> str:
    """Sanitize user input before including in LLM context.

    - Strip null bytes
    - Truncate to max_length
    - Normalize excessive whitespace
    """
    # Remove null bytes
    text = text.replace("\x00", "")

    # Truncate
    if len(text) > max_length:
        text = text[:max_length]

    # Collapse runs of whitespace (preserve single newlines)
    text = re.sub(r"[^\S\n]+", " ", text)
    text = re.sub(r"\n{3,}", "\n\n", text)

    return text.strip()


def sanitize_for_log(text: str, max_length: int = 200) -> str:
    """Truncate and sanitize text for safe logging (no PII leaking)."""
    text = text.replace("\n", " ").strip()
    if len(text) > max_length:
        return text[:max_length] + "..."
    return text
