"""Centralized Parsing Utility for AI JSON Responses."""
import re
import json

def extract_json_payload(raw):
    """Accept raw JSON, fenced JSON, or bash heredoc-wrapped JSON."""
    s = (raw or "").strip()
    if not s: return None
    s = re.sub(r"^```[a-zA-Z0-9_-]*\s*\n", "", s)
    s = re.sub(r"\n```\s*$", "", s)
    m = re.search(r"<<-?'?([A-Za-z_][A-Za-z0-9_]*)'?\s*\n(.*?)\n\1\s*$", s, re.DOTALL)
    if m: s = m.group(2).strip()
    start = s.find("{")
    if start < 0: return None
    depth = 0
    in_str = False
    esc = False
    for i in range(start, len(s)):
        c = s[i]
        if esc:
            esc = False
            continue
        if c == "\\":
            esc = True
            continue
        if c == '"':
            in_str = not in_str
            continue
        if in_str:
            continue
        if c == "{":
            depth += 1
        elif c == "}":
            depth -= 1
            if depth == 0:
                try:
                    return json.loads(s[start:i+1])
                except json.JSONDecodeError:
                    return None
    return None
