import assert from 'node:assert/strict'
import test from 'node:test'
import { createRuntimeTimelineState, reduceRuntimeTimeline, runtimeTimelineStatusLabel } from './runtimeTimeline.js'

test('runtime timeline keeps status while heartbeat updates liveness', () => {
  let state = createRuntimeTimelineState()
  state = reduceRuntimeTimeline(state, { eventId: 1, t: 'status', v: '正在调用 Codex', ts: '2026-07-19T16:00:00.000Z' })
  state = reduceRuntimeTimeline(state, { eventId: 2, t: 'heartbeat', ts: '2026-07-19T16:00:05.000Z', elapsedMs: 5000 })

  assert.equal(state.status, '正在调用 Codex')
  assert.equal(state.heartbeatAt, '2026-07-19T16:00:05.000Z')
  assert.equal(state.elapsedMs, 5000)
})

test('runtime timeline coalesces deltas and preserves reasoning and tool order', () => {
  let state = createRuntimeTimelineState()
  const events = [
    { eventId: 1, t: 'reasoning_summary', v: '先读取文件' },
    { eventId: 2, t: 'delta', v: '你好' },
    { eventId: 3, t: 'delta', v: '，世界' },
    { eventId: 4, t: 'tool_call', name: 'read_file', args: { path: 'SOP.md' } },
    { eventId: 5, t: 'tool_result', name: 'read_file', result: 'ok' },
  ]
  for (const event of events) state = reduceRuntimeTimeline(state, event)

  assert.deepEqual(state.entries.map(entry => entry.type), ['reasoning', 'assistant', 'tool_call', 'tool_result'])
  assert.equal(state.entries[1].content, '你好，世界')
})

test('runtime timeline deduplicates replayed events and artifacts', () => {
  let state = createRuntimeTimelineState()
  const event = { eventId: 7, t: 'artifact', artifact: { name: 'REPORT.md', path: 'REPORT.md' } }
  state = reduceRuntimeTimeline(state, event)
  state = reduceRuntimeTimeline(state, event)

  assert.equal(state.entries.length, 1)
  assert.equal(state.artifacts.length, 1)
  assert.equal(state.lastEventId, 7)
})

test('completed timeline no longer looks like it is still executing', () => {
  let state = reduceRuntimeTimeline(createRuntimeTimelineState(), { t: 'status', v: 'QODER Cloud Agent 正在执行' })
  state = reduceRuntimeTimeline(state, { t: 'done', state: 'completed' })
  assert.equal(runtimeTimelineStatusLabel(state, false), '运行时已完成')
})
