/**
 * ASL模块 - API客户端
 * 
 * 负责所有与后端的API交互
 */

import type {
  ScreeningProject,
  CreateProjectRequest,
  Literature,
  ScreeningResult,
  ScreeningTask,
  ApiResponse,
  PaginatedResponse,
  ProjectStatistics
} from '../types';

// API基础URL
const API_BASE_URL = '/api/v1/asl';

// 通用请求函数
async function request<T = any>(
  url: string,
  options?: RequestInit
): Promise<T> {
  const response = await fetch(`${API_BASE_URL}${url}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options?.headers,
    },
  });

  if (!response.ok) {
    // 尝试解析错误响应
    let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
    try {
      const errorData = await response.json();
      errorMessage = errorData.error || errorData.message || errorMessage;
    } catch (e) {
      // 如果响应体不是JSON，使用状态文本
      const text = await response.text().catch(() => '');
      if (text) {
        errorMessage = text;
      }
    }
    console.error('❌ API请求失败:', { url: `${API_BASE_URL}${url}`, status: response.status, error: errorMessage });
    throw new Error(errorMessage);
  }

  return response.json();
}

// ==================== 项目管理API ====================

/**
 * 创建筛选项目
 */
export async function createProject(
  data: CreateProjectRequest
): Promise<ApiResponse<ScreeningProject>> {
  return request('/projects', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

/**
 * 获取项目列表
 */
export async function listProjects(): Promise<ApiResponse<ScreeningProject[]>> {
  return request('/projects');
}

/**
 * 获取项目详情
 */
export async function getProject(
  projectId: string
): Promise<ApiResponse<ScreeningProject>> {
  return request(`/projects/${projectId}`);
}

/**
 * 更新项目
 */
export async function updateProject(
  projectId: string,
  data: Partial<CreateProjectRequest>
): Promise<ApiResponse<ScreeningProject>> {
  return request(`/projects/${projectId}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  });
}

/**
 * 删除项目
 */
export async function deleteProject(
  projectId: string
): Promise<ApiResponse<void>> {
  return request(`/projects/${projectId}`, {
    method: 'DELETE',
  });
}

// ==================== 文献管理API ====================

/**
 * 批量导入文献（JSON格式）
 */
