"""Parse JSON from LLM responses, cleaning think tags and markdown code blocks."""

import json

from strip_think_tags import strip_think_tags
from strip_markdown_codeblock import strip_markdown_codeblock


def parse_llm_json(response: str) -> dict:
    """Parse an LLM response as JSON, cleaning think tags and markdown code blocks first.

    Combines strip_think_tags + strip_markdown_codeblock + json.loads into a
    single pipeline. Raises ValueError with the cleaned text included in the
    message to aid debugging.

    Args:
        response: Raw LLM response string.

    Returns:
        Parsed JSON as a dict.

    Raises:
        ValueError: If the cleaned text is not valid JSON.
    """
    cleaned = strip_think_tags(response)
    cleaned = strip_markdown_codeblock(cleaned)
    try:
        return json.loads(cleaned)
    except json.JSONDecodeError as exc:
        raise ValueError(
            f"parse_llm_json: invalid JSON after cleaning. "
            f"Cleaned text: {cleaned!r}"
        ) from exc
