export const AXIS_LABEL = {
  实质: '实质（3-4层）',
  形式: '形式（3-4层）',
}

export const PLATFORM_LABEL = {
  xiaohongshu: ['小红书', 'xhs'],
  weixin: ['微信公众号', 'wx'],
  douyin: ['抖音', 'dy'],
}

export const AXIS_ICON = {
  实质: '实',
  形式: '形',
  动作: '动',
  作用: '作',
  类型: '类',
  工具类型: '工',
  知识状态: '知',
  模态: '模',
  业务阶段: '阶',
  知识类型: '知',
  '作用/感受/意图': '意',
}

export const LIVE_STATUSES = new Set(['pending', 'running'])

export function statusText(status) {
  return {
    pending: '等待中',
    running: '运行中',
    done: '完成',
    partial: '部分完成',
    failed: '失败',
    skipped: '跳过',
  }[status] || status || '未开始'
}

export function querySummaryMap(summary) {
  const out = new Map()
  for (const row of summary?.queries || []) {
    out.set(row.query_id, row)
  }
  return out
}

export function platformCounts(row) {
  const platforms = row?.platforms || {}
  return ['xiaohongshu', 'weixin', 'douyin'].map((key) => platforms[key]?.status || '未跑').join(' / ')
}

export function searchedLabel(row) {
  return row ? `搜到 ${row.candidate_count || 0}` : ''
}

export function coarseLabel(row) {
  return row ? `粗筛通过 ${row.creation_hit_count || 0}` : ''
}

export function decodedLabel(row) {
  return row ? `解构完成 ${row.decoded_count || 0}` : ''
}

export function pct(part, total) {
  if (!total) return 0
  return Math.round((part / total) * 1000) / 10
}

export function uniqueAxisValues(items, axis) {
  const seen = new Set()
  const out = []
  for (const item of items || []) {
    const value = item.parts?.[axis]
    if (value && !seen.has(value)) {
      seen.add(value)
      out.push(value)
    }
  }
  return out
}

export function axisValues(data, family, axis) {
  if (axis === '实质' || axis === '形式') {
    return uniqueAxisValues(family.items, axis)
  }
  const key = axis === '作用/感受/意图' ? '目的池' : axis
  return data.axis_values?.[key] || uniqueAxisValues(family.items, key)
}

export function axisRowStats(familyItems, axis, value) {
  const key = axis === '作用/感受/意图' ? '目的池' : axis
  const values = Array.isArray(value) ? new Set(value) : new Set([value])
  const related = familyItems.filter((item) => values.has(item.parts?.[key]))
  return { total: related.length }
}

export function singletonMaps(singleton) {
  const byQueryText = new Map()
  const decodedByQueryId = new Map()
  for (const item of singleton?.decoded_items || []) {
    const key = item.query_id || ''
    decodedByQueryId.set(key, [...(decodedByQueryId.get(key) || []), item])
  }
  for (const row of singleton?.queries || []) {
    byQueryText.set(row.query_text, {
      ...row,
      decoded_items: decodedByQueryId.get(row.query_id) || [],
    })
  }
  return byQueryText
}

export function flatDetailItems(detail) {
  return (detail?.items || []).map((item) => {
    const [label, tone] = PLATFORM_LABEL[item.platform] || [item.platform, item.platform]
    return {
      ...item,
      platform_label: label,
      platform_tone: tone,
    }
  })
}

export function itemMediaUrl(item) {
  const media = item.media_assets || []
  const firstImage = media.find((asset) => ['image', 'cover', 'frame'].includes(asset.media_type))
  return firstImage?.cdn_url || firstImage?.oss_url || firstImage?.source_url || ''
}

export function itemBrief(item) {
  return item.brief || item.raw_summary || item.classification?.reason || ''
}

export function isQuerySearched(row) {
  return (row?.candidate_count || 0) > 0
}

export function isFinalKnowledge(item) {
  const decoded = item.decode_summary
  return item.classification?.is_creation_knowledge === true
    && decoded?.decode_status === 'decoded'
    && (decoded?.particle_count || 0) > 0
    && (decoded?.payload_count || 0) > 0
}

export function isLiveRun(run) {
  return LIVE_STATUSES.has(run?.status)
}