export async function importLiteratures(data: {
  projectId: string;
  literatures: Array<Omit<Literature, 'id' | 'projectId' | 'createdAt'>>;
}): Promise<ApiResponse<{
  importedCount: number;
}>> {
  return request('/literatures/import', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

/**
 * 获取文献列表
 */
export async function listLiteratures(
  projectId: string,
  params?: {
    page?: number;
    pageSize?: number;
  }
): Promise<ApiResponse<PaginatedResponse<Literature>>> {
  const queryString = new URLSearchParams(
    params as Record<string, string>
  ).toString();
  return request(`/projects/${projectId}/literatures?${queryString}`);
}

/**
 * 删除文献
 */
export async function deleteLiterature(
  projectId: string,
  literatureId: string
): Promise<ApiResponse<void>> {
  return request(`/projects/${projectId}/literatures/${literatureId}`, {
    method: 'DELETE',
  });
}

// ==================== 筛选任务API ====================

/**
 * 启动筛选任务
 */
export async function startScreening(
  projectId: string
): Promise<ApiResponse<{ taskId: string }>> {
  return request(`/projects/${projectId}/screening/start`, {
    method: 'POST',
  });
}

/**
 * 查询任务进度
 */
export async function getTaskProgress(
  taskId: string
): Promise<ApiResponse<ScreeningTask>> {
  return request(`/screening/tasks/${taskId}/progress`);
}

// ==================== 筛选结果API ====================

/**
 * 获取筛选结果列表
 */
export async function getScreeningResults(
  projectId: string,
  params?: {
    conflictOnly?: boolean;
    finalDecision?: 'include' | 'exclude' | 'pending';
    page?: number;
    pageSize?: number;
  }
): Promise<ApiResponse<PaginatedResponse<ScreeningResult>>> {
  const queryString = new URLSearchParams(
    params as Record<string, string>
  ).toString();
  return request(`/projects/${projectId}/screening/results?${queryString}`);
}

/**
 * 更新单个筛选结果
 */
export async function updateScreeningResult(
  resultId: string,
  data: {
    finalDecision?: 'include' | 'exclude' | 'pending';
    reviewComment?: string;
  }
): Promise<ApiResponse<ScreeningResult>> {
  return request(`/screening/results/${resultId}`, {
    method: 'PUT',
    body: JSON.stringify(data),
  });
}

/**
 * 批量更新筛选结果
 */
export async function batchUpdateScreeningResults(data: {
  resultIds: string[];
  finalDecision: 'include' | 'exclude' | 'pending';
  decisionMethod?: string;
  reviewComment?: string;
}): Promise<ApiResponse<{ updated: number }>> {
  return request('/screening/results/batch-update', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

// ==================== 导出API ====================

/**
 * 导出筛选结果为Excel
 */
export async function exportScreeningResults(
  projectId: string,
  params?: {
    filter?: 'all' | 'included' | 'excluded' | 'pending';
  }
): Promise<Blob> {
  const queryString = new URLSearchParams(
    params as Record<string, string>
  ).toString();
  
  const response = await fetch(
    `${API_BASE_URL}/projects/${projectId}/screening/results/export?${queryString}`
  );

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  return response.blob();
}

// ==================== 统计API ====================

/**
 * 获取项目统计信息
 */
export async function getProjectStatistics(
  projectId: string
): Promise<ApiResponse<ProjectStatistics>> {
  return request(`/projects/${projectId}/statistics`);
}

// ==================== Day 3 新增API ====================

/**
 * 获取筛选任务进度（新）
 * GET /projects/:projectId/screening-task
 */
export async function getScreeningTask(
  projectId: string
): Promise<ApiResponse<ScreeningTask>> {
  return request(`/projects/${projectId}/screening-task`);
}

/**
 * 获取筛选结果列表（新，支持分页和筛选）
 * GET /projects/:projectId/screening-results
 */
export async function getScreeningResultsList(
  projectId: string,
  params?: {
    page?: number;
    pageSize?: number;
    filter?: 'all' | 'conflict' | 'included' | 'excluded' | 'pending' | 'reviewed';
  }
): Promise<ApiResponse<{
  items: ScreeningResult[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}>> {
  const queryString = new URLSearchParams(
    params as Record<string, string>
  ).toString();
  return request(`/projects/${projectId}/screening-results?${queryString}`);
}

/**
 * 获取单个筛选结果详情（新）
 * GET /screening-results/:resultId
 */
export async function getScreeningResultDetail(
  resultId: string
): Promise<ApiResponse<ScreeningResult>> {
  return request(`/screening-results/${resultId}`);
}

/**
 * 提交人工复核（新）
 * POST /screening-results/:resultId/review
 */
export async function reviewScreeningResult(
  resultId: string,
  data: {
    decision: 'include' | 'exclude';
    note?: string;
  }
): Promise<ApiResponse<ScreeningResult>> {
  return request(`/screening-results/${resultId}/review`, {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

// ==================== 健康检查API ====================

/**
 * 模块健康检查
 */
export async function healthCheck(): Promise<ApiResponse<{
  status: string;
  module: string;
}>> {
  return request('/health');
}

// ==================== 统一导出API对象 ====================

/**
 * ASL API统一导出对象
 */
export const aslApi = {
  // 项目管理
  createProject,
  listProjects,
  getProject,
  updateProject,
  deleteProject,
  
  // 文献管理
  importLiteratures,
  listLiteratures,
  deleteLiterature,
  
  // 筛选任务
  startScreening,
  getTaskProgress,
  getScreeningTask, // Day 3 新增
  
  // 筛选结果
  getScreeningResults,
  getScreeningResultsList, // Day 3 新增（分页版本）
  getScreeningResultDetail, // Day 3 新增
  updateScreeningResult,
  batchUpdateScreeningResults,
  reviewScreeningResult, // Day 3 新增（人工复核）
  
  // 导出
  exportScreeningResults,
  
  // 统计
  getProjectStatistics,
  
  // 健康检查
  healthCheck,
};
