import { http } from "@/utils/http";

/** 通用响应结果 */
type Result<T = any> = {
  code: number;
  message: string;
  data?: T;
};

// ==================== 数据结构定义 ====================

/** 会话信息 */
export interface ChatSessionVO {
  sessionId: string; // UUID格式
  sessionTitle: string;
  projectId: string;
  projectName: string;
  timelineNodeId?: string;
  timelineNodeName?: string;
  lastMessageTime: string; // ISO 8601格式
  messageCount: number;
  createTime: string;
}

/** 引用文档 */
export interface ReferencedDocVO {
  id: number;
  docId: string;
  title: string;
  docType: string;
  fileType: string;
  sourceType: string;
  score: number; // 相似度分数 0-1
  content: string; // 内容摘要
}

/** 对话消息 */
export interface ChatMessageVO {
  id: number;
  role: "user" | "assistant" | "system";
  content: string;
  referencedDocs?: ReferencedDocVO[];
  model?: string;
  tokensUsed?: number;
  responseTime?: number;
  messageIndex: number;
  createTime: string;
}

/** 知识库文档 */
export interface KbDocumentVO {
  id: string; // UUID格式
  docId?: string; // 可能为空
  title: string;
  docType: string; // report/document/text/data/other
  fileType: string; // pdf/doc/txt/md等
  fileSize: string; // 字节
  filePath: string;
  fileUrl?: string; // 文件访问URL
  sourceType: string; // upload/project/risk等
  chunkCount: number; // 分块数量
  status: "pending" | "processing" | "active" | "error";
  createByName: string;
  createTime: string;
}

/** 文档分片VO */
export interface DocumentChunkVO {
  id: string; // 分片ID
  docId: string; // 原始文档ID
  content: string; // 分片内容
  chunkIndex: number; // 分片序号
  chunkTotal: number; // 总分片数
  title: string; // 文档标题
  docType: string; // 文档类型
  sourceType: string; // 来源类型
  status: string; // 状态
}

/** 文档状态 */
export type DocumentStatus = "pending" | "processing" | "active" | "error";

// ==================== SSE事件数据类型 ====================

/** SSE start 事件数据 */
export interface SSEStartData {
  sessionId: string;
  isNewSession: boolean;
}

/** SSE chunk 事件数据 */
export interface SSEChunkData {
  content: string;
}

/** SSE references 事件数据 */
export interface SSEReferencesData {
  docs: ReferencedDocVO[];
}

/** SSE complete 事件数据 */
export interface SSECompleteData {
  messageId: number;
  tokensUsed: number;
}

/** SSE error 事件数据 */
export interface SSEErrorData {
  message: string;
}

// ==================== 请求参数类型 ====================

/** 创建会话请求参数 */
export interface CreateSessionRequest {
  projectId: string;
  timelineNodeId?: string | null;
  firstMessage?: string;
  sessionTitle?: string;
}

/** SSE对话请求参数 */
export interface SSEChatParams {
  sessionId?: string; // UUID格式，为空则新建会话
  projectId: string;
  timelineNodeId?: string;
  message: string;
  useRag?: boolean; // 默认true
  useTextToSql?: boolean; // 默认false
  contextWindow?: number; // 默认10
}

/** 上传文件请求参数 */
export interface UploadDocumentParams {
  projectId: string;
  file: File;
}

// ==================== AI对话接口 ====================

/** 新建会话 */
export const createChatSession = (data: CreateSessionRequest) => {
  return http.request<Result<ChatSessionVO>>(
    "post",
    "/api/v1/ai/chat/session",
    {
      data
    }
  );
};

/** 获取会话列表 */
export const getChatSessions = (projectId: string) => {
  return http.request<Result<ChatSessionVO[]>>(
    "get",
    "/api/v1/ai/chat/sessions",
    {
      params: { projectId }
    }
  );
};

/** 获取会话历史消息 */
export const getSessionMessages = (sessionId: string) => {
  return http.request<Result<ChatMessageVO[]>>(
    "get",
    `/api/v1/ai/chat/session/${sessionId}/messages`
  );
};

/** 删除会话 */
export const deleteChatSession = (sessionId: string) => {
  return http.request<Result<void>>(
    "delete",
    `/api/v1/ai/chat/session/${sessionId}`
  );
};

/** 构建SSE URL */
export const buildSSEUrl = (params: SSEChatParams): string => {
  const queryParams = new URLSearchParams();

  if (params.sessionId) {
    queryParams.append("sessionId", params.sessionId);
  }
  queryParams.append("projectId", String(params.projectId));
  if (params.timelineNodeId !== undefined) {
    queryParams.append("timelineNodeId", String(params.timelineNodeId));
  }
  queryParams.append("message", params.message);
  if (params.useRag !== undefined) {
    queryParams.append("useRag", String(params.useRag));
  }
  if (params.useTextToSql !== undefined) {
    queryParams.append("useTextToSql", String(params.useTextToSql));
  }
  if (params.contextWindow !== undefined) {
    queryParams.append("contextWindow", String(params.contextWindow));
  }

  return `/api/v1/ai/chat/sse?${queryParams.toString()}`;
};

// ==================== 知识库接口 ====================

/** 上传文档 */
export const uploadDocument = (params: UploadDocumentParams) => {
  const formData = new FormData();
  formData.append("projectId", String(params.projectId));
  formData.append("file", params.file);

  return http.request<Result<KbDocumentVO>>("post", "/api/v1/ai/kb/upload", {
    data: formData,
    headers: {
      "Content-Type": undefined // 让浏览器自动设置 multipart/form-data
    }
  });
};

/** 获取文档列表 */
export const getDocuments = (projectId: string) => {
  return http.request<Result<KbDocumentVO[]>>(
    "get",
    "/api/v1/ai/kb/documents",
    {
      params: { projectId }
    }
  );
};

/** 删除文档 */
export const deleteDocument = (docId: string) => {
  return http.request<Result<void>>(
    "delete",
    `/api/v1/ai/kb/document/${docId}`
  );
};

/** 重新索引文档 */
export const reindexDocument = (docId: string) => {
  return http.request<Result<void>>(
    "post",
    `/api/v1/ai/kb/document/${docId}/reindex`
  );
};

/** 获取文档分片列表 */
export const getDocumentChunks = (docId: string) => {
  return http.request<Result<DocumentChunkVO[]>>(
    "get",
    `/api/v1/ai/kb/document/${docId}/chunks`
  );
};

/** 获取分片详情 */
export const getChunkDetail = (chunkId: string) => {
  return http.request<Result<DocumentChunkVO>>(
    "get",
    `/api/v1/ai/kb/chunk/${chunkId}`
  );
};
