import dayjs from 'dayjs';

export type AiProvider = 'OPENAI' | 'DEEPSEEK' | 'OPENAI_COMPATIBLE';

export const PROVIDER_OPTIONS: { value: AiProvider; label: string }[] = [
  { value: 'DEEPSEEK', label: 'DeepSeek' },
  { value: 'OPENAI', label: 'OpenAI' },
  { value: 'OPENAI_COMPATIBLE', label: 'OpenAI 兼容' },
];

// aislop-ignore-next-line: hardcoded-url -- OpenAI 官方 API 固定端点
export const OPENAI_DEFAULT_BASE_URL = 'https://api.openai.com/v1';
// aislop-ignore-next-line: hardcoded-url -- DeepSeek 官方 API 固定端点
export const DEEPSEEK_DEFAULT_BASE_URL = 'https://api.deepseek.com';

export const PROVIDER_DEFAULTS: Record<AiProvider, string> = {
  OPENAI: OPENAI_DEFAULT_BASE_URL,
  DEEPSEEK: DEEPSEEK_DEFAULT_BASE_URL,
  OPENAI_COMPATIBLE: '',
} as const;

export const FIXED_PROVIDERS: AiProvider[] = ['OPENAI', 'DEEPSEEK'];

export function formatDateTime(iso: string | null): string {
  if (!iso) return '-';
  return dayjs(iso).format('YYYY-MM-DD HH:mm:ss');
}

export function sourceLabel(source: string): string {
  switch (source) {
    case 'database':
      return '数据库';
    case 'environment':
      return '环境变量';
    default:
      return '未配置';
  }
}

export function sourceColor(source: string): 'green' | 'blue' | 'default' {
  switch (source) {
    case 'database':
      return 'green';
    case 'environment':
      return 'blue';
    default:
      return 'default';
  }
}

export function shouldAutoSwapBaseUrl(
  provider: AiProvider,
  currentBaseUrl: string,
  lastProvider: AiProvider | null,
): { baseUrl: string; shouldSwap: boolean } {
  if (!lastProvider) {
    return { baseUrl: PROVIDER_DEFAULTS[provider], shouldSwap: true };
  }
  const prevDefault = PROVIDER_DEFAULTS[lastProvider];
  if (!currentBaseUrl || currentBaseUrl === prevDefault) {
    return { baseUrl: PROVIDER_DEFAULTS[provider], shouldSwap: true };
  }
  return { baseUrl: currentBaseUrl, shouldSwap: false };
}
