"""Utilities for processing and cleaning LLM output."""

from __future__ import annotations

import re

# Detects pathological repeated escape sequences (LLM got stuck in a loop)
_PATHOLOGICAL_PATTERN = re.compile(r"(\\['\"]{10,})")


def truncate_pathological_output(code: str) -> str:
    """Truncate code at pathological patterns (LLM got stuck generating repeated escape sequences)."""
    if match := _PATHOLOGICAL_PATTERN.search(code):
        return code[: match.start()].rstrip()
    return code
