/**
 * MCP tool helper that calls the WhatsApp Hono routes on localhost and
 * surfaces structured error bodies on non-2xx responses.
 *
 * Why this exists separate from `index.ts`: the previous inline helper at
 * `index.ts:36-38` discarded the response body on every non-2xx, returning
 * only `HTTP <status>: <statusText>`. The Hono route emits validation
 * details (e.g. `{ ok: false, error: "Unrecognized keys: mode, agent" }`)
 * that the agent needs to self-correct. Without surfacing them, every
 * 400 looks identical and the agent retries blindly until max-turns
 * (root cause).
 */
export async function callApi(baseUrl, path, method = "POST", body) {
    const res = await fetch(`${baseUrl}${path}`, {
        method,
        headers: body ? { "Content-Type": "application/json" } : undefined,
        body: body ? JSON.stringify(body) : undefined,
    });
    if (res.ok)
        return res.json();
    const fallback = `HTTP ${res.status}: ${res.statusText} (${method} ${path})`;
    let text;
    try {
        text = await res.text();
    }
    catch {
        return { ok: false, error: fallback };
    }
    if (!text)
        return { ok: false, error: fallback };
    try {
        const parsed = JSON.parse(text);
        if (typeof parsed.error === "string" && parsed.error.trim()) {
            return { ok: false, error: parsed.error };
        }
        return { ok: false, error: fallback };
    }
    catch {
        return { ok: false, error: fallback };
    }
}
//# sourceMappingURL=call-api.js.map