/**
 * 异步任务服务
 */
import api from './api'
import type { TaskProgress } from '@/components/TaskProgressTracker'

export interface CreateTaskRequest {
  type: string
  params: Record<string, any>
  projectId?: string
}

export interface CreateTaskResponse {
  success: boolean
  taskId: string
  message: string
}

export const taskService = {
  /**
   * 创建异步任务
   */
  createTask: async (request: CreateTaskRequest) => {
    return await api.post<CreateTaskResponse>('/tasks', request)
  },

  /**
   * 获取任务详情
   */
  getTask: async (taskId: string) => {
    return await api.get<TaskProgress>(`/tasks/${taskId}`)
  },

  /**
   * 列出任务
   */
  listTasks: async (params?: {
    type?: string
    projectId?: string
    status?: string
  }) => {
    // 后端期望的参数名是 task_type 而不是 type
    const apiParams: any = {}
    if (params?.type) {
      apiParams.task_type = params.type
    }
    if (params?.projectId) {
      apiParams.project_id = params.projectId
    }
    if (params?.status) {
      apiParams.status = params.status
    }
    return await api.get<TaskProgress[]>('/tasks', { params: apiParams })
  },

  /**
   * 取消任务
   */
  cancelTask: async (taskId: string) => {
    return await api.post(`/tasks/${taskId}/cancel`)
  },

  /**
   * 删除任务
   */
  deleteTask: async (taskId: string) => {
    return await api.delete(`/tasks/${taskId}`)
  },

  /**
   * 获取项目的所有任务
   */
  getProjectTasks: async (projectId: string) => {
    return await api.get<TaskProgress[]>(`/tasks/project/${projectId}`)
  },

  // ============================================================================
  // AI 生成任务快捷方法
  // ============================================================================

  /**
   * 异步生成人物设定
   */
  generateCharacters: async (params: {
    idea: string
    projectName?: string
    genre?: string
    totalEpisodes?: number
    skills?: Array<{ id: string; name: string; behavior: string }>
    customPrompt?: string
    projectId?: string
  }) => {
    return await api.post<CreateTaskResponse>('/ai-assistant/async/generate/characters', params)
  },

  /**
   * 异步生成大纲
   */
  generateOutline: async (params: {
    idea: string
    totalEpisodes?: number
    genre?: string
    projectName?: string
    skills?: Array<{ id: string; name: string; behavior: string }>
    customPrompt?: string
    projectId?: string
  }) => {
    return await api.post<CreateTaskResponse>('/ai-assistant/async/generate/outline', params)
  },

  /**
   * 异步生成世界观
   */
  generateWorld: async (params: {
    idea: string
    projectName?: string
    genre?: string
    skills?: Array<{ id: string; name: string; behavior: string }>
    customPrompt?: string
    projectId?: string
  }) => {
    return await api.post<CreateTaskResponse>('/ai-assistant/async/generate/world', params)
  },

  /**
   * 异步生成技能
   */
  generateSkill: async (params: {
    description: string
    category?: string
    tags?: string[]
    temperature?: number
  }): Promise<CreateTaskResponse> => {
    return await api.post<CreateTaskResponse>('/skills/async/generate', params)
  },

  /**
   * 轮询任务直到完成
   * @param taskId 任务ID
   * @param onUpdate 进度更新回调
   * @param interval 轮询间隔（毫秒）
   * @returns Promise<任务结果>
   */
  pollTask: async (
    taskId: string,
    onUpdate?: (progress: any) => void,
    interval = 1000
  ): Promise<any> => {
    return new Promise((resolve, reject) => {
      const poll = async () => {
        try {
          // 后端返回的是 TaskResponse，包含 taskId, type, status, progress 等字段
          const taskResponse = await api.get<any>(`/tasks/${taskId}`)
          console.log('Poll task response:', taskResponse)

          // 调用进度更新回调，传递完整的任务信息
          onUpdate?.(taskResponse)

          // 检查任务状态
          if (taskResponse.status === 'completed') {
            resolve({ success: true, result: taskResponse.result })
            return
          }

          if (taskResponse.status === 'failed') {
            reject(new Error(taskResponse.error || '任务执行失败'))
            return
          }

          // 继续轮询
          setTimeout(poll, interval)
        } catch (err) {
          reject(err)
        }
      }

      poll()
    })
  }
}
