import { api } from '../api/client'
import type { JobData, PersonaData } from '../types/api'
import { isActiveJobStatus } from './jobStatus'

export function copyAnalyzeActionLabel(
  analyzeJob: JobData | null | undefined,
  analyzing: boolean,
  mapReady: boolean,
): string {
  if (analyzing || (analyzeJob != null && isActiveJobStatus(analyzeJob.status))) {
    return '產生中…'
  }
  return mapReady ? '重新產生研究地圖' : '產生研究地圖'
}

export const VIRAL_SCAN_PIPELINE_STEPS = [
  { id: 'viral_crawl', title: '爆款海巡', hint: '僅掃你勾選的標籤，節省搜尋配額' },
] as const

export const ANALYZE_COPY_MISSION_PIPELINE_STEPS = [
  { id: 'copy_mission_map', title: '研究地圖', hint: '一次 LLM 產出地圖與搜尋標籤' },
] as const

export const GENERATE_COPY_MATRIX_PIPELINE_STEPS = [
  { id: 'copy_matrix_generate', title: '內容矩陣', hint: '依爆款樣本產出 5 篇矩陣草稿' },
] as const

export const GENERATE_COPY_DRAFT_PIPELINE_STEPS = [
  { id: 'copy_draft_generate', title: '深仿寫', hint: '分析爆款結構後產出單篇仿寫草稿' },
] as const

export type CopyFlowStepKey = 'research' | 'output'

export type CopyFlowStep = {
  key: CopyFlowStepKey
  step: string
  label: string
  shortLabel: string
  desc: string
  hash: string
}

/** 拷貝忍者子步驟（同一任務頁錨點捲動） */
export const COPY_FLOW: CopyFlowStep[] = [
  {
    key: 'research',
    step: '01',
    label: '研究地圖',
    shortLabel: '研究',
    desc: '受眾方向、建議搜尋標籤',
    hash: '#copy-research',
  },
  {
    key: 'output',
    step: '02',
    label: '海巡產文',
    shortLabel: '產文',
    desc: '海巡爆款、產出矩陣或深仿寫草稿',
    hash: '#copy-output',
  },
]

export function copyMissionDetailPath(missionId: string, hash?: string) {
  const base = `/matrix/missions/${encodeURIComponent(missionId.trim())}`
  if (!hash?.trim()) return base
  const normalized = hash.startsWith('#') ? hash : `#${hash}`
  return `${base}${normalized}`
}

const ACTIVE_COPY_PERSONA_KEY = 'haixun.copyPersonaId'
const LEGACY_COPY_PERSONA_KEY = 'haixun.copy.personaId'
export const COPY_PERSONA_CHANGED_EVENT = 'haixun.copy-persona-changed'

export function rememberCopyPersonaId(personaId: string) {
  const id = personaId.trim()
  if (!id) return
  try {
    sessionStorage.setItem(ACTIVE_COPY_PERSONA_KEY, id)
    window.dispatchEvent(new CustomEvent(COPY_PERSONA_CHANGED_EVENT, { detail: { id } }))
  } catch {
    // ignore
  }
}

export function getActiveCopyPersonaId(): string {
  try {
    const current = sessionStorage.getItem(ACTIVE_COPY_PERSONA_KEY)?.trim() ?? ''
    if (current) return current
    const legacy = sessionStorage.getItem(LEGACY_COPY_PERSONA_KEY)?.trim() ?? ''
    if (legacy) {
      sessionStorage.setItem(ACTIVE_COPY_PERSONA_KEY, legacy)
      sessionStorage.removeItem(LEGACY_COPY_PERSONA_KEY)
      return legacy
    }
    return ''
  } catch {
    return ''
  }
}

/** Pick a valid persona id from the list; clears stale session values. */
export function resolveCopyPersonaId(personas: PersonaData[], preferredId?: string): string {
  if (!personas.length) return ''
  const preferred = preferredId?.trim()
  if (preferred && personas.some((item) => item.id === preferred)) return preferred
  return personas[0]?.id ?? ''
}

export function findPersonaInList(personas: PersonaData[], personaId: string): PersonaData | undefined {
  const id = personaId.trim()
  if (!id) return undefined
  return personas.find((item) => item.id === id)
}

export function isPersonaNotFoundError(message: string): boolean {
  const text = message.trim()
  return /找不到人設|persona.*not found|404/i.test(text)
}

export async function listCopyMissionJobs(missionId: string, pageSize = 20) {
  const id = missionId.trim()
  if (!id) return [] as JobData[]
  const data = await api.get<{ list: JobData[] }>('/api/v1/jobs', {
    auth: true,
    query: { page: 1, pageSize, scope: 'copy_mission', scope_id: id },
  })
  return data.list ?? []
}

export function pickActiveCopyMissionAnalyzeJob(jobs: JobData[]): JobData | null {
  return (
    jobs.find((job) => job.template_type === 'analyze-copy-mission' && isActiveJobStatus(job.status)) ??
    null
  )
}

export function pickActiveCopyMissionScanJob(jobs: JobData[]): JobData | null {
  return jobs.find((job) => job.template_type === 'scan-viral' && isActiveJobStatus(job.status)) ?? null
}

export function pickActiveCopyMissionMatrixJob(jobs: JobData[]): JobData | null {
  return (
    jobs.find((job) => job.template_type === 'generate-copy-matrix' && isActiveJobStatus(job.status)) ??
    null
  )
}

export function pickActiveCopyMissionReplicateJobs(jobs: JobData[]): JobData[] {
  return jobs.filter(
    (job) => job.template_type === 'generate-copy-draft' && isActiveJobStatus(job.status),
  )
}

export function replicateJobScanPostId(job: JobData): string {
  const id = job.payload?.scan_post_id
  return typeof id === 'string' ? id.trim() : ''
}