"""Parse fenced LLM replies and truncate raw text for artifacts."""
from __future__ import annotations

import json
from typing import Any, Dict


def strip_json_fences(text: str) -> str:
    t = text.strip()
    if not t.startswith("```"):
        return t
    lines = t.split("\n")
    if lines and lines[0].startswith("```"):
        lines = lines[1:]
    if lines and lines[-1].strip() == "```":
        lines = lines[:-1]
    return "\n".join(lines).strip()


def parse_llm_norms_json(content: str) -> Dict[str, Any]:
    text = strip_json_fences(content)
    return json.loads(text)


def truncate_raw_llm(raw: str, limit: int) -> tuple[str, bool]:
    if len(raw) <= limit:
        return raw, False
    return raw[:limit] + "\n...[truncated]\n", True
