// 知识库 API — 对接 Gateway REST API

import { request } from './client';

/** 知识库 */
export interface KnowledgeBase {
  id: string;
  user_id: string;
  name: string;
  description: string;
  document_count: number;
  created_at: string;
  updated_at: string;
}

/** 知识库文档 */
export interface KnowledgeDocument {
  id: string;
  kb_id: string;
  title: string;
  content_type: string;
  source_type: string;
  source_ref: string;
  chunk_count: number;
  created_at: string;
}

/** 搜索结果 */
export interface SearchChunkResult {
  chunk_id: string;
  doc_id: string;
  kb_id: string;
  content: string;
  rank: number;
  headline: string;
  doc_title: string;
  kb_name: string;
}

/** 知识库列表响应 */
interface KBListResponse {
  knowledge_bases: KnowledgeBase[];
  total: number;
}

/** 文档列表响应 */
interface DocListResponse {
  documents: KnowledgeDocument[];
}

/** 搜索响应 */
interface SearchResponse {
  chunks: SearchChunkResult[];
  total: number;
  query: string;
}

// ========== 知识库 CRUD ==========

/** 创建知识库 */
export async function createKB(name: string, description?: string): Promise<KnowledgeBase> {
  const res = await request<KnowledgeBase>(`/knowledge/bases`, {
    method: 'POST',
    body: JSON.stringify({ name, description }),
  });
  if (res.error) throw new Error(res.error);
  return res.data!;
}

/** 列出知识库 */
export async function listKBs(): Promise<KnowledgeBase[]> {
  const res = await request<KBListResponse>(`/knowledge/bases`);
  if (res.error) throw new Error(res.error);
  return res.data?.knowledge_bases || [];
}

/** 获取知识库 */
export async function getKB(id: string): Promise<KnowledgeBase> {
  const res = await request<KnowledgeBase>(`/knowledge/bases/${id}`);
  if (res.error) throw new Error(res.error);
  return res.data!;
}

/** 更新知识库 */
export async function updateKB(id: string, name: string, description?: string): Promise<KnowledgeBase> {
  const res = await request<KnowledgeBase>(`/knowledge/bases/${id}`, {
    method: 'PUT',
    body: JSON.stringify({ name, description }),
  });
  if (res.error) throw new Error(res.error);
  return res.data!;
}

/** 删除知识库 */
export async function deleteKB(id: string): Promise<boolean> {
  const res = await request<{ message: string }>(`/knowledge/bases/${id}`, {
    method: 'DELETE',
  });
  return !res.error;
}

// ========== 文档管理 ==========

/** 添加文档 (文本内容) */
export async function addDocument(
  kbId: string,
  title: string,
  content: string,
  sourceType: 'text' | 'url' = 'text',
): Promise<KnowledgeDocument> {
  const res = await request<KnowledgeDocument>(`/knowledge/bases/${kbId}/documents`, {
    method: 'POST',
    body: JSON.stringify({ title, content, source_type: sourceType }),
  });
  if (res.error) throw new Error(res.error);
  return res.data!;
}

/** 从文件添加文档 */
export async function addDocumentFromFile(
  kbId: string,
  title: string,
  fileId: string,
): Promise<KnowledgeDocument> {
  const res = await request<KnowledgeDocument>(`/knowledge/bases/${kbId}/documents`, {
    method: 'POST',
    body: JSON.stringify({ title, source_type: 'file', file_id: fileId }),
  });
  if (res.error) throw new Error(res.error);
  return res.data!;
}

/** 列出文档 */
export async function listDocuments(kbId: string): Promise<KnowledgeDocument[]> {
  const res = await request<DocListResponse>(`/knowledge/bases/${kbId}/documents`);
  if (res.error) throw new Error(res.error);
  return res.data?.documents || [];
}

/** 获取文档 */
export async function getDocument(id: string): Promise<KnowledgeDocument> {
  const res = await request<KnowledgeDocument>(`/knowledge/documents/${id}`);
  if (res.error) throw new Error(res.error);
  return res.data!;
}

/** 删除文档 */
export async function deleteDocument(id: string): Promise<boolean> {
  const res = await request<{ message: string }>(`/knowledge/documents/${id}`, {
    method: 'DELETE',
  });
  return !res.error;
}

// ========== 搜索 ==========

/** 搜索知识库 */
export async function searchKnowledge(
  query: string,
  kbIds?: string[],
  limit?: number,
): Promise<SearchResponse> {
  const res = await request<SearchResponse>(`/knowledge/search`, {
    method: 'POST',
    body: JSON.stringify({ query, kb_ids: kbIds, limit: limit || 10 }),
  });
  if (res.error) throw new Error(res.error);
  return res.data!;
}
