// src/sessions/mcp-auth.ts
function injectMcpAuthHeaders(agent, vaultEntries) {
  const mcpServers = agent.mcp_servers;
  if (!mcpServers || mcpServers.length === 0) return agent;
  if (vaultEntries.length === 0) return agent;
  const serverLookup = /* @__PURE__ */ new Map();
  for (let i = 0; i < mcpServers.length; i++) {
    const name = mcpServers[i].name;
    serverLookup.set(name.toUpperCase().replace(/-/g, "_"), i);
  }
  let mutated = false;
  const merged = {};
  for (const { key, value } of vaultEntries) {
    const authMatch = /^MCP_AUTH_(.+)$/i.exec(key);
    if (authMatch) {
      const norm = authMatch[1].toUpperCase();
      const idx = serverLookup.get(norm);
      if (idx !== void 0) {
        merged[idx] = merged[idx] ?? {};
        merged[idx]["Authorization"] = `Bearer ${value}`;
        mutated = true;
      }
      continue;
    }
    const headerPrefix = /^MCP_HEADER_/i;
    if (headerPrefix.test(key)) {
      const rest = key.replace(headerPrefix, "");
      const parts = rest.split("_");
      for (let i = parts.length - 1; i >= 1; i--) {
        const serverPart = parts.slice(0, i).join("_").toUpperCase();
        const headerPart = parts.slice(i).join("-");
        const idx = serverLookup.get(serverPart);
        if (idx !== void 0) {
          merged[idx] = merged[idx] ?? {};
          merged[idx][headerPart] = value;
          mutated = true;
          break;
        }
      }
    }
  }
  if (!mutated) return agent;
  const newServers = mcpServers.map((server, idx) => {
    const headers = merged[idx];
    if (!headers) return server;
    return {
      ...server,
      headers: { ...server.headers, ...headers }
    };
  });
  return { ...agent, mcp_servers: newServers };
}

export {
  injectMcpAuthHeaders
};
