import {
  getConfig
} from "./chunk-2MAQ6JFL.js";
import {
  ApiError
} from "./chunk-EZYKRG4W.js";

// src/proxy/forward.ts
var ANTHROPIC_BASE = "https://api.anthropic.com";
var BETA_HEADER = "managed-agents-2026-04-01";
async function forwardToAnthropic(request, path, opts) {
  const cfg = getConfig();
  const apiKey = opts?.apiKey ?? cfg.anthropicApiKey;
  if (!apiKey) {
    throw new ApiError(
      500,
      "server_error",
      "ANTHROPIC_API_KEY is required for the anthropic proxy backend"
    );
  }
  const upstreamPath = path.startsWith("/anthropic/") ? path.slice("/anthropic".length) : path;
  const url = new URL(upstreamPath, ANTHROPIC_BASE);
  const origUrl = new URL(request.url);
  url.search = origUrl.search;
  const beta = BETA_HEADER;
  const headers = new Headers();
  headers.set("x-api-key", apiKey);
  headers.set("anthropic-version", "2023-06-01");
  headers.set("anthropic-beta", beta);
  const ct = request.headers.get("content-type");
  if (ct) headers.set("content-type", ct);
  const lastId = request.headers.get("last-event-id");
  if (lastId) headers.set("last-event-id", lastId);
  const idem = request.headers.get("idempotency-key") || request.headers.get("Idempotency-Key");
  if (idem) headers.set("idempotency-key", idem);
  const accept = request.headers.get("accept");
  if (accept) headers.set("accept", accept);
  const isMultipart = (ct ?? "").toLowerCase().startsWith("multipart/");
  let body;
  if (request.method !== "GET" && request.method !== "HEAD") {
    if (opts?.body !== void 0) {
      body = opts.body;
    } else if (isMultipart && request.body) {
      body = request.body;
    } else {
      body = await request.text();
    }
  }
  const fetchInit = {
    method: request.method,
    headers,
    body,
    signal: request.signal
  };
  if (body && typeof body !== "string") {
    fetchInit.duplex = "half";
  }
  const res = await fetch(url.toString(), fetchInit);
  const HOP_BY_HOP = /* @__PURE__ */ new Set([
    "connection",
    "keep-alive",
    "transfer-encoding",
    "te",
    "trailer",
    "upgrade",
    "content-encoding",
    // Node fetch auto-decompresses; forwarding this causes ERR_CONTENT_DECODING_FAILED
    "content-length"
    // Length changes after decompression
  ]);
  const responseHeaders = new Headers();
  for (const [k, v] of res.headers) {
    if (!HOP_BY_HOP.has(k.toLowerCase())) {
      responseHeaders.set(k, v);
    }
  }
  return new Response(res.body, {
    status: res.status,
    headers: responseHeaders
  });
}
function validateAnthropicProxy() {
  const cfg = getConfig();
  if (!cfg.anthropicApiKey) {
    return "anthropic proxy backend requires ANTHROPIC_API_KEY to be set";
  }
  return null;
}

export {
  forwardToAnthropic,
  validateAnthropicProxy
};
