// AI 模式下的报销草稿模型。
// 独立于旧的引导式报销状态机，只在 AI 对话页内驱动逐项收集，
// 不调用 steward、不复用 guidedFlow 的编排流程。

const DEFAULT_FIELD_STEPS = [
  { key: 'reason', label: '事由', prompt: '先告诉我这笔报销的事由，例如：项目现场支持、客户接待。' },
  { key: 'time_range', label: '发生时间', prompt: '费用是什么时候发生的？例如：2026-06-15。' },
  { key: 'location', label: '地点/对象', prompt: '费用发生的地点或对象是哪里？' },
  { key: 'amount', label: '金额', prompt: '本次报销金额是多少？' },
  { key: 'attachments', label: '票据', prompt: '票据可以现在上传，或回复“稍后上传”。' }
]

const SUMMARY_STEP_KEY = 'summary'

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

function normalizeFileNames(files) {
  return Array.from(files || [])
    .map((file) => String(file?.name || '').trim())
    .filter(Boolean)
}

export function getAiExpenseSteps() {
  return DEFAULT_FIELD_STEPS
}

// 将 task 的 ontology_fields 映射到报销草稿字段。
// 只映射草稿能识别的字段(amount/time_range/reason/location),未知字段忽略。
export function buildAiExpenseDraftPrefillValues(ontologyFields = {}) {
  const source = ontologyFields || {}
  const values = {}
  const amount = normalizeAnswer(
    source.amount || source.application_amount || source.applicationAmount || source.estimated_amount
  )
  if (amount) {
    values.amount = amount
  }
  const timeRange = normalizeAnswer(
    source.time_range || source.business_time || source.application_business_time || source.time
  )
  if (timeRange) {
    values.time_range = timeRange
  }
  const reason = normalizeAnswer(source.reason || source.application_reason || source.title || source.summary)
  if (reason) {
    values.reason = reason
  }
  const location = normalizeAnswer(source.location || source.application_location)
  if (location) {
    values.location = location
  }
  return values
}

// 根据已填值推进 stepKey 到第一个未填字段,全部填满则到 summary。
function resolveInitialStepKey(values = {}) {
  for (const step of DEFAULT_FIELD_STEPS) {
    if (!normalizeAnswer(values[step.key])) {
      return step.key
    }
  }
  return SUMMARY_STEP_KEY
}

export function createAiExpenseDraft(expenseType, expenseTypeLabel, prefillValues = {}) {
  const safePrefill = prefillValues && typeof prefillValues === 'object' ? prefillValues : {}
  const values = {}
  for (const step of DEFAULT_FIELD_STEPS) {
    const value = normalizeAnswer(safePrefill[step.key])
    if (value) {
      values[step.key] = value
    }
  }
  return {
    expenseType: normalizeAnswer(expenseType),
    expenseTypeLabel: normalizeAnswer(expenseTypeLabel),
    applicationClaim: null,
    values,
    stepKey: resolveInitialStepKey(values)
  }
}

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

export function buildAiExpenseStepPrompt(draft) {
  const step = getAiExpenseCurrentStep(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 applyAiExpenseAnswer(draft, answer, files = []) {
  const current = draft && typeof draft === 'object' ? draft : createAiExpenseDraft()
  const step = getAiExpenseCurrentStep(current)
  const nextValues = { ...(current.values || {}) }
  const fileNames = normalizeFileNames(files)

  if (step.key === 'attachments') {
    if (fileNames.length) {
      nextValues.attachment_names = Array.from(
        new Set([...(nextValues.attachment_names || []), ...fileNames])
      )
    }
    nextValues.attachments = normalizeAnswer(answer)
      || (nextValues.attachment_names?.length ? `已选择 ${nextValues.attachment_names.length} 份附件` : '稍后上传')
  } else {
    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 isAiExpenseDraftComplete(draft) {
  return Boolean(draft) && normalizeAnswer(draft?.stepKey) === SUMMARY_STEP_KEY
}

export function buildAiExpenseSummary(draft) {
  const label = normalizeAnswer(draft?.expenseTypeLabel) || '报销'
  const values = draft?.values || {}
  const application = draft?.applicationClaim || null
  const lines = [`已完成「${label}」的信息收集，请核对：`, '']

  if (application && normalizeAnswer(application.application_claim_no)) {
    const parts = [
      application.application_claim_no,
      application.application_reason,
      application.application_business_time,
      application.application_location
    ].map(normalizeAnswer).filter(Boolean)
    lines.push(`- 关联申请单：${parts.join(' / ')}`)
  }

  DEFAULT_FIELD_STEPS.forEach((step) => {
    const value = step.key === 'attachments'
      ? (values.attachment_names?.length
        ? values.attachment_names.join('、')
        : normalizeAnswer(values.attachments) || '稍后上传')
      : normalizeAnswer(values[step.key])
    lines.push(`- ${step.label}：${value || '待补充'}`)
  })

  return lines.join('\n')
}
