import type { BusinessParams, SsmlConfig, SystemConfig } from './types'
import { isIos } from '@minto-ai/tools'
import TtsController from './tts-controller'

import 'core-js'

let systemConfig: SystemConfig

const defaultSystemConfig: SystemConfig = {
  ttsRequestBaseUrl: 'wss://audio.workbrain.cn/tts',
}

const defaultBusinessParams: BusinessParams = {
  voice_type: 'zh_female_daimengchuanmei_moon_bigtts',
  text_type: 'plain',
  speed_ratio: 1,
  volume_ratio: 1,
  pitch_ratio: 1,
  language: 'cn',
  provider: '0',
  cache: false,
  stream: true,
}

const defaultSsmlConfig: SsmlConfig = {
  pronunciationRules: [],
}

if (isIos()) {
  Object.assign(defaultBusinessParams, {
    encoding: 'pcm',
    output_format: 'base64',
  })
}

/**
 * 用于管理文本转语音的配置和创建实例
 */
export default {
  /**
   * 配置系统参数。
   * @param {Partial<SystemConfig>} [_systemConfig] - 系统配置参数。
   * @returns {object} 返回当前对象，支持链式调用。
   */
  config(_systemConfig: Partial<SystemConfig>) {
    systemConfig = {
      ...defaultSystemConfig,
      ..._systemConfig,
    }

    return this
  },

  /**
   * 创建文本转语音控制器实例。
   * @param {Partial<BusinessParams>} [_businessParams] - 业务参数，默认为空对象。
   * @param {Partial<SsmlConfig>} [_ssmlConfig] - SSML配置参数，默认为空对象。
   * @returns {TtsController} 返回TtsController实例。s
   */
  create(_businessParams: Partial<BusinessParams> = {}, _ssmlConfig: Partial<SsmlConfig> = {}): TtsController {
    const businessParams = {
      ...defaultBusinessParams,
      ..._businessParams,
    }

    const ssmlConfig = {
      ...defaultSsmlConfig,
      ..._ssmlConfig,
    }

    // 使用的是巴山大峡谷大模型，需要传递 output_format: 'url',获取mp3链接
    if (isIos() && _businessParams.provider === '100') {
      Object.assign(businessParams, {
        encoding: 'mp3',
        output_format: 'url',
      })
    }

    // 巴山大峡谷大模型不支持ssml，需要传递 text_type: 'plain'
    if (_businessParams.provider === '100') {
      businessParams.text_type = 'plain'
    }

    return new TtsController(systemConfig, businessParams, ssmlConfig)
  },
}
