import assert from 'node:assert/strict'
import test from 'node:test'

import {
  buildApplicationFieldsFromOntology,
  expandApplicationTimeWithDays,
  resolveApplicationReason,
  resolveApplicationTimeRange,
  resolvePromptField
} from '../src/utils/expenseApplicationOntology.js'

const structuredApplicationPrompt = [
  '发生时间：2026-05-25',
  '地点：上海',
  '事由：支撑国网服务器部署',
  '天数：3天'
].join('\n')

test('expense application fields use labeled reason and filter resolved missing slots', () => {
  const fields = buildApplicationFieldsFromOntology(
    {
      scenario: 'expense',
      intent: 'draft',
      entities: [],
      time_range: {},
      missing_slots: ['time_range', 'location', 'reason', 'amount']
    },
    structuredApplicationPrompt,
    { name: '申请员工', departmentName: '交付部' }
  )

  assert.equal(fields.timeRange, '2026-05-25 至 2026-05-27')
  assert.equal(fields.expenseTypeCode, 'travel')
  assert.equal(fields.expenseTypeLabel, '差旅费')
  assert.equal(fields.location, '上海')
  assert.equal(fields.reason, '支撑国网服务器部署')
  assert.deepEqual(
    fields.missingSlots.map((item) => item.key),
    ['amount']
  )
})

test('expense application prompt field parser supports multiline labels', () => {
  assert.equal(resolvePromptField(structuredApplicationPrompt, ['事由']), '支撑国网服务器部署')
  assert.equal(resolveApplicationReason(structuredApplicationPrompt), '支撑国网服务器部署')
})

test('expense application reason prefers model entity and strips context fragments', () => {
  assert.equal(
    resolveApplicationReason(
      '发生时间：，去九江出差3天，服务美团业务部署',
      {
        entities: [
          { type: 'location', value: '九江', normalized_value: '九江' },
          { type: 'reason', value: '服务美团业务部署', normalized_value: '服务美团业务部署' }
        ]
      }
    ),
    '服务美团业务部署'
  )
  assert.equal(resolveApplicationReason('发生时间：，去九江出差3天，服务美团业务部署'), '服务美团业务部署')
})

test('expense application expands a single selected date with natural days', () => {
  const prompt = [
    '发生时间：2026-05-25',
    '去上海出差3天，支撑国网服务器部署'
  ].join('\n')

  assert.equal(expandApplicationTimeWithDays('2026-05-25', 3), '2026-05-25 至 2026-05-27')
  assert.equal(resolveApplicationTimeRange({ time_range: {} }, prompt), '2026-05-25 至 2026-05-27')
})

test('expense application keeps explicit time range before applying days', () => {
  assert.equal(
    resolveApplicationTimeRange(
      {
        time_range: {
          start_date: '2026-05-25',
          end_date: '2026-05-27'
        }
      },
      '去上海出差3天，支撑国网服务器部署'
    ),
    '2026-05-25 至 2026-05-27'
  )
})
