import { extractExpenseClaimItems } from '../services/reimbursements.js'
import { buildAiDocumentDetailHref } from './aiDocumentDetailReference.js'
import { isApplicationDocumentNo } from './documentClassification.js'
import { compactText, normalizeDateText, normalizeText, parseDate } from './aiDocumentQueryText.js'
import { filterActionableRiskFlags, isRiskSummaryWithRisk, normalizeRiskFlagTone } from './riskFlags.js'

export { resolveAiDocumentQueryIntent } from './aiDocumentQueryIntent.js'

const DOCUMENT_QUERY_LIMIT = 8

const STATUS_LABELS = {
  draft: '草稿',
  submitted: '审批中',
  pending: '待处理',
  approved: '已审批',
  completed: '已完成',
  archived: '已归档',
  returned: '已退回',
  rejected: '已驳回',
  pending_payment: '待付款',
  paid: '已付款'
}

const TYPE_LABELS = {
  travel: '差旅费',
  travel_application: '差旅费用申请',
  expense_application: '费用申请',
  application: '费用申请',
  office: '办公用品费',
  transport: '交通费',
  hotel: '住宿费',
  meal: '业务招待费',
  entertainment: '业务招待费',
  meeting: '会务费',
  training: '培训费',
  software: '软件服务费',
  other: '其他费用'
}

const COMMAND_ACTION_LABELS = {
  delete: '删除',
  approve: '审核通过',
  reject: '驳回/退回'
}

const COMMAND_ACTION_VERBS = {
  delete: '删除',
  approve: '审核',
  reject: '驳回或退回'
}

const COMMAND_OBJECT_LABELS = {
  draft: '草稿',
  application: '申请单',
  reimbursement: '报销单',
  approval_task: '待审任务',
  document: '单据'
}

const MONEY_FORMATTER = new Intl.NumberFormat('zh-CN', {
  style: 'currency',
  currency: 'CNY',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
})

function resolveStatusDisplayLabel(value = '') {
  const text = normalizeText(value)
  if (!text) {
    return ''
  }
  return STATUS_LABELS[text.toLowerCase()] || text
}

