import { getSystemConfigSync, fetchSystemConfig } from '../../service/systemConfig'
import { SystemModels } from './models'

export interface BuiltInProviderConfig {
  id: string;
  apiKey: string;
  apiHost?: string;
  enabled: boolean;
  ossConfig?: {
    accessKeyId: string;
    accessKeySecret: string;
    bucket: string;
    region: string;
  };
}

function buildBuiltinProviders(): Record<string, BuiltInProviderConfig> {
  const sysConfig = getSystemConfigSync()

  return {
    builtInAliyun: {
      id: 'builtInAliyun',
      apiKey: sysConfig.aliyun_bailian_api_key || '',
      apiHost: sysConfig.aliyun_bailian_base_url || 'https://dashscope.aliyuncs.com/api/v1',
      enabled: true,
      ossConfig: {
        accessKeyId: sysConfig.aliyun_oss_access_key_id || '',
        accessKeySecret: sysConfig.aliyun_oss_access_key_secret || '',
        bucket: sysConfig.aliyun_oss_bucket || '',
        region: sysConfig.aliyun_oss_region || 'oss-cn-beijing'
      }
    },

    builtInDoubao: {
      id: 'builtInDoubao',
      apiKey: sysConfig.volcengine_api_key || '',
      apiHost: '',
      enabled: true
    }
  }
}

export const BUILTIN_PROVIDERS: Record<string, BuiltInProviderConfig> = buildBuiltinProviders()

export function refreshBuiltinProviders(): void {
  const providers = buildBuiltinProviders()
  Object.assign(BUILTIN_PROVIDERS, providers)
  syncDoubaoModel()
}

function syncDoubaoModel(): void {
  const sysConfig = getSystemConfigSync()
  const modelId = sysConfig.volcengine_model || 'doubao-seed-2-0-mini-260215'
  const models = SystemModels.builtInDoubao
  if (models && models.length > 0) {
    models[0].id = modelId
    models[0].name = modelId
    models[0].group = modelId
  }
}

export async function initBuiltinProviders(): Promise<void> {
  await fetchSystemConfig()
  refreshBuiltinProviders()
}

export function isBuiltInProvider(providerId: string): boolean {
  return providerId.startsWith('builtIn');
}

export function getBuiltInConfig(providerId: string): BuiltInProviderConfig | null {
  return BUILTIN_PROVIDERS[providerId] || null;
}
