/** 云存储单项配置（与 projectConfig tencent_cloud_config / tmp_secret_config 一致） */
export function defaultCloudConfig() {
  return {
    secret_id: '',
    secret_key: '',
    bucket: '',
    app_id: '',
    region: '',
    proxy: ''
  }
}

export function defaultAdminUiForm() {
  return {
    tencent_cloud_config: defaultCloudConfig(),
    tmp_secret_config: defaultCloudConfig(),
    videoLinePrimary: '',
    videoLineSecondary: '',
    livePath: '',
    volcanoVideoDomain: '',
    volcanoVodSpace: '',
    liveWebSocketUrl: '',
    courseDefaultType: '1'
  }
}

/** 加载配置：兼容旧版平铺字段（obsAccessKeyId、cosBucket 等） */
export function normalizeAdminUiConfig(raw) {
  if (!raw || typeof raw !== 'object') {
    return defaultAdminUiForm()
  }
  const form = defaultAdminUiForm()
  Object.keys(form).forEach(key => {
    if (key === 'tencent_cloud_config' || key === 'tmp_secret_config') {
      return
    }
    if (raw[key] !== undefined && raw[key] !== null) {
      form[key] = raw[key]
    }
  })
  if (raw.tencent_cloud_config && typeof raw.tencent_cloud_config === 'object') {
    form.tencent_cloud_config = { ...defaultCloudConfig(), ...raw.tencent_cloud_config }
  }
  if (raw.tmp_secret_config && typeof raw.tmp_secret_config === 'object') {
    form.tmp_secret_config = { ...defaultCloudConfig(), ...raw.tmp_secret_config }
  }
  const tc = form.tencent_cloud_config
  if (raw.cosBucket && !tc.bucket) tc.bucket = raw.cosBucket
  if (raw.cosRegion && !tc.region) tc.region = raw.cosRegion
  const hw = form.tmp_secret_config
  if (raw.obsAccessKeyId && !hw.secret_id) hw.secret_id = raw.obsAccessKeyId
  if (raw.obsSecretAccessKey && !hw.secret_key) hw.secret_key = raw.obsSecretAccessKey
  if (raw.obsBucket && !hw.bucket) hw.bucket = raw.obsBucket
  if (raw.obsServer && !hw.proxy) hw.proxy = raw.obsServer.replace(/^https?:\/\//, '')
  return form
}

/** 供 main.js / login.vue 写入 $runtimeConfig */
export function buildRuntimeConfigFromAdminUi(form) {
  const normalized = normalizeAdminUiConfig(form)
  const tc = normalized.tencent_cloud_config || defaultCloudConfig()
  const hw = normalized.tmp_secret_config || defaultCloudConfig()
  return {
    VUE_APP_OBS_ACCESS_KEY_ID: hw.secret_id || '',
    VUE_APP_OBS_SECRET_ACCESS_KEY: hw.secret_key || '',
    VUE_APP_OBS_SERVER: hw.proxy || '',
    VUE_APP_OBS_BUCKET: hw.bucket || '',
    VUE_APP_VIDEO_LINE_1: normalized.videoLinePrimary || '',
    VUE_APP_VIDEO_LINE_2: normalized.videoLineSecondary || '',
    VUE_APP_VIDEO_URL: normalized.volcanoVideoDomain || '',
    VUE_APP_HSY_SPACE: normalized.volcanoVodSpace || '',
    VUE_APP_LIVE_PATH: normalized.livePath || '/live',
    VUE_APP_COS_BUCKET: tc.bucket || '',
    VUE_APP_LIVE_WS_URL: normalized.liveWebSocketUrl || '',
    VUE_APP_COURSE_DEFAULT: normalized.courseDefaultType || '1',
    VUE_APP_COS_REGION: tc.region || ''
  }
}
