import { describe, expect, it } from 'vitest'
import type { TaskArtifact } from '../../types'
import { extractToolOutputArtifact, normalizeArtifactFileType } from './previewUtils'

describe('normalizeArtifactFileType', () => {
  it('normalizes common mime types', () => {
    expect(normalizeArtifactFileType('text/markdown')).toBe('md')
    expect(normalizeArtifactFileType('image/svg+xml')).toBe('svg')
    expect(
      normalizeArtifactFileType(
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      ),
    ).toBe('pptx')
  })

  it('falls back to file extension', () => {
    expect(normalizeArtifactFileType('', 'report.csv')).toBe('csv')
    expect(normalizeArtifactFileType(undefined, undefined, '/tmp/demo.py')).toBe('py')
  })
})

describe('extractToolOutputArtifact', () => {
  const baseArtifact: TaskArtifact = {
    path: 'tool-call-1',
    file_name: '工具调用',
    file_type: 'tool_call',
    event_type: 'tool_call',
    tool_name: 'file_create',
  }

  it('extracts remote file artifacts from tool_output', () => {
    const artifact = extractToolOutputArtifact({
      ...baseArtifact,
      tool_output: {
        path: '/upload/result/index.html',
        file_name: 'index.html',
        file_type: 'text/html',
      },
    })

    expect(artifact).toEqual({
      path: '/upload/result/index.html',
      file_name: 'index.html',
      file_type: 'html',
      content: undefined,
      url: undefined,
      task_id: undefined,
    })
  })

  it('extracts inline preview content when only file_type and content exist', () => {
    const artifact = extractToolOutputArtifact({
      ...baseArtifact,
      tool_output: {
        file_name: 'notes.md',
        file_type: 'text/markdown',
        content: '# Title',
      },
    })

    expect(artifact).toEqual({
      path: '',
      file_name: 'notes.md',
      file_type: 'md',
      content: '# Title',
      url: undefined,
      task_id: undefined,
    })
  })

  it('ignores non-file tool outputs', () => {
    expect(
      extractToolOutputArtifact({
        ...baseArtifact,
        tool_output: {
          status: 'ok',
          message: 'done',
        },
      }),
    ).toBeNull()
  })
})
