/**
 * OpenAI Provider Definition
 */

import { createOpenAI } from '@ai-sdk/openai';
import { createQwen } from 'qwen-ai-provider-v5';
import type { ProviderInfo, ProviderFactory } from '../types.js';

export const openaiProvider: ProviderInfo = {
  id: 'openai',
  name: 'OpenAI',
  description: 'GPT models by OpenAI (also supports OpenAI-compatible APIs)',
  builtin: true,
  apiKeyEnvVar: 'OPENAI_API_KEY',
  models: [
    {
      id: 'gpt-4o',
      name: 'GPT-4o',
      capabilities: { vision: true, functionCalling: true, streaming: true },
      contextWindow: 128000,
      maxOutput: 16384,
    },
    {
      id: 'gpt-4o-mini',
      name: 'GPT-4o Mini',
      capabilities: { vision: true, functionCalling: true, streaming: true },
      contextWindow: 128000,
      maxOutput: 16384,
    },
    {
      id: 'gpt-4-turbo',
      name: 'GPT-4 Turbo',
      capabilities: { vision: true, functionCalling: true, streaming: true },
      contextWindow: 128000,
      maxOutput: 4096,
    },
    {
      id: 'o1',
      name: 'o1',
      capabilities: { vision: false, functionCalling: false, streaming: true },
      contextWindow: 200000,
      maxOutput: 100000,
    },
    {
      id: 'o1-mini',
      name: 'o1 Mini',
      capabilities: { vision: false, functionCalling: false, streaming: true },
      contextWindow: 128000,
      maxOutput: 65536,
    },
  ],
  allowCustomModels: true,
};

/**
 * 检查 baseUrl 是否为阿里云百炼/DashScope
 */
function isDashScopeUrl(baseUrl?: string): boolean {
  if (!baseUrl) return false;
  return baseUrl.includes('dashscope');
}

export const openaiFactory: ProviderFactory = ({ apiKey, baseUrl }) => {
  // 如果是百炼的 URL，使用 qwen provider
  if (isDashScopeUrl(baseUrl)) {
    const client = createQwen({ apiKey, baseURL: baseUrl });
    return (model) => client(model);
  }
  const client = createOpenAI({ apiKey, baseURL: baseUrl });
  return (model) => client(model);
};
