/**
 * 全局任务轮询服务

避免多个组件/页面同时轮询，统一管理任务状态更新

特性：
1. 获取所有 generate_skill 类型的任务（包括已完成）
2. 通知新完成的任务
3. 支持页面关闭后继续追踪
 */
import { taskService } from './taskService'

interface TaskPollingCallbacks {
  onTasksUpdate?: (tasks: any[]) => void
  onTaskCompleted?: (task: any) => void  // 新增：任务完成回调
}

class TaskPollingService {
  private pollTimer: any = null
  private isPolling = false
  private isPageVisible = true
  private listeners: Set<TaskPollingCallbacks> = new Set()
  private currentTasks: any[] = []
  private completedTaskIds: Set<string> = new Set()  // 追踪已通知完成的任务
  private recentCompletedTasks: any[] = []  // 最近完成的任务（5分钟内）

  constructor() {
    // 监听页面可见性
    document.addEventListener('visibilitychange', this.handleVisibilityChange)
  }

  private handleVisibilityChange = () => {
    this.isPageVisible = !document.hidden

    if (this.isPageVisible) {
      // 页面重新可见时，立即刷新并开始轮询
      this.fetchTasks()
      if (!this.isPolling && this.listeners.size > 0) {
        this.startPolling()
      }
    } else {
      // 页面不可见时，停止轮询
      this.stopPolling()
    }
  }

  /**
   * 订阅任务更新
   */
  subscribe(callbacks: TaskPollingCallbacks): () => void {
    this.listeners.add(callbacks)

    // 如果有新的订阅者且没有在轮询，开始轮询
    if (this.listeners.size === 1 && !this.isPolling) {
      this.startPolling()
    }

    // 立即返回当前的任务状态
    if (callbacks.onTasksUpdate && this.currentTasks.length > 0) {
      callbacks.onTasksUpdate(this.currentTasks)
    }

    // 返回取消订阅函数
    return () => {
      this.listeners.delete(callbacks)

      // 如果没有订阅者了，停止轮询
      if (this.listeners.size === 0) {
        this.stopPolling()
      }
    }
  }

  /**
   * 开始轮询
   */
  private startPolling() {
    if (this.isPolling) return

    this.isPolling = true
    this.poll()
  }

  /**
   * 停止轮询
   */
  private stopPolling() {
    this.isPolling = false
    if (this.pollTimer) {
      clearTimeout(this.pollTimer)
      this.pollTimer = null
    }
  }

  /**
   * 执行轮询
   */
  private async poll() {
    if (!this.isPolling || !this.isPageVisible) {
      return
    }

    try {
      await this.fetchTasks()
    } catch (error) {
      console.error('Task polling error:', error)
    }

    // 继续轮询（10秒间隔）
    if (this.isPolling && this.isPageVisible) {
      this.pollTimer = setTimeout(() => this.poll(), 10000)
    }
  }

  /**
   * 获取任务列表（包括正在运行和最近完成的任务）
   */
  private async fetchTasks() {
    try {
      // 获取所有 generate_skill 类型的任务
      const response = await taskService.listTasks({
        type: 'generate_skill'
      }) as any

      console.log('[TaskPollingService] Fetched tasks:', response)

      // 转换数据格式
      // 注意：后端返回的 ID 字段名可能是 taskId 或 id，需要兼容处理
      const tasks = (response || []).map((task: any) => ({
        id: task.taskId || task.id,  // 兼容两种字段名
        type: task.type,
        status: task.status,
        progress: task.progress || { current: 0, total: 100, message: '', stage: null },
        params: task.params || {},
        result: task.result,
        error: task.error,
        project_id: task.projectId || task.project_id,
        created_at: task.created_at,
        updated_at: task.updated_at
      }))

      console.log('[TaskPollingService] Mapped tasks:', tasks)

      // 分离正在运行和已完成的任务
      const runningTasks = tasks.filter((t: any) => t.status === 'running')
      const newlyCompletedTasks = tasks.filter((t: any) =>
        t.status === 'completed' && !this.completedTaskIds.has(t.id)
      )

      // 更新已完成任务追踪
      if (newlyCompletedTasks.length > 0) {
        console.log('[TaskPollingService] Newly completed tasks:', newlyCompletedTasks)

        newlyCompletedTasks.forEach((task: any) => {
          this.completedTaskIds.add(task.id)
          this.recentCompletedTasks.push(task)

          // 通知所有订阅者有新任务完成
          this.listeners.forEach(callbacks => {
            if (callbacks.onTaskCompleted) {
              callbacks.onTaskCompleted(task)
            }
          })
        })

        // 清理超过5分钟的已完成任务
        const fiveMinutesAgo = Date.now() - 5 * 60 * 1000
        this.recentCompletedTasks = this.recentCompletedTasks.filter((t: any) => {
          const taskTime = new Date(t.updated_at).getTime()
          return taskTime > fiveMinutesAgo
        })
      }

      // 返回：正在运行的任务 + 最近完成的任务
      this.currentTasks = [...runningTasks, ...this.recentCompletedTasks]

      // 通知所有订阅者
      this.listeners.forEach(callbacks => {
        if (callbacks.onTasksUpdate) {
          callbacks.onTasksUpdate(this.currentTasks)
        }
      })
    } catch (error) {
      console.error('[TaskPollingService] Failed to fetch tasks:', error)
    }
  }

  /**
   * 手动刷新任务列表
   */
  refresh() {
    this.fetchTasks()
  }

  /**
   * 获取当前任务列表
   */
  getCurrentTasks(): any[] {
    return this.currentTasks
  }

  /**
   * 销毁服务
   */
  destroy() {
    this.stopPolling()
    this.listeners.clear()
    document.removeEventListener('visibilitychange', this.handleVisibilityChange)
  }
}

// 全局单例
let pollingService: TaskPollingService | null = null

export const getTaskPollingService = () => {
  if (!pollingService) {
    pollingService = new TaskPollingService()
  }
  return pollingService
}

/**
 * React Hook 用于订阅任务更新
 */
export const useTaskPolling = (callback: (tasks: any[]) => void) => {
  const service = getTaskPollingService()

  // 组件挂载时订阅
  const subscribe = () => {
    const unsubscribe = service.subscribe({
      onTasksUpdate: callback
    })
    return unsubscribe
  }

  return { service, subscribe }
}
