import { api } from '../../api/client'
import { registerIslanderActionHandler } from './actionExecutor'
import type { IslanderAction, IslanderExecutorContext } from './types'
import type { KnowledgeGraphData, KnowledgeGraphNode } from '../knowledgeGraph'

export const RESEARCH_SCAN_EVENT = 'haixun.research-scan-started'

type ResearchHandlers = {
  brandId: string
  getSeedQuery: () => string
  getDraftNodes: () => KnowledgeGraphNode[]
  toggleNode: (nodeId: string, selected: boolean) => void
  saveSelection: () => Promise<KnowledgeGraphData>
  onExpandStarted: (jobId: string, message?: string) => void
  onScanStarted: (jobId: string, message?: string) => void
}

let handlers: ResearchHandlers | null = null

export function bindResearchIslanderActions(next: ResearchHandlers) {
  handlers = next
}

export function unbindResearchIslanderActions() {
  handlers = null
}

let registered = false

export function ensureResearchActionHandlers() {
  if (registered) return
  registered = true

  registerIslanderActionHandler('expandKnowledgeGraph', async (action) => {
    const typed = action as Extract<IslanderAction, { type: 'expandKnowledgeGraph' }>
    if (!handlers?.brandId) {
      return { action, ok: false, detail: '請在海巡研究頁使用此操作' }
    }
    const seed = typed.seed_query?.trim() || handlers.getSeedQuery().trim()
    if (!seed) {
      return { action, ok: false, detail: '請先填寫種子詞' }
    }
    try {
      const data = await api.post<{ job_id: string; message?: string }>(
        `/api/v1/brands/${encodeURIComponent(handlers.brandId)}/knowledge-graph/expand`,
        { seed_query: seed, supplemental: !!typed.supplemental },
        { auth: true },
      )
      handlers.onExpandStarted(data.job_id, data.message)
      return {
        action,
        ok: true,
        detail: data.message ?? `已觸發圖譜擴展（job ${data.job_id}）`,
      }
    } catch (e) {
      const message = e instanceof Error ? e.message : '觸發圖譜擴展失敗'
      return { action, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('toggleGraphNode', async (action) => {
    const typed = action as Extract<IslanderAction, { type: 'toggleGraphNode' }>
    if (!handlers) {
      return { action, ok: false, detail: '請在海巡研究頁使用此操作' }
    }
    const nodeId = typed.node_id?.trim()
    if (!nodeId) {
      return { action, ok: false, detail: '缺少 node_id' }
    }
    handlers.toggleNode(nodeId, !!typed.selected)
    return {
      action,
      ok: true,
      detail: typed.selected ? `已勾選節點 ${nodeId}` : `已取消勾選 ${nodeId}`,
    }
  })

  registerIslanderActionHandler('startScan', async (action, ctx: IslanderExecutorContext) => {
    if (!handlers?.brandId) {
      return { action, ok: false, detail: '請在海巡研究頁使用此操作' }
    }
    try {
      const selected = handlers.getDraftNodes().filter((node) => node.selected_for_scan)
      if (selected.length === 0) {
        return { action, ok: false, detail: '請先勾選至少一個節點' }
      }
      const saved = await handlers.saveSelection()
      const data = await api.post<{ job_id: string; message?: string }>(
        `/api/v1/brands/${encodeURIComponent(handlers.brandId)}/scan-jobs`,
        { dual_track: true, graph_id: saved.id },
        { auth: true },
      )
      handlers.onScanStarted(data.job_id, data.message)
      window.dispatchEvent(
        new CustomEvent(RESEARCH_SCAN_EVENT, {
          detail: { jobId: data.job_id, message: data.message },
        }),
      )
      const outreachPath = `/outreach?brand=${encodeURIComponent(handlers.brandId)}`
      ctx.navigate(outreachPath)
      return {
        action,
        ok: true,
        detail: data.message ?? `雙軌海巡已啟動（job ${data.job_id}）`,
      }
    } catch (e) {
      const message = e instanceof Error ? e.message : '啟動海巡失敗'
      return { action, ok: false, detail: message }
    }
  })
}