import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import ts from 'typescript'

const sourceUrl = new URL('../src/views/Editor/EnglishSpeaking/services/speakingApiConfig.ts', import.meta.url)
const source = await readFile(sourceUrl, 'utf8')

async function loadConfig(env = {}) {
  const compiled = ts.transpileModule(source.replaceAll('import.meta.env', JSON.stringify(env)), {
    compilerOptions: {
      module: ts.ModuleKind.ESNext,
      target: ts.ScriptTarget.ES2020,
    },
  }).outputText

  return import(`data:text/javascript,${encodeURIComponent(compiled)}#${Math.random()}`)
}

const defaults = await loadConfig()

assert.equal(
  defaults.FALLBACK_SPEAKING_API_HOST,
  'https://ppt-english-speaking-api.cocorobo.cn',
)

assert.equal(
  defaults.SPEAKING_DIALOGUE_API_BASE_URL,
  'https://ppt-english-speaking-api.cocorobo.cn/api/speaking/dialogue',
)

assert.equal(
  defaults.SPEAKING_CONFIG_API_BASE_URL,
  'https://ppt-english-speaking-api.cocorobo.cn/api/speaking/config',
)

assert.equal(
  defaults.SPEAKING_TRANSPORT,
  'websocket',
)

assert.equal(
  defaults.buildSpeakingWsUrl('/speak-stream'),
  'wss://ppt-english-speaking-api.cocorobo.cn/api/speaking/dialogue/speak-stream',
)

const custom = await loadConfig({
  VITE_SPEAKING_API_HOST: 'https://example.com/',
  VITE_SPEAKING_TRANSPORT: 'http',
})

assert.equal(
  custom.SPEAKING_DIALOGUE_API_BASE_URL,
  'https://example.com/api/speaking/dialogue',
)

assert.equal(
  custom.SPEAKING_CONFIG_API_BASE_URL,
  'https://example.com/api/speaking/config',
)

assert.equal(
  custom.SPEAKING_TRANSPORT,
  'http',
)

assert.equal(
  defaults.SPEAKING_ARTICLE_API_BASE_URL,
  'https://ppt-english-speaking-api.cocorobo.cn/api/speaking/article',
)

assert.equal(
  defaults.buildArticleWsUrl('/session/s1/paragraph/0/stream'),
  'wss://ppt-english-speaking-api.cocorobo.cn/api/speaking/article/session/s1/paragraph/0/stream',
)

assert.equal(
  custom.SPEAKING_ARTICLE_API_BASE_URL,
  'https://example.com/api/speaking/article',
)
