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

import {
  buildStewardFieldCompletionContinuation,
  buildStewardFieldCompletionRawText,
  resolveStewardRuntimeFieldCompletion
} from '../src/views/scripts/stewardFieldCompletionModel.js'

test('steward field completion maps ontology travel type and anchors reason update', () => {
  const continuation = buildStewardFieldCompletionContinuation(
    {
      currentTask: {
        summary: '2月20-23日上海出差',
        ontology_fields: {
          expense_type: 'travel',
          time_range: '2026-02-20 至 2026-02-23',
          location: '上海市'
        },
        missing_fields: ['reason']
      }
    },
    'reason',
    '辅助国网仿生产服务器部署'
  )

  const rawText = buildStewardFieldCompletionRawText({
    preview: {
      fields: {
        applicationType: '',
        time: '2026-02-20 至 2026-02-23',
        location: '上海市',
        reason: '',
        days: '4天',
        transportMode: '火车'
      }
    },
    fieldKey: 'reason',
    fieldLabel: '事由',
    value: '辅助国网仿生产服务器部署',
    continuation
  })

  assert.equal(continuation.currentTask.ontology_fields.reason, '辅助国网仿生产服务器部署')
  assert.deepEqual(continuation.currentTask.missing_fields, [])
  assert.match(rawText, /申请类型：差旅费用申请/)
  assert.doesNotMatch(rawText, /申请类型：travel/)
  assert.match(rawText, /用户已补充：事由：辅助国网仿生产服务器部署。/)
  assert.match(rawText, /当前申请单字段的补充\/更新/)
  assert.match(rawText, /不是新建申请或切换任务/)
  assert.match(rawText, /不要把它改判为新的 IT 部署申请/)
})

test('steward runtime treats bare reason reply as current application field completion', () => {
  const decision = resolveStewardRuntimeFieldCompletion(
    '辅助国网仿生产服务器部署',
    {
      waiting_for: 'application_field_completion',
      pending_application: {
        message_id: 'application-preview-1',
        ready_to_submit: false,
        missing_fields: ['事由']
      }
    }
  )

  assert.deepEqual(decision, {
    next_action: 'fill_current_application_field',
    target_message_id: 'application-preview-1',
    field_key: 'reason',
    field_label: '事由',
    field_value: '辅助国网仿生产服务器部署'
  })
})

test('steward runtime keeps multi-field free text ambiguous for normal decision flow', () => {
  assert.equal(
    resolveStewardRuntimeFieldCompletion(
      '辅助国网仿生产服务器部署',
      {
        waiting_for: 'application_field_completion',
        pending_application: {
          message_id: 'application-preview-1',
          missing_fields: ['地点', '事由']
        }
      }
    ),
    null
  )
})
