import json

# edited by glg


def sanitize_response_text(raw_text):
    text = str(raw_text or "")
    return text.lstrip("\ufeff")


def parse_json_response(response, label="response"):
    try:
        return response.json()
    except (ValueError, json.JSONDecodeError):
        pass

    raw_bytes = getattr(response, "content", b"") or b""
    text = ""
    if raw_bytes:
        try:
            text = raw_bytes.decode("utf-8-sig")
        except (UnicodeDecodeError, LookupError):
            text = raw_bytes.decode("utf-8", errors="replace")
    else:
        text = str(getattr(response, "text", "") or "")

    text = sanitize_response_text(text).strip()
    if not text:
        raise ValueError(f"{label} kosong atau bukan JSON.")

    try:
        return json.loads(text)
    except (ValueError, json.JSONDecodeError, TypeError) as exc:
        snippet = text[:300].replace("\n", " ")
        raise ValueError(f"{label} bukan JSON valid: {snippet}") from exc
