"""Sanitize untrusted Jira/Confluence text before LLM prompts."""

from __future__ import annotations

import re

_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
_INJECTION_MARKERS = [
    "ignore previous instructions",
    "ignore all previous",
    "system prompt",
    "you are now",
    "disregard your instructions",
]


def sanitize_text(text: str, max_len: int = 20_000) -> str:
    cleaned = _CONTROL.sub("", text or "")
    cleaned = cleaned.replace("```", "'''")
    lower = cleaned.lower()
    for marker in _INJECTION_MARKERS:
        if marker in lower:
            cleaned = re.sub(re.escape(marker), "[filtered]", cleaned, flags=re.IGNORECASE)
    if len(cleaned) > max_len:
        cleaned = cleaned[:max_len] + "\n...[truncated]"
    return cleaned.strip()
