import { createOpenAI } from "@ai-sdk/openai";
function readFirstNonEmpty(env, keys) {
  for (const key of keys) {
    const value = env[key];
    if (typeof value === "string") {
      const trimmed = value.trim();
      if (trimmed.length > 0) return trimmed;
    }
  }
  return null;
}
function createOpenAICompatibleProvider(preset) {
  if (!preset.id || preset.id.length === 0) {
    throw new Error("[OpenAIAdapter] Preset must have a non-empty id");
  }
  if (!preset.envKeys || preset.envKeys.length === 0) {
    throw new Error(
      `[OpenAIAdapter] Preset "${preset.id}" must declare at least one env key`
    );
  }
  function resolveApiKey(env) {
    return readFirstNonEmpty(env ?? process.env, preset.envKeys);
  }
  function resolveBaseURL(env) {
    const lookup = env ?? process.env;
    if (preset.baseURLEnvKeys && preset.baseURLEnvKeys.length > 0) {
      const override = readFirstNonEmpty(lookup, preset.baseURLEnvKeys);
      if (override) return override;
    }
    return preset.baseURL;
  }
  return {
    id: preset.id,
    name: preset.name,
    envKeys: preset.envKeys,
    defaultModel: preset.defaultModel,
    defaultModels: preset.defaultModels,
    isConfigured(env) {
      return resolveApiKey(env) !== null;
    },
    resolveApiKey,
    getConfiguredEnvKey(env) {
      const lookup = env ?? process.env;
      for (const key of preset.envKeys) {
        const value = lookup[key];
        if (typeof value === "string" && value.trim().length > 0) {
          return key;
        }
      }
      return preset.envKeys[0];
    },
    createModel(options) {
      const baseURL = options.baseURL ?? resolveBaseURL();
      const openai = createOpenAI({
        apiKey: options.apiKey,
        ...baseURL ? { baseURL } : {}
      });
      return openai(options.modelId);
    }
  };
}
export {
  createOpenAICompatibleProvider
};
//# sourceMappingURL=openai.js.map
