import type { JobData } from '../types/api'
import {
  ANALYZE_COPY_MISSION_PIPELINE_STEPS,
  EXPAND_COPY_MISSION_GRAPH_PIPELINE_STEPS,
  GENERATE_COPY_DRAFT_PIPELINE_STEPS,
  GENERATE_COPY_MATRIX_PIPELINE_STEPS,
  VIRAL_SCAN_PIPELINE_STEPS,
  copyMissionDetailPath,
} from './copyFlow'
import { jobErrorMessage, isTerminalJobStatus } from './jobStatus'
import { jobTemplateLabel } from './jobTemplate'
import { EXPAND_GRAPH_PIPELINE_STEPS, PLACEMENT_SCAN_PIPELINE_STEPS } from './knowledgeGraph'
import { STYLE_8D_PIPELINE_STEPS } from './styleProfile'
import { placementFlowPath } from './placementFlow'
import { topicResearchMapPath } from './placementTopics'

const STEP_TITLE_BY_ID = new Map<string, string>(
  [
    ...EXPAND_GRAPH_PIPELINE_STEPS,
    ...PLACEMENT_SCAN_PIPELINE_STEPS,
    ...VIRAL_SCAN_PIPELINE_STEPS,
    ...ANALYZE_COPY_MISSION_PIPELINE_STEPS,
    ...EXPAND_COPY_MISSION_GRAPH_PIPELINE_STEPS,
    ...GENERATE_COPY_MATRIX_PIPELINE_STEPS,
    ...GENERATE_COPY_DRAFT_PIPELINE_STEPS,
    ...STYLE_8D_PIPELINE_STEPS,
    { id: 'prepare', title: '準備' },
    { id: 'execute', title: '執行' },
    { id: 'finalize', title: '收尾' },
  ].map((step) => [step.id, step.title]),
)

const PHASE_LABEL: Record<string, string> = {
  expand: '產生研究地圖',
  expand_copy_knowledge: '延伸知識',
  crawl: '雙軌海巡',
  viral_crawl: '爆款海巡',
  copy_mission_map: '研究地圖',
  copy_matrix_generate: '內容矩陣',
  copy_draft_generate: '深仿寫',
  session: '確認連線',
  samples: '抓取樣本',
  style: 'AI 8D 分析',
  store: '寫入人設',
  prepare: '準備',
  execute: '執行',
  finalize: '收尾',
}

const TERMINAL_ACTIVITY: Record<string, string> = {
  'expand-graph': '研究地圖已產生完成',
  'placement-scan': '雙軌海巡已完成',
  'scan-viral': '爆款掃描已完成',
  'analyze-copy-mission': '拷貝研究地圖已產生完成',
  'expand-copy-mission-graph': '延伸知識圖譜已產生完成',
  'generate-copy-matrix': '內容矩陣已產生完成',
  'generate-copy-draft': '仿寫草稿已產生完成',
  'style-8d': '8D 風格分析已完成',
}

function stepTitle(stepId: string): string {
  return STEP_TITLE_BY_ID.get(stepId) ?? PHASE_LABEL[stepId] ?? stepId
}

function hasCjk(text: string): boolean {
  return /[\u3400-\u9fff]/.test(text)
}

function translateGenericSummary(summary: string, job: JobData): string | null {
  const trimmed = summary.trim()
  if (!trimmed) return null

  const waiting = trimmed.match(/^waiting for worker$/i)
  if (waiting) return '等待背景執行接手…'

  if (/^job completed$/i.test(trimmed)) {
    return TERMINAL_ACTIVITY[job.template_type] ?? '任務已完成'
  }

  const running = trimmed.match(/^running step (.+)$/i)
  if (running) return `正在執行：${stepTitle(running[1])}`

  const completed = trimmed.match(/^completed step (.+)$/i)
  if (completed) {
    if (isTerminalJobStatus(job.status)) {
      return TERMINAL_ACTIVITY[job.template_type] ?? `${stepTitle(completed[1])}已完成`
    }
    return `已完成：${stepTitle(completed[1])}`
  }

  if (/^step failed$/i.test(trimmed)) return '步驟失敗'

  return hasCjk(trimmed) ? trimmed : null
}

