"""
Robust JSON extraction from LLM responses.

Lives in core/ so both brain/ and analysis/ can import it without
violating the V16 layering rule (analysis -> brain forbidden).
"""

from __future__ import annotations

import re


_JSON_FENCE_RE = re.compile(
    r"```(?:json)?\s*(.*?)\s*```",
    re.DOTALL | re.IGNORECASE,
)


def extract_json_from_response(text: str) -> str:
    """
    Extract a JSON candidate from a Claude / LLM response.

    Strategy:
      1) First fenced block ``` ... ``` or ```json ... ``` anywhere
         in the text (handles prose before/after, case-insensitive).
      2) Fallback: substring from the first '{' to the last '}'
         (rfind, not balanced — sufficient for object-shaped responses).
      3) Last resort: the stripped raw text.

    Empty / whitespace-only input returns "".
    """
    if not text or not text.strip():
        return ""
    stripped = text.strip()

    m = _JSON_FENCE_RE.search(stripped)
    if m:
        return m.group(1).strip()

    start = stripped.find("{")
    end = stripped.rfind("}")
    if start != -1 and end > start:
        return stripped[start:end + 1]

    return stripped
