export const FALLBACK_SPEAKING_API_HOST = 'https://ppt-english-speaking-api.cocorobo.cn'

// 优先级：容器运行时注入的 config.js > 构建期 .env 的 VITE_* > 硬编码兜底。
// config.js 在本地 dev 与现有构建部署下都是空对象，因此这两种场景行为不变。
const RUNTIME_SPEAKING_API_HOST = window.__APP_CONFIG__?.SPEAKING_API_HOST
const ENV_SPEAKING_API_HOST = (RUNTIME_SPEAKING_API_HOST || import.meta.env.VITE_SPEAKING_API_HOST)?.trim()
const SPEAKING_API_HOST = (ENV_SPEAKING_API_HOST || FALLBACK_SPEAKING_API_HOST).replace(/\/+$/, '')

export const SPEAKING_DIALOGUE_API_BASE_URL = `${SPEAKING_API_HOST}/api/speaking/dialogue`
export const SPEAKING_CONFIG_API_BASE_URL = `${SPEAKING_API_HOST}/api/speaking/config`
export const SPEAKING_ARTICLE_API_BASE_URL = `${SPEAKING_API_HOST}/api/speaking/article`

export type SpeakTransport = 'websocket' | 'http'

const ENV_SPEAKING_TRANSPORT = import.meta.env.VITE_SPEAKING_TRANSPORT?.trim().toLowerCase()

export const SPEAKING_TRANSPORT: SpeakTransport = ENV_SPEAKING_TRANSPORT === 'http' ? 'http' : 'websocket'

export function buildSpeakingWsUrl(path: string): string {
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  return `${SPEAKING_DIALOGUE_API_BASE_URL.replace(/^http/, 'ws')}${normalizedPath}`
}

export function buildArticleWsUrl(path: string): string {
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  return `${SPEAKING_ARTICLE_API_BASE_URL.replace(/^http/, 'ws')}${normalizedPath}`
}