function escapeHtml(value = '') {
  return String(value || '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
}

function resolveDocumentNo(claim = {}) {
  return normalizeText(claim.claim_no || claim.claimNo || claim.documentNo || claim.id || claim.claim_id)
}

function resolveClaimId(claim = {}) {
  return normalizeText(claim.id || claim.claim_id || claim.claimId || resolveDocumentNo(claim))
}

export function mergeAiDocumentQueryPayloads(...payloads) {
  const records = []
  const seen = new Set()

  payloads.forEach((payload) => {
    const querySource = normalizeText(payload?.querySource || payload?.aiQuerySource || payload?.ai_query_source)
    extractExpenseClaimItems(payload).forEach((claim) => {
      const normalizedClaim = querySource
        ? { ...claim, ai_query_source: querySource }
        : claim
      const documentNo = resolveDocumentNo(normalizedClaim)
      const claimId = resolveClaimId(normalizedClaim)
      const documentType = resolveDocumentTypeCode(normalizedClaim)
      const stableId = documentNo || claimId
      if (!stableId) {
        records.push(normalizedClaim)
        return
      }
      const key = `${documentType}:${stableId}`
      if (seen.has(key)) {
        return
      }
      seen.add(key)
      records.push(normalizedClaim)
    })
  })

  return records
}

function resolveDocumentTypeCode(claim = {}) {
  const explicitType = normalizeText(
    claim.document_type_code
      || claim.documentTypeCode
      || claim.document_type
      || claim.documentType
  ).toLowerCase()
  const expenseType = normalizeText(claim.expense_type || claim.expenseType || claim.typeCode).toLowerCase()
  const documentNo = resolveDocumentNo(claim).toUpperCase()
  if (
    explicitType === 'application'
    || explicitType === 'expense_application'
    || expenseType === 'application'
    || expenseType.endsWith('_application')
    || isApplicationDocumentNo(documentNo)
  ) {
    return 'application'
  }
  return 'reimbursement'
}

function resolveStatusLabel(claim = {}) {
  const key = normalizeText(claim.status || claim.state || claim.approval_status || claim.approvalStatus).toLowerCase()
  const explicitLabel = resolveStatusDisplayLabel(
    claim.status_label || claim.statusLabel || claim.approval_stage || claim.approvalStage
  )
  return explicitLabel || STATUS_LABELS[key] || '待确认'
}

// 状态语义化分类，驱动卡片着色：进行中 / 正向终态 / 需关注 / 异常终态
function resolveStatusTone(statusLabel = '') {
  const text = normalizeText(statusLabel)
  if (/草稿|已退回|退回|待补充/.test(text)) {
    return 'is-warning'
  }
  if (/已驳回|驳回|已拒绝|拒绝/.test(text)) {
    return 'is-danger'
  }
  if (/已批准|已审批|已完成|已付款|已支付|已归档|已报销/.test(text)) {
    return 'is-success'
  }
  return 'is-pending'
}

function resolveStatusKey(claim = {}) {
  return normalizeText(claim.status || claim.state || claim.approval_status || claim.approvalStatus).toLowerCase()
}

function resolveRecordQuerySource(claim = {}, intent = {}) {
  return normalizeText(
    claim.ai_query_source
      || claim.aiQuerySource
      || claim.querySource
      || (intent.source === 'approval' ? 'approval' : '')
  )
}

function resolveRiskFlags(claim = {}) {
  if (Array.isArray(claim.risk_flags_json)) {
    return claim.risk_flags_json
  }
  if (Array.isArray(claim.riskFlags)) {
    return claim.riskFlags
  }
  if (Array.isArray(claim.review_flags)) {
    return claim.review_flags
  }
  if (Array.isArray(claim.reviewFlags)) {
    return claim.reviewFlags
  }
  return []
}

function resolveRiskSummary(claim = {}) {
  return normalizeText(
    claim.risk_summary ||
    claim.riskSummary ||
    claim.risk ||
    claim.risk_label ||
    claim.riskLabel
  )
}

function resolveRecordRiskMeta(claim = {}) {
  const flags = filterActionableRiskFlags(resolveRiskFlags(claim))
  const summary = resolveRiskSummary(claim)
  if (!flags.length && !isRiskSummaryWithRisk(summary)) {
    return { hasRisk: false, riskTone: 'none', riskLabel: '无风险' }
  }
  const tones = flags.map((flag) => normalizeRiskFlagTone(flag))
  const riskTone = tones.includes('high')
    ? 'high'
    : tones.includes('medium')
      ? 'medium'
      : tones.includes('low')
        ? 'low'
        : 'medium'
  const riskLabel = riskTone === 'high'
    ? '高风险'
    : riskTone === 'medium'
      ? '中风险'
      : '低风险'
  return { hasRisk: true, riskTone, riskLabel }
}

function isApprovalTaskClaim(claim = {}, intent = {}) {
  return resolveRecordQuerySource(claim, intent) === 'approval'
}

function isPendingApprovalStatus(statusKey = '', statusLabel = '') {
  const normalizedStatusKey = normalizeText(statusKey).toLowerCase()
  const normalizedStatusLabel = normalizeText(statusLabel)
  if (['approved', 'completed', 'archived', 'paid', 'rejected', 'returned', 'cancelled'].includes(normalizedStatusKey)) {
    return false
  }
  return !/已审批|已批准|审批通过|已完成|已付款|已支付|已归档|已驳回|已退回|已拒绝|拒绝|取消/.test(normalizedStatusLabel)
}

function resolveReason(claim = {}) {
  return normalizeText(claim.reason || claim.business_reason || claim.description || claim.title || claim.note) || '未填写事由'
}

function resolveExpenseTypeLabel(claim = {}) {
  const key = normalizeText(claim.expense_type || claim.expenseType || claim.type_code || claim.typeCode).toLowerCase()
  return TYPE_LABELS[key] || TYPE_LABELS.other
}

function resolveExpenseTypeCode(claim = {}) {
  return normalizeText(claim.expense_type || claim.expenseType || claim.type_code || claim.typeCode).toLowerCase()
}

function pickText(source = {}, keys = [], fallback = '') {
  for (const key of keys) {
    const value = normalizeText(source[key])
    if (value) {
      return value
    }
  }
  return fallback
}

function pickRawValue(source = {}, keys = []) {
  for (const key of keys) {
    const value = source[key]
    if (value !== undefined && value !== null && normalizeText(value)) {
      return value
    }
  }
  return null
}

function normalizeMoneyValue(value) {
  if (typeof value === 'number') {
    return Number.isFinite(value) ? value : null
  }
  const normalized = normalizeText(value).replace(/,/g, '')
  if (!normalized) {
    return null
  }
  const matched = normalized.match(/-?\d+(?:\.\d+)?/)
  if (!matched) {
    return null
  }
  const amount = Number(matched[0])
  return Number.isFinite(amount) ? amount : null
}

function resolveAmountLabel(claim = {}) {
  const rawValue = pickRawValue(claim, [
    'amount',
    'total_amount',
    'totalAmount',
    'claimed_amount',
    'claimedAmount',
    'application_amount',
    'applicationAmount',
    'budget_amount',
    'budgetAmount',
    'estimated_amount',
    'estimatedAmount'
  ])
  const amount = normalizeMoneyValue(rawValue)
  return amount === null ? '待确认' : MONEY_FORMATTER.format(amount)
}

function resolveAmountValue(claim = {}) {
  return normalizeMoneyValue(pickRawValue(claim, [
    'amount',
    'total_amount',
    'totalAmount',
    'claimed_amount',
    'claimedAmount',
    'application_amount',
    'applicationAmount',
    'budget_amount',
    'budgetAmount',
    'estimated_amount',
    'estimatedAmount'
  ]))
}

function resolveOwnerLabel(claim = {}) {
  return pickText(claim, [
    'applicant_name',
    'applicantName',
    'employee_name',
    'employeeName',
    'claimant_name',
    'claimantName',
    'created_by_name',
    'createdByName',
    'user_name',
    'userName',
    'applicant',
    'employee'
  ], '未显示')
}

function resolveDepartmentLabel(claim = {}) {
  return pickText(claim, [
    'department_name',
    'departmentName',
    'dept_name',
    'deptName',
    'org_name',
    'orgName',
    'department'
  ], '未显示')
}

function resolveLocationLabel(claim = {}) {
  return pickText(claim, [
    'location',
    'destination',
    'destination_city',
    'destinationCity',
    'city',
    'business_location',
    'businessLocation',
    'place'
  ])
}

function resolveUpdatedDate(claim = {}) {
  return normalizeDateText(
    claim.updated_at
      || claim.updatedAt
      || claim.submitted_at
      || claim.submittedAt
      || claim.created_at
      || claim.createdAt
  )
}

function resolveRecordDate(claim = {}) {
  return normalizeDateText(
    claim.occurred_at
      || claim.occurredAt
      || claim.business_time
      || claim.businessTime
      || claim.submitted_at
      || claim.submittedAt
      || claim.created_at
      || claim.createdAt
      || claim.updated_at
      || claim.updatedAt
  )
}

function resolveTimeLabel(claim = {}, fallbackDate = '') {
  const businessTime = pickText(claim, [
    'business_time',
    'businessTime',
    'trip_time',
    'tripTime',
    'travel_time',
    'travelTime'
  ])
  if (businessTime) {
    return businessTime
  }

  const startDate = normalizeDateText(
    claim.start_date
      || claim.startDate
      || claim.trip_start_date
      || claim.tripStartDate
      || claim.departure_date
      || claim.departureDate
  )
  const endDate = normalizeDateText(
    claim.end_date
      || claim.endDate
      || claim.trip_end_date
      || claim.tripEndDate
      || claim.return_date
      || claim.returnDate
  )
  if (startDate && endDate && startDate !== endDate) {
    return `${startDate} 至 ${endDate}`
  }
  return startDate || endDate || fallbackDate || '待补充'
}

function dateInRange(dateText, range) {
  if (!range || !range.start || !range.end) {
    return true
  }
  if (!dateText) {
    return false
  }
  return dateText >= range.start && dateText <= range.end
}

function toTimestamp(dateText) {
  const date = parseDate(dateText)
  return date ? date.getTime() : 0
}

function normalizeRecord(claim = {}, intent = {}) {
  const documentType = resolveDocumentTypeCode(claim)
  const documentNo = resolveDocumentNo(claim)
  const date = resolveRecordDate(claim)
  const updatedDate = resolveUpdatedDate(claim)
  const reason = resolveReason(claim)
  const expenseTypeCode = resolveExpenseTypeCode(claim)
  const typeLabel = resolveExpenseTypeLabel(claim)
  const statusKey = resolveStatusKey(claim)
  const rawStatusLabel = resolveStatusLabel(claim)
  const querySource = resolveRecordQuerySource(claim, intent)
  const isApprovalTask = isApprovalTaskClaim(claim, intent)
  const riskMeta = resolveRecordRiskMeta(claim)
  const statusLabel = isApprovalTask && isPendingApprovalStatus(statusKey, rawStatusLabel)
    ? '待审批'
    : rawStatusLabel
  const ownerLabel = resolveOwnerLabel(claim)
  const departmentLabel = resolveDepartmentLabel(claim)
  const locationLabel = resolveLocationLabel(claim)
  return {
    id: resolveClaimId(claim),
    claimId: resolveClaimId(claim),
    claimNo: documentNo,
    documentNo,
    documentType,
    documentTypeLabel: documentType === 'application' ? '申请单' : '报销单',
    expenseTypeCode,
    typeLabel,
    time: resolveTimeLabel(claim, date),
    dateKey: date,
    updatedTime: updatedDate || '未显示',
    statusKey,
    statusLabel,
    statusTone: resolveStatusTone(statusLabel),
    hasRisk: riskMeta.hasRisk,
    riskTone: riskMeta.riskTone,
    riskLabel: riskMeta.riskLabel,
    querySource,
    isApprovalTask,
    reason,
    amountLabel: resolveAmountLabel(claim),
    amountValue: resolveAmountValue(claim),
    ownerLabel,
    departmentLabel,
    locationLabel,
    searchableText: compactText([
      documentNo,
      reason,
      ownerLabel,
      departmentLabel,
      locationLabel,
      typeLabel,
      statusLabel,
      riskMeta.riskLabel
    ].join(' '))
  }
}

function matchesStatusFilter(record = {}, statusFilter = null) {
  if (!statusFilter) {
    return true
  }
  return statusFilter.keys.includes(record.statusKey) || statusFilter.label === record.statusLabel
}

function matchesExpenseTypeFilter(record = {}, expenseTypeFilter = null) {
  if (!expenseTypeFilter) {
    return true
  }
  return expenseTypeFilter.codes.includes(record.expenseTypeCode)
}

function matchesKeywordFilter(record = {}, keywordFilter = null) {
  if (!keywordFilter?.keyword) {
    return true
  }
  return record.searchableText.includes(compactText(keywordFilter.keyword))
}

function matchesAmountFilter(record = {}, amountFilter = null) {
  if (!amountFilter) {
    return true
  }
  if (record.amountValue === null || record.amountValue === undefined) {
    return false
  }
  if (amountFilter.min !== null && amountFilter.min !== undefined && record.amountValue < amountFilter.min) {
    return false
  }
  if (amountFilter.max !== null && amountFilter.max !== undefined && record.amountValue > amountFilter.max) {
    return false
  }
  return true
}

function matchesRiskFilter(record = {}, riskFilter = null) {
  if (!riskFilter?.level) {
    return true
  }
  if (riskFilter.level === 'none') {
    return !record.hasRisk
  }
  if (riskFilter.level === 'has') {
    return record.hasRisk
  }
  return record.hasRisk && record.riskTone === riskFilter.level
}

export function filterAiDocumentQueryRecords(claimsPayload, intent = {}) {
  const rows = extractExpenseClaimItems(claimsPayload)
    .map((claim) => normalizeRecord(claim, intent))
    .filter((record) => (
      !intent?.documentType ||
      intent.documentType === 'all' ||
      record.documentType === intent.documentType
    ))
    .filter((record) => dateInRange(record.dateKey, intent?.timeRange))
    .filter((record) => matchesStatusFilter(record, intent?.statusFilter))
    .filter((record) => matchesExpenseTypeFilter(record, intent?.expenseTypeFilter))
    .filter((record) => matchesKeywordFilter(record, intent?.keywordFilter))
    .filter((record) => matchesAmountFilter(record, intent?.amountFilter))
    .filter((record) => matchesRiskFilter(record, intent?.riskFilter))
    .sort((left, right) => toTimestamp(right.dateKey) - toTimestamp(left.dateKey))

  return rows
}

function buildDocumentCardFieldHtml(label = '', value = '', options = {}) {
  const text = normalizeText(value)
  if (!text || text === '-') {
    return ''
  }
  const valueClass = options.valueClass ? ` ${options.valueClass}` : ''
  const fieldClass = options.fieldClass ? ` ${options.fieldClass}` : ''
  return [
    `<div class="ai-document-card__field${fieldClass}">`,
    `<span class="ai-document-card__label">${escapeHtml(label)}</span>`,
    `<strong class="ai-document-card__value${valueClass}">${escapeHtml(text)}</strong>`,
    '</div>'
  ].join('')
}

function resolveCommandDetailActionLabel(commandFrame = null) {
  if (!commandFrame || commandFrame.safetyLevel !== 'confirm_required') {
    return '查看详情'
  }
  if (commandFrame.action === 'delete') {
    return '进入详情确认删除'
  }
  if (commandFrame.action === 'approve') {
    return '进入详情确认审核'
  }
  if (commandFrame.action === 'reject') {
    return '进入详情确认驳回'
  }
  return '进入详情确认'
}

function buildCommandConfirmationGuidanceHtml(commandFrame = null) {
  if (!commandFrame || commandFrame.safetyLevel !== 'confirm_required') {
    return ''
  }
  const actionVerb = COMMAND_ACTION_VERBS[commandFrame.action] || '操作'
  const ctaLabel = resolveCommandDetailActionLabel(commandFrame)
  return [
    '<section class="ai-document-command-guidance" aria-label="高风险操作提示">',
    '<strong class="ai-document-command-guidance__title">需要先确认目标单据</strong>',
    '<div class="ai-document-command-guidance__body">',
    `系统不会直接${escapeHtml(actionVerb)}相关单据。`,
    `如果您希望继续${escapeHtml(actionVerb)}单据，请点击下方候选单据里的快捷按钮“${escapeHtml(ctaLabel)}”，进入单据详情核对后再操作。`,
    '</div>',
    '</section>'
  ].join('')
}

function buildDocumentCardHtml(record = {}, options = {}) {
  const href = buildAiDocumentDetailHref(record)
  const typeClass = record.documentType === 'application' ? 'application' : 'reimbursement'
  const approvalTaskClass = record.isApprovalTask ? ' ai-document-card--approval-task' : ''
  const statusTone = record.statusTone || 'is-pending'
  const amountLabel = record.documentType === 'application' ? '预计金额' : '报销金额'
  const documentTypeText = [record.documentTypeLabel, record.typeLabel].filter(Boolean).join(' · ')
  const title = record.typeLabel || record.documentTypeLabel || record.reason || '单据详情'
  const ownerText = [record.ownerLabel, record.departmentLabel]
    .filter((item) => item && item !== '未显示')
    .join(' · ') || '未显示'
  const detailActionLabel = resolveCommandDetailActionLabel(options.commandFrame)
  const summaryHtml = [
    buildDocumentCardFieldHtml('日期', record.time || '待补充'),
    buildDocumentCardFieldHtml(amountLabel, record.amountLabel, { valueClass: 'ai-document-card__amount' })
  ].join('')
  const detailsHtml = [
    buildDocumentCardFieldHtml('地点', record.locationLabel || '待补充'),
    buildDocumentCardFieldHtml('风险', record.riskLabel || '无风险'),
    buildDocumentCardFieldHtml('单据编号', record.documentNo || '未编号单据', { valueClass: 'ai-document-card__number' }),
    buildDocumentCardFieldHtml('事由', record.reason || '待补充'),
    buildDocumentCardFieldHtml('申请人', ownerText),
    [
      '<div class="ai-document-card__field ai-document-card__field--action">',
      '<span class="ai-document-card__label">操作</span>',
      href
        ? `<a class="ai-html-action-link ai-html-action-link-document ai-document-card__action" data-ai-action="open-document-detail" href="${escapeHtml(href)}">${escapeHtml(detailActionLabel)}</a>`
        : '<span class="ai-document-card__value">暂无详情</span>',
      '</div>'
    ].join(''),
    buildDocumentCardFieldHtml('单据类型', documentTypeText)
  ].join('')

  return [
    `<article class="ai-document-card ai-document-card--${typeClass}${approvalTaskClass} ${statusTone}" aria-label="单据详情">`,
    '<header class="ai-document-card__head">',
    `<strong class="ai-document-card__reason">${escapeHtml(title)}</strong>`,
    `<span class="ai-document-card__status">${escapeHtml(record.statusLabel)}</span>`,
    '</header>',
    '<div class="ai-document-card__body">',
    summaryHtml ? `<div class="ai-document-card__summary">${summaryHtml}</div>` : '',
    '<div class="ai-document-card__details">',
    detailsHtml,
    '</div>',
    '</div>',
    '</article>'
  ].join('')
}

function buildDocumentQuerySummaryHtml(scopeText = '', totalCount = 0, visibleCount = 0) {
  return [
    '<section class="ai-document-query-summary" aria-label="单据查询范围">',
    '<span class="ai-document-query-summary__label">查询范围</span>',
    `<strong class="ai-document-query-summary__scope">${escapeHtml(scopeText || '相关单据')}</strong>`,
    '<span class="ai-document-query-summary__count">',
    `共 <strong>${escapeHtml(String(totalCount))}</strong> 张`,
    '</span>',
    '<span class="ai-document-query-summary__count">',
    `展示最近 <strong>${escapeHtml(String(visibleCount))}</strong> 张`,
    '</span>',
    '</section>'
  ].join('')
}

function buildDocumentCardsHtml(records = [], options = {}) {
  const querySummaryHtml = options.querySummaryHtml || ''
  const commandGuidanceHtml = buildCommandConfirmationGuidanceHtml(options.commandFrame)
  return [
    '<!-- ai-trusted-html:start -->',
    commandGuidanceHtml,
    querySummaryHtml,
    '<section class="ai-document-card-list" aria-label="单据查询结果">',
    ...records.map((record) => buildDocumentCardHtml(record, options)),
    '</section>',
    '<!-- ai-trusted-html:end -->'
  ].join('\n')
}

function buildQueryScopeText(intent = {}) {
  return [
    intent.sourceLabel || '相关单据',
    intent.documentTypeLabel && intent.documentTypeLabel !== '全部单据' ? intent.documentTypeLabel : '',
    intent.timeRange?.label || '',
    intent.statusFilter?.label ? `状态：${intent.statusFilter.label}` : '',
    intent.expenseTypeFilter?.label ? `费用类型：${intent.expenseTypeFilter.label}` : '',
    intent.keywordFilter?.label ? `关键词：${intent.keywordFilter.label}` : '',
    intent.amountFilter?.label ? `金额：${intent.amountFilter.label}` : '',
    intent.riskFilter?.label ? `风险：${intent.riskFilter.label}` : ''
  ].filter(Boolean).join(' / ')
}

export function buildAiDocumentQueryConditionSummary(intent = {}) {
  const conditions = [
    `查询来源：${intent.sourceLabel || '相关单据'}`,
    `单据类型：${intent.documentTypeLabel || '全部单据'}`,
    `时间范围：${intent.timeRange?.label || '不限'}`,
    intent.statusFilter?.label ? `状态：${intent.statusFilter.label}` : '',
    intent.expenseTypeFilter?.label ? `费用类型：${intent.expenseTypeFilter.label}` : '',
    intent.keywordFilter?.label ? `关键词：${intent.keywordFilter.label}` : '',
    intent.amountFilter?.label ? `金额：${intent.amountFilter.label}` : '',
    intent.riskFilter?.label ? `风险：${intent.riskFilter.label}` : ''
  ].filter(Boolean)
  return conditions.join('；')
}

function buildAiDocumentCommandPolicyEvent(commandFrame = null) {
  if (!commandFrame || commandFrame.safetyLevel !== 'confirm_required') {
    return null
  }
  const actionLabel = COMMAND_ACTION_LABELS[commandFrame.action] || '高风险操作'
  const objectLabel = COMMAND_OBJECT_LABELS[commandFrame.objectType] || '单据'
  return {
    eventId: 'document-command-policy',
    title: '识别高风险操作意图',
    content: `识别到用户想执行“${actionLabel}”动作，对象是“${objectLabel}”。这类动作不会直接执行，我会先筛选候选单据，再让用户进入详情页确认。`,
    status: 'running'
  }
}

export function buildAiDocumentQueryThinkingEvents(intent = {}, options = {}) {
  const conditionSummary = buildAiDocumentQueryConditionSummary(intent)
  return [
    buildAiDocumentCommandPolicyEvent(options.commandFrame),
    {
      eventId: 'document-query-parse',
      title: '解析自然语言筛选条件',
      content: `正在从您的问题里提取查询来源、单据类型、时间、状态、费用类型、风险、关键词和金额条件。当前识别：${conditionSummary}。`,
      status: 'running'
    },
    {
      eventId: 'document-query-fetch',
      title: '查询业务单据接口',
      content: '等待调用业务单据接口。',
      status: 'pending'
    },
    {
      eventId: 'document-query-filter',
      title: '组合筛选单据',
      content: '等待接口返回后，再按已识别条件做二次筛选。',
      status: 'pending'
    }
  ].filter(Boolean)
}

export function buildAiDocumentQueryMessage(intent = {}, claimsPayload = [], options = {}) {
  const records = filterAiDocumentQueryRecords(claimsPayload, intent)
  const visibleRecords = records.slice(0, DOCUMENT_QUERY_LIMIT)
  const scopeText = buildQueryScopeText(intent)

  if (!records.length) {
    return [
      '### 未查询到相关单据',
      '',
      `**查询范围**：${scopeText || '相关单据'}。`,
      '',
      '当前没有匹配的单据。可以继续告诉我更具体的单据类型、时间范围或状态，我会重新筛选。'
    ].join('\n')
  }

  const lines = [
    '### 已查询到相关单据',
    '',
    buildDocumentCardsHtml(visibleRecords, {
      querySummaryHtml: buildDocumentQuerySummaryHtml(scopeText, records.length, visibleRecords.length),
      commandFrame: options.commandFrame
    })
  ]

  if (records.length > visibleRecords.length) {
    lines.push('', `还有 ${records.length - visibleRecords.length} 张未展示；可以继续补充时间、类型或状态缩小范围。`)
  }
  return lines.join('\n')
}
