// Knowledge Base API

const API_BASE = 'http://localhost:8082'

export interface KnowledgeBase {
  id: string
  name: string
  description: string
  llm_model_id: string
  embedding_model_id: string
  parsing_config: {
    engine: string
    docling_url?: string
    enable_pdf: boolean
    pandoc: boolean
  }
  status: string
  document_count: number
  chunk_count: number
  created_at: string
  updated_at: string
}

export interface KnowledgeDocument {
  id: string
  knowledge_base_id: string
  name: string
  file_key?: string
  file_url?: string
  file_size: number
  status: string
  chunk_count: number
  uploaded_at: string
}

// 获取知识库列表
export const fetchKnowledgeBases = async (): Promise<KnowledgeBase[]> => {
  try {
    const response = await fetch(`${API_BASE}/api/knowledge/list`)

    if (!response.ok) {
      console.error('Server error:', response.status)
      return []
    }

    const text = await response.text()
    if (!text) {
      return []
    }

    try {
      const data = JSON.parse(text)
      if (data.success) {
        return data.data || []
      }
      console.error('API error:', data.message)
      return []
    } catch (parseError) {
      console.error('Failed to parse JSON:', text)
      return []
    }
  } catch (error) {
    console.error('Failed to fetch knowledge bases:', error)
    return []
  }
}

// 创建知识库
export const createKnowledgeBase = async (params: {
  name: string
  description?: string
  llm_model_id: string
  embedding_model_id: string
  parsing_config: {
    engine: string
    docling_url?: string
    enable_pdf?: boolean
    pandoc?: boolean
  }
  vlm_config?: {
    enabled: boolean
    model_id: string
  }
  storage_config?: {
    type: string
    endpoint?: string
    access_key_id?: string
    secret_access_key?: string
    bucket?: string
  }
}): Promise<{ success: boolean; id?: string; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE}/api/knowledge/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    })

    // Check if response is OK
    if (!response.ok) {
      const errorText = await response.text()
      return { success: false, message: `Server error: ${response.status} - ${errorText}` }
    }

    const text = await response.text()
    if (!text) {
      return { success: false, message: 'Empty response from server' }
    }

    try {
      const data = JSON.parse(text)
      return data
    } catch (parseError) {
      console.error('Failed to parse JSON:', text)
      return { success: false, message: `Invalid JSON response: ${text}` }
    }
  } catch (error) {
    console.error('Failed to create knowledge base:', error)
    return { success: false, message: `Network error: ${error}` }
  }
}

// 删除知识库
export const deleteKnowledgeBase = async (id: string): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE}/api/knowledge/${id}`, {
      method: 'DELETE',
    })
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Failed to delete knowledge base:', error)
    return { success: false, message: 'Failed to delete knowledge base' }
  }
}

// 获取知识库下的文档列表
export const fetchKnowledgeDocuments = async (kbId: string, status?: string): Promise<KnowledgeDocument[]> => {
  try {
    const query = status && status !== 'all' ? `?status=${status}` : ''
    const response = await fetch(`${API_BASE}/api/knowledge/${kbId}/documents${query}`)
    const data = await response.json()
    if (data.success) {
      return data.data
    }
    throw new Error(data.message || 'Failed to fetch documents')
  } catch (error) {
    console.error('Failed to fetch documents:', error)
    return []
  }
}

// 上传文档到知识库
export const uploadDocument = async (kbId: string, file: File): Promise<{ success: boolean; id?: string; url?: string; document?: KnowledgeDocument; message?: string }> => {
  try {
    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch(`${API_BASE}/api/knowledge/${kbId}/documents`, {
      method: 'POST',
      body: formData,
    })
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Failed to upload document:', error)
    return { success: false, message: 'Failed to upload document' }
  }
}

// 删除知识库文档
export const deleteDocument = async (kbId: string, docId: string): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE}/api/knowledge/${kbId}/documents/${docId}`, {
      method: 'DELETE',
    })
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Failed to delete document:', error)
    return { success: false, message: 'Failed to delete document' }
  }
}

// 重新解析文档
export const reparseDocument = async (kbId: string, docId: string): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE}/api/knowledge/${kbId}/documents/${docId}/reparse`, {
      method: 'POST',
    })
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Failed to reparse document:', error)
    return { success: false, message: 'Failed to reparse document' }
  }
}

// 获取文档预览内容
export const getDocumentPreview = async (kbId: string, docId: string, page: number = 1): Promise<{ success: boolean; data?: { total_pages: number; current_page: number; content: string; content_type?: string }; message?: string }> => {
  try {
    const response = await fetch(`${API_BASE}/api/knowledge/${kbId}/documents/${docId}/preview?page=${page}`)
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Failed to get document preview:', error)
    return { success: false, message: 'Failed to get document preview' }
  }
}

// 获取文件代理URL (用于预览PDF)
export const getFileProxyUrl = (kbId: string, key: string): string => {
  const encodedKey = encodeURIComponent(key)
  return `${API_BASE}/api/file_proxy?kb_id=${kbId}&key=${encodedKey}`
}
