// AI 模式下的申请单草稿模型。
// 独立于旧的引导式报销/申请状态机，只在 AI 对话页内驱动逐项收集，
// 不调用旧视图的申请模板/预览钩子，也不复用 buildLocalApplicationPreview。

const DEFAULT_FIELD_STEPS = [
  { key: 'reason', label: '出差事由', prompt: '先告诉我这次出差的事由，例如：去上海支持上海电力部署项目。' },
  { key: 'time_range', label: '出差时间/天数', prompt: '出差时间和天数是什么？例如：2026-06-20 至 2026-06-22，出差 3 天。' },
  { key: 'location', label: '出差地点', prompt: '出差地点是哪里？可以填城市或具体客户地点。' },
  { key: 'amount', label: '预计金额', prompt: '预计金额是多少？如果还没有汇总，可以回复“待核算”。' }
]

const SUMMARY_STEP_KEY = 'summary'

function normalizeAnswer(value) {
  return String(value || '').trim()
}

export function getAiApplicationSteps() {
  return DEFAULT_FIELD_STEPS
}

export function createAiApplicationDraft(expenseType, expenseTypeLabel) {
  return {
    expenseType: normalizeAnswer(expenseType),
    expenseTypeLabel: normalizeAnswer(expenseTypeLabel),
    values: {},
    stepKey: DEFAULT_FIELD_STEPS[0].key
  }
}

export function getAiApplicationCurrentStep(draft) {
  const stepKey = normalizeAnswer(draft?.stepKey)
  return DEFAULT_FIELD_STEPS.find((step) => step.key === stepKey) || DEFAULT_FIELD_STEPS[0]
}

export function buildAiApplicationStepPrompt(draft) {
  const step = getAiApplicationCurrentStep(draft)
  const label = normalizeAnswer(draft?.expenseTypeLabel) || '出差申请'
  const stepIndex = Math.max(0, DEFAULT_FIELD_STEPS.findIndex((item) => item.key === step.key))
  return [
    `好的，那我们先把${label}申请在当前对话里理一下。`,
    '',
    `第 ${stepIndex + 1} 步 · ${step.label}`,
    step.prompt
  ].join('\n')
}

export function applyAiApplicationAnswer(draft, answer, files = []) {
  const current = draft && typeof draft === 'object' ? draft : createAiApplicationDraft()
  const step = getAiApplicationCurrentStep(current)
  const nextValues = { ...(current.values || {}) }
  nextValues[step.key] = normalizeAnswer(answer)

  const currentIndex = DEFAULT_FIELD_STEPS.findIndex((item) => item.key === step.key)
  const nextStep = DEFAULT_FIELD_STEPS[currentIndex + 1]
  return {
    ...current,
    values: nextValues,
    stepKey: nextStep ? nextStep.key : SUMMARY_STEP_KEY
  }
}

export function isAiApplicationDraftComplete(draft) {
  return Boolean(draft) && normalizeAnswer(draft?.stepKey) === SUMMARY_STEP_KEY
}

export function buildAiApplicationSummary(draft) {
  const label = normalizeAnswer(draft?.expenseTypeLabel) || '出差申请'
  const values = draft?.values || {}
  const lines = [`已完成「${label}」的要点收集，请核对：`, '']

  DEFAULT_FIELD_STEPS.forEach((step) => {
    const value = normalizeAnswer(values[step.key])
    lines.push(`- ${step.label}：${value || '待补充'}`)
  })

  lines.push('', '如果哪一项需要修改，请直接告诉我；确认无误后我会帮您整理成申请草稿内容，再提交到申请助手生成单据。')
  return lines.join('\n')
}