import { ASSISTANT_SCOPE_ACTION_FILL_COMPOSER } from './assistantSessionScope.js'

const APPLICATION_FIELD_PREFILLS = {
  time: '申请时间段：',
  time_range: '申请时间段：',
  location: '地点：',
  reason: '事由：',
  days: '天数：',
  transport_mode: '出行方式：',
  amount: '用户预估费用：'
}

export function resolveSuggestedActionPrefill(action = {}) {
  const payload = action?.payload && typeof action.payload === 'object' ? action.payload : {}
  const explicitPrefill = String(
    payload.prompt_prefill
      || payload.input_prefill
      || payload.prefill_text
      || payload.fill_text
      || ''
  ).trim()
  if (explicitPrefill) {
    return explicitPrefill
  }

  const actionType = String(action?.action_type || '').trim()
  if (actionType !== 'prefill_composer' && actionType !== ASSISTANT_SCOPE_ACTION_FILL_COMPOSER) {
    return ''
  }

  const applicationField = String(payload.application_field || '').trim()
  return APPLICATION_FIELD_PREFILLS[applicationField] || ''
}

export function mergeComposerPrefill(currentDraft = '', prefill = '') {
  const normalizedPrefill = String(prefill || '').trim()
  if (!normalizedPrefill) {
    return String(currentDraft || '')
  }

  const current = String(currentDraft || '')
  if (!current.trim()) {
    return normalizedPrefill
  }
  if (current.includes(normalizedPrefill)) {
    return current
  }
  return `${current.trimEnd()}\n${normalizedPrefill}`
}
