export const EXPAND_GRAPH_PIPELINE_STEPS = [
  { id: 'expand', title: '擴展圖譜', hint: 'Brave 知識搜尋 + AI 合成三層 TKG' },
] as const

export const PLACEMENT_SCAN_PIPELINE_STEPS = [
  { id: 'crawl', title: '雙軌海巡', hint: '相關軌 + 近期軌（7d/30d）' },
] as const

export const PAIN_TAG_MINIMUM = 8

export type KnowledgeGraphNode = {
  id: string
  label: string
  node_kind: string
  type: string
  layer: number
  relation?: string
  placement_value?: string
  product_fit_score: number
  selected_for_scan: boolean
  relevance_tags: string[]
  recency_tags: string[]
}

export type KnowledgeGraphEdge = {
  from: string
  to: string
  relation: string
}

export type KnowledgeGraphData = {
  id: string
  brand_id: string
  seed: string
  nodes: KnowledgeGraphNode[]
  edges: KnowledgeGraphEdge[]
  pain_tag_count: number
  generated_at: number
  create_at: number
  update_at: number
}

export type ExpandKnowledgeGraphData = {
  job_id: string
  status: string
  message?: string
}

const NODE_KIND_LABEL: Record<string, string> = {
  pain: '痛點',
  symptom: '症狀',
  cause: '成因',
  knowledge: '知識',
}

const LAYER_LABEL: Record<number, string> = {
  0: 'L0 核心',
  1: 'L1 延伸',
  2: 'L2 周邊',
}

export function nodeKindLabel(kind: string) {
  return NODE_KIND_LABEL[kind] ?? (kind || '節點')
}

export function layerLabel(layer: number) {
  return LAYER_LABEL[layer] ?? `L${layer}`
}

export function productFitTone(score: number): 'success' | 'warning' | 'neutral' {
  if (score >= 70) return 'success'
  if (score >= 40) return 'warning'
  return 'neutral'
}

export function countSelectedNodes(nodes: KnowledgeGraphNode[]) {
  return nodes.filter((node) => node.selected_for_scan).length
}

export function groupNodesByLayer(nodes: KnowledgeGraphNode[]) {
  const groups = new Map<number, KnowledgeGraphNode[]>()
  for (const node of nodes) {
    const layer = node.layer ?? 0
    const list = groups.get(layer) ?? []
    list.push(node)
    groups.set(layer, list)
  }
  return [...groups.entries()].sort(([a], [b]) => a - b)
}