import {
  disableUpstreamKey,
  selectNextUpstreamKey
} from "./chunk-2KDG4PKE.js";
import {
  listEntries
} from "./chunk-JU6ELMEH.js";
import {
  getSession
} from "./chunk-SEGKFEG5.js";
import {
  getConfig
} from "./chunk-2MAQ6JFL.js";
import {
  isAnthropicOAuthToken
} from "./chunk-ZX44HT4Y.js";

// src/providers/upstream-keys.ts
var CONSECUTIVE_FAIL_THRESHOLD = 3;
var SUPPORTED_PROVIDERS = ["anthropic", "openai", "gemini"];
var g = globalThis;
if (!g.__caUpstreamKeyFailures) g.__caUpstreamKeyFailures = /* @__PURE__ */ new Map();
var failures = g.__caUpstreamKeyFailures;
function rejectOAuth(provider, value) {
  if (!value) return null;
  if (provider === "anthropic" && isAnthropicOAuthToken(value)) return null;
  return value;
}
var VAULT_KEY_FOR = {
  anthropic: "ANTHROPIC_API_KEY",
  openai: "OPENAI_API_KEY",
  gemini: "GEMINI_API_KEY"
};
function configKeyFor(provider) {
  const cfg = getConfig();
  switch (provider) {
    case "anthropic":
      return cfg.anthropicApiKey;
    case "openai":
      return cfg.openAiApiKey;
    case "gemini":
      return cfg.geminiApiKey;
  }
}
function resolveProviderKey(provider, opts = {}) {
  const vaultKeyName = VAULT_KEY_FOR[provider];
  let vaultIds = opts.vaultIds;
  if (!vaultIds && opts.sessionId) {
    const session = getSession(opts.sessionId);
    vaultIds = session?.vault_ids ?? void 0;
  }
  if (vaultIds?.length) {
    for (const vid of vaultIds) {
      const entries = listEntries(vid);
      const found = entries.find((e) => e.key === vaultKeyName);
      const clean2 = rejectOAuth(provider, found?.value);
      if (clean2) return { value: clean2, poolId: null };
    }
  }
  const pooled = selectNextUpstreamKey(provider);
  if (pooled) {
    const clean2 = rejectOAuth(provider, pooled.value);
    if (clean2) return { value: clean2, poolId: pooled.id };
  }
  const clean = rejectOAuth(provider, configKeyFor(provider));
  if (clean) return { value: clean, poolId: null };
  return null;
}
function resolveAnthropicKey(opts = {}) {
  return resolveProviderKey("anthropic", opts);
}
function reportUpstreamFailure(poolId) {
  if (!poolId) return;
  const count = (failures.get(poolId) ?? 0) + 1;
  failures.set(poolId, count);
  if (count >= CONSECUTIVE_FAIL_THRESHOLD) {
    disableUpstreamKey(poolId);
    failures.delete(poolId);
  }
}
function reportUpstreamSuccess(poolId) {
  if (!poolId) return;
  failures.delete(poolId);
}

export {
  SUPPORTED_PROVIDERS,
  resolveProviderKey,
  resolveAnthropicKey,
  reportUpstreamFailure,
  reportUpstreamSuccess
};
