import { dedupeLowerSeverityRiskCards } from './travelRequestDetailRiskCardDedupe.js'

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

export function buildAiAdviceViewModel({
  completionItems = [],
  materialPrompts = [],
  profileAdviceItems = [],
  riskCards = []
} = {}) {
  const normalizedCompletionItems = completionItems.map((item) => normalizeText(item)).filter(Boolean)
  const normalizedMaterialPrompts = materialPrompts.map((item) => normalizeText(item)).filter(Boolean)
  const normalizedProfileAdviceItems = profileAdviceItems.map((item) => normalizeText(item)).filter(Boolean)
  const normalizedRiskCards = dedupeLowerSeverityRiskCards(riskCards.filter(Boolean))
  const hasHighRisk = normalizedRiskCards.some((card) => card.tone === 'high')
  const sortedRiskCards = sortRiskCardsByTone(normalizedRiskCards)

  if (
    !normalizedCompletionItems.length
    && !normalizedMaterialPrompts.length
    && !normalizedProfileAdviceItems.length
    && !normalizedRiskCards.length
  ) {
    return {
      tone: 'ready',
      badge: '可以提交',
      summary: '自动检测未发现票据、金额、行程或历史画像异常，可以提交审批。',
      items: [],
      riskCards: [],
      sections: []
    }
  }

  const sections = []
  if (normalizedCompletionItems.length) {
    sections.push({
      kind: 'completion',
      title: '建议补充字段',
      items: normalizedCompletionItems
    })
  }
  if (normalizedMaterialPrompts.length) {
    sections.push({
      kind: 'material',
      title: '材料补充提示',
      items: normalizedMaterialPrompts
    })
  }
  if (normalizedProfileAdviceItems.length) {
    sections.push({
      kind: 'profile',
      title: '历史操作建议',
      items: normalizedProfileAdviceItems
    })
  }
  if (normalizedRiskCards.length) {
    sections.push({
      kind: 'risk',
      title: `已知存在风险（${normalizedRiskCards.length}项）`,
      items: sortedRiskCards,
      totalCount: normalizedRiskCards.length
    })
  }

  return {
    tone: hasHighRisk ? 'warning' : 'pending',
    badge: hasHighRisk ? '优先整改' : normalizedRiskCards.length ? '待核对' : '建议关注',
    summary: normalizedRiskCards.length
      ? `自动检测发现 ${normalizedRiskCards.length} 个风险点，已按风险等级排序全部展示。`
      : normalizedMaterialPrompts.length
        ? `自动检测发现 ${normalizedMaterialPrompts.length} 条材料补充提示，不作为风险计数。`
        : '结合历史操作记录生成提交建议，请按提示核对后提交审批。',
    items: normalizedCompletionItems,
    riskCards: normalizedRiskCards,
    sections
  }
}

function sortRiskCardsByTone(cards) {
  const toneWeight = {
    high: 0,
    medium: 1,
    low: 2,
    normal: 3,
    pass: 4
  }
  return [...cards].sort((left, right) => {
    const leftWeight = toneWeight[normalizeText(left?.tone).toLowerCase()] ?? 9
    const rightWeight = toneWeight[normalizeText(right?.tone).toLowerCase()] ?? 9
    return leftWeight - rightWeight
  })
}
