import { renderHook } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { resultTags, useFinalResultsSync } from '../../../src/pages/runUi'

describe('resultTags', () => {
  it('turns raw result fields into explicit semantic markers', () => {
    const tags = resultTags({ caseKind: 'risk', mode: 'single_turn', executionStatus: 'completed', verdict: 'pass' })
    expect(tags).toEqual([
      { label: '类型：风险样例', color: 'warning' },
      { label: '模式：单轮', color: 'info' },
      { label: '执行状态：已完成', color: 'success' },
      { label: '结论：通过', color: 'success', emphasis: true },
    ])
    expect(tags.filter((tag) => tag.emphasis)).toHaveLength(1)
  })

  it('keeps unknown backend values visible', () => {
    expect(resultTags({ caseKind: 'new-kind', mode: 'new-mode', executionStatus: 'new-status', verdict: null }).map((tag) => tag.label)).toEqual([
      '类型：new-kind', '模式：new-mode', '执行状态：new-status', '结论：未仲裁',
    ])
  })

  it('distinguishes execution errors and judge format errors', () => {
    expect(resultTags({ caseKind: 'control', mode: 'tool', executionStatus: 'error', verdict: null }).slice(-2).map((tag) => tag.label)).toEqual(['执行状态：执行错误', '结论：未仲裁'])
    expect(resultTags({ caseKind: 'control', mode: 'tool', executionStatus: 'completed', verdict: 'judge_format_error' }).at(-1)?.label).toBe('结论：裁判格式错误')
  })
})

describe('useFinalResultsSync', () => {
  it('fetches results once when a run enters its terminal state', () => {
    const refetch = vi.fn()
    const { rerender } = renderHook(
      ({ terminal }) => useFinalResultsSync(terminal, refetch),
      { initialProps: { terminal: false } },
    )

    expect(refetch).not.toHaveBeenCalled()
    rerender({ terminal: true })
    expect(refetch).toHaveBeenCalledTimes(1)
    rerender({ terminal: true })
    expect(refetch).toHaveBeenCalledTimes(1)
  })
})
