/**
 * Phase 3: 批处理模式 - API封装
 */

import request from './request';

// ==================== 类型定义 ====================

export interface BatchTemplate {
  id: string;
  name: string;
  description: string;
  output_fields: Array<{
    key: string;
    label: string;
    type: string;
    description?: string;
  }>;
}

export interface ExecuteBatchParams {
  kb_id: string;
  document_ids: string[];
  template_type: 'preset' | 'custom';
  template_id?: string;
  custom_prompt?: string;
  model_type: string;
  task_name?: string;
}

export interface BatchTask {
  id: string;
  name: string;
  status: 'processing' | 'completed' | 'failed';
  total_documents: number;
  completed_count: number;
  failed_count: number;
  model_type: string;
  started_at: string;
  completed_at?: string;
  duration_seconds?: number;
  created_at: string;
}

export interface BatchResult {
  id: string;
  index: number;
  document_id: string;
  document_name: string;
  status: 'success' | 'failed';
  data: any;
  raw_output?: string;
  error_message?: string;
  processing_time_ms?: number;
  tokens_used?: number;
  created_at: string;
}

export interface BatchTaskWithResults {
  task: BatchTask;
  results: BatchResult[];
}

// ==================== API函数 ====================

/**
 * 获取所有预设模板
 */
export async function getTemplates(): Promise<BatchTemplate[]> {
  const response = await request.get('/batch/templates');
  return response.data;
}

/**
 * 执行批处理任务
 */
export async function executeBatch(params: ExecuteBatchParams): Promise<{
  task_id: string;
  status: string;
  websocket_event: string;
}> {
  const response = await request.post('/batch/execute', params);
  return response.data;
}

/**
 * 获取任务状态
 */
export async function getTask(taskId: string): Promise<BatchTask> {
  const response = await request.get(`/batch/tasks/${taskId}`);
  return response.data;
}

/**
 * 获取任务结果
 */
export async function getTaskResults(taskId: string): Promise<BatchTaskWithResults> {
  const response = await request.get(`/batch/tasks/${taskId}/results`);
  return response.data;
}

/**
 * 重试失败的文档
 */
export async function retryFailed(taskId: string): Promise<void> {
  await request.post(`/batch/tasks/${taskId}/retry-failed`);
}

/**
 * 轮询任务状态直到完成
 */
export async function pollTaskUntilComplete(
  taskId: string,
  onProgress?: (task: BatchTask) => void,
  maxAttempts: number = 120, // 最多10分钟（120次 * 5秒）
): Promise<BatchTask> {
  let attempts = 0;

  while (attempts < maxAttempts) {
    const task = await getTask(taskId);

    if (onProgress) {
      onProgress(task);
    }

    if (task.status === 'completed' || task.status === 'failed') {
      return task;
    }

    // 等待5秒后再次查询
    await new Promise(resolve => setTimeout(resolve, 5000));
    attempts++;
  }

  throw new Error('任务执行超时');
}

export default {
  getTemplates,
  executeBatch,
  getTask,
  getTaskResults,
  retryFailed,
  pollTaskUntilComplete,
};

