/**
 * AI Provider 工厂
 * 支持多种 AI 提供商
 */

const { createOpenAICompatible } = require('@ai-sdk/openai-compatible');
const { createOpenAI } = require('@ai-sdk/openai');
const { createAnthropic } = require('@ai-sdk/anthropic');

/**
 * 默认提供商配置
 */
const DEFAULT_PROVIDERS = {
  openai: {
    name: 'OpenAI',
    baseURL: 'https://api.openai.com/v1',
  },
  ollama: {
    name: 'Ollama',
    baseURL: 'http://localhost:11434/v1',
  },
  lmstudio: {
    name: 'LM Studio',
    baseURL: 'http://localhost:1234/v1',
  },
  deepseek: {
    name: 'DeepSeek',
    baseURL: 'https://api.deepseek.com/v1',
  },
  anthropic: {
    name: 'Anthropic',
    baseURL: 'https://api.anthropic.com/v1',
  },
  minimax: {
    name: 'MiniMax',
    baseURL: 'https://api.minimaxi.com/v1',
  },
};

/**
 * 创建 AI 客户端
 * @param {Object} config - 配置
 * @param {string} config.provider - 提供商名称
 * @param {string} config.model - 模型名称
 * @param {string} config.apiKey - API 密钥
 * @param {string} [config.baseURL] - 自定义 API 地址
 */
function createAI(config) {
  const { provider, model, apiKey, baseURL } = config;
  const providerName = (provider || 'deepseek').toLowerCase();
  // 检查是否是预定义提供商
  if (DEFAULT_PROVIDERS[providerName]) {
    const providerConfig = DEFAULT_PROVIDERS[providerName];
    return createOpenAICompatible({
      name: providerConfig.name,
      baseURL: baseURL || providerConfig.baseURL,
      apiKey: apiKey || 'dummy-key',
      headers:
        provider === 'anthropic'
          ? {
              'x-api-key': apiKey,
              'anthropic-version': '2023-06-01',
            }
          : undefined,
      models: {
        default: {
          id: model || 'deepseek-chat',
          streamOptions: {
            includeUsage: true,
          },
        },
      },
    });
  }

  // 自定义提供商
  return createOpenAICompatible({
    name: providerName || 'Custom',
    baseURL: baseURL,
    apiKey: apiKey || 'dummy-key',
    models: {
      default: {
        id: model || 'gpt-4',
      },
    },
  });
}

/**
 * 获取可用提供商列表
 */
function getAvailableProviders() {
  return Object.entries(DEFAULT_PROVIDERS).map(([key, value]) => ({
    id: key,
    name: value.name,
    baseURL: value.baseURL,
  }));
}

/**
 * 创建模型实例
 * @param {string} model - 模型名称
 * @param {Object} provider - Provider 实例
 */
function createModel(model, provider) {
  return provider(model);
}

module.exports = {
  createAI,
  createModel,
  getAvailableProviders,
  DEFAULT_PROVIDERS,
};
