import json
from typing import Optional


def format_llm_output_for_logging(purpose: str, result: str, max_len: Optional[int] = None) -> str:
    if purpose == "sentence_transformer":
        try:
            parsed = json.loads(result)
        except json.JSONDecodeError:
            return result
        return json.dumps(parsed, indent=2, ensure_ascii=False)

    if max_len is not None and len(result) > max_len:
        return f"{result[:max_len]}..."

    return result
