export const DEFAULT_SPEAKING_API_HOST = 'https://ppt-english-speaking-api.cocorobo.cn'
export const SPEAKING_API_DIALOGUE_PATH = '/api/speaking/dialogue'

type SpeakingApiEnv = {
  readonly [key: string]: string | boolean | undefined
  VITE_SPEAKING_API_HOST?: string
}

function normalizeHost(host: string): string {
  return host.replace(/\/+$/, '')
}

export function getSpeakingApiHost(env: SpeakingApiEnv | undefined = import.meta.env): string {
  const configuredHost = env?.VITE_SPEAKING_API_HOST?.trim()
  return normalizeHost(configuredHost || DEFAULT_SPEAKING_API_HOST)
}

export function getSpeakingApiBaseUrl(env: SpeakingApiEnv | undefined = import.meta.env): string {
  return `${getSpeakingApiHost(env)}${SPEAKING_API_DIALOGUE_PATH}`
}

export function buildSpeakingWsUrl(path: string, env: SpeakingApiEnv | undefined = import.meta.env): string {
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  return getSpeakingApiBaseUrl(env).replace(/^http/, 'ws') + normalizedPath
}