function activePhaseHint(job: JobData): string {
  if (job.template_type === 'expand-graph') {
    return '研究地圖產生中…'
  }
  if (job.template_type === 'placement-scan') {
    return '雙軌海巡進行中…'
  }
  if (job.template_type === 'scan-viral') {
    return '依關鍵字搜尋 Threads 爆款候選…'
  }
  if (job.template_type === 'analyze-copy-mission') {
    return '產出研究地圖與預設搜尋標籤…'
  }
  if (job.template_type === 'expand-copy-mission-graph') {
    return '蒐集參考資料並整理延伸知識節點…'
  }
  if (job.template_type === 'generate-copy-matrix') {
    return '依勾選延伸知識產出內容矩陣…'
  }
  if (job.template_type === 'generate-copy-draft') {
    return '分析爆款結構並產出仿寫草稿…'
  }
  if (job.template_type === 'style-8d') {
    switch (job.phase) {
      case 'session':
        return '確認 Chrome session 與 Worker 心跳…'
      case 'samples':
        return '讀取對標帳號近期貼文樣本…'
      case 'style':
        return '交給 AI 分析 D1–D8 風格策略…'
      case 'store':
        return '寫回人設，讓後續產文套用…'
      default:
        return '8D 風格分析進行中…'
    }
  }
  if (job.phase) {
    const label = PHASE_LABEL[job.phase]
    return label ? `目前階段：${label}` : '任務執行中…'
  }
  return '等待背景執行回報進度…'
}

/** 任務 phase 欄位繁中標籤（列表副標等）。 */
export function jobPhaseLabel(phase: string): string {
  const trimmed = phase.trim()
  if (!trimmed) return '—'
  return PHASE_LABEL[trimmed] ?? stepTitle(trimmed)
}

/** 任務觀察站「現在在做」— 終態會改為完成／失敗等繁中說明。 */
export function jobActivitySummary(job: JobData): string {
  if (job.status === 'cancel_requested') return '正在取消任務…'
  if (job.status === 'cancelled') return '任務已取消'
  if (job.status === 'expired') return '任務已過期（執行逾時）'
  if (job.status === 'failed') {
    return jobErrorMessage(job) ?? `${jobTemplateLabel(job.template_type)}失敗`
  }
  if (job.status === 'succeeded') {
    return TERMINAL_ACTIVITY[job.template_type] ?? `${jobTemplateLabel(job.template_type)}已完成`
  }

  const steps = job.progress?.steps ?? []
  const activeStep = steps.find((step) => step.status === 'running')
  if (activeStep?.message && hasCjk(activeStep.message)) {
    return activeStep.message
  }

  const summary = job.progress?.summary?.trim()
  if (summary) {
    const translated = translateGenericSummary(summary, job)
    if (translated) return translated
  }

  return activePhaseHint(job)
}

export function jobStepDetailMessage(message?: string): string | null {
  const trimmed = message?.trim()
  if (!trimmed) return null
  if (/^(running|done)$/i.test(trimmed)) return null
  if (hasCjk(trimmed)) return trimmed
  if (/^running$/i.test(trimmed)) return null
  return trimmed
}

/** 回到發起任務的頁面（不顯示 job id）。 */
export function jobOriginPath(job: JobData): string | null {
  const id = job.scope_id?.trim()
  if (!id) return null

  switch (job.template_type) {
    case 'expand-graph':
      if (job.scope === 'placement_topic') return topicResearchMapPath(id)
      return placementFlowPath('/research', id, 'brand')
    case 'placement-scan':
      if (job.scope === 'placement_topic') return placementFlowPath('/outreach', id, 'topic')
      return placementFlowPath('/outreach', id, 'brand')
    case 'analyze-copy-mission':
    case 'expand-copy-mission-graph':
      return copyMissionDetailPath(id, '#copy-research')
    case 'scan-viral':
    case 'generate-copy-matrix':
    case 'generate-copy-draft':
      if (job.scope === 'copy_mission') return copyMissionDetailPath(id, '#copy-output')
      return `/matrix/missions/${encodeURIComponent(id)}`
    case 'style-8d':
      return `/personas/${encodeURIComponent(id)}`
    default:
      return null
  }
}

export function jobOriginLinkLabel(job: JobData): string {
  switch (job.template_type) {
    case 'expand-graph':
      return job.status === 'succeeded' ? '回到研究地圖勾選 tag →' : '回到研究地圖 →'
    case 'placement-scan':
      return job.status === 'succeeded' ? '回到獲客台 →' : '回到海巡頁 →'
    case 'analyze-copy-mission':
    case 'expand-copy-mission-graph':
    case 'scan-viral':
    case 'generate-copy-matrix':
    case 'generate-copy-draft':
      return job.template_type === 'expand-copy-mission-graph' && job.status === 'succeeded'
        ? '回到延伸知識勾選 →'
        : '回到拷貝任務 →'
    case 'style-8d':
      return '回到人設頁 →'
    default:
      return '回到任務頁 →'
  }
}