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

const unitId = 'SHEP-5-上-Unit2'
const topics = JSON.parse(
  await readFile(new URL('../src/views/Editor/EnglishSpeaking/data/topicDiscussionTasks.json', import.meta.url), 'utf8'),
)
const articles = JSON.parse(
  await readFile(new URL('../src/views/Editor/EnglishSpeaking/data/articleReadingTasks.json', import.meta.url), 'utf8'),
)
const article = articles[unitId][0]

// 模型的所有导入都是 `import type`，转译后被抹除，因此模块自足、可直接在 Node 里跑。
const sourceUrl = new URL('../src/views/Editor/EnglishSpeaking/preview/articleReadingModel.ts', import.meta.url)
const source = await readFile(sourceUrl, 'utf8')
const compiled = ts.transpileModule(source, {
  compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2020 },
}).outputText
const mod = await import(`data:text/javascript,${encodeURIComponent(compiled)}#${Math.random()}`)

const empty = mod.buildEmptyArticleConfig('五年级')
assert.deepEqual(empty, {
  type: 'article',
  grade: '五年级',
  title: '',
  content: '',
  practice: { mode: 'time', duration: 10 },
  evaluation: { showReport: true },
})

const fromTask = mod.buildArticleConfig(article, '五年级')
assert.equal(fromTask.type, 'article')
assert.equal(fromTask.grade, '五年级')
assert.equal(fromTask.title, 'A Day at the Zoo')
assert.equal(fromTask.content, article.content)

assert.equal(mod.scoreToStars(0), 0)
assert.equal(mod.scoreToStars(79), 3.95)
assert.equal(mod.scoreToStars(100), 5)

const allTasks = [...topics[unitId], article]
assert.equal(mod.filterSpeakingTasks(allTasks, 'all').length, 5)
assert.equal(mod.filterSpeakingTasks(allTasks, 'topic-discussion').length, 4)
assert.equal(mod.filterSpeakingTasks(allTasks, 'article-reading').length, 1)

assert.equal(mod.isFinalReportReady({ paragraphs: [{ status: 'generating' }], overallStatus: null }), false)
assert.equal(mod.isFinalReportReady({ paragraphs: [{ status: 'completed' }], overallStatus: null }), true)
assert.equal(mod.isFinalReportReady({ paragraphs: [{ status: 'failed' }], overallStatus: 'failed' }), true)

assert.equal(mod.pollDelayMs(0), 1000)
assert.equal(mod.pollDelayMs(5), 8000)
