import json


def trim_for_log(text: str | None, max_chars: int = 800) -> str:
    if text is None:
        return ""
    cleaned = str(text)
    if len(cleaned) <= max_chars:
        return cleaned
    return f"{cleaned[: max_chars - 1]}…"


def format_json_for_log(payload: dict) -> str:
    return json.dumps(payload, indent=2, ensure_ascii=False)


def format_llm_output_value(output: str | None, max_chars: int = 800) -> object:
    trimmed = trim_for_log(output, max_chars=max_chars)
    if not trimmed:
        return ""
    try:
        return json.loads(trimmed)
    except json.JSONDecodeError:
        return trimmed
