/** Knowledge Base API client */

const API_BASE = '/api/v1/kb-management'

export interface IKbSource {
  id: string
  name: string
  type: 'local' | 'feishu' | 'confluence' | 'http'
  status: string
  document_count: number
  last_synced: string | null
}

export interface IAddSourceRequest {
  name: string
  type: 'local' | 'feishu' | 'confluence' | 'http'
  config: Record<string, unknown>
}

export interface IUploadedDocument {
  document_id: string
  filename: string
  chunks: number
  status: string
}

export interface ISearchResult {
  content: string
  source: string
  score: number
  metadata: Record<string, unknown>
}

export interface ISourceHealth {
  source_id: string
  status: string
  message: string
}

async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
  const url = `${API_BASE}${path}`
  const headers: HeadersInit = {
    ...options.headers,
  }
  // Don't set Content-Type for FormData (upload)
  if (!(options.body instanceof FormData)) {
    headers['Content-Type'] = 'application/json'
  }

  const response = await fetch(url, { ...options, headers })

  if (!response.ok) {
    const error = { status: response.status, message: response.statusText }
    try {
      const body = await response.json()
      error.message = body.detail ?? body.message ?? error.message
    } catch {
      // use status text
    }
    throw error
  }

  return response.json() as Promise<T>
}

/** List all knowledge sources */
export async function listSources(): Promise<{ sources: IKbSource[] }> {
  return request<{ sources: IKbSource[] }>('/sources')
}

/** Add a knowledge source */
export async function addSource(data: IAddSourceRequest): Promise<IKbSource> {
  return request<IKbSource>('/sources', {
    method: 'POST',
    body: JSON.stringify(data),
  })
}

/** Remove a knowledge source */
export async function removeSource(sourceId: string): Promise<{ status: string }> {
  return request<{ status: string }>(`/sources/${sourceId}`, {
    method: 'DELETE',
  })
}

/** Upload a document */
export async function uploadDocument(file: File, sourceId?: string): Promise<IUploadedDocument> {
  const formData = new FormData()
  formData.append('file', file)
  if (sourceId) {
    formData.append('source_id', sourceId)
  }
  return request<IUploadedDocument>('/documents/upload', {
    method: 'POST',
    body: formData,
  })
}

/** Search/retrieve from knowledge base */
export async function searchKnowledge(
  query: string,
  sources?: string[],
  topK: number = 5
): Promise<{ results: ISearchResult[]; message?: string }> {
  return request<{ results: ISearchResult[]; message?: string }>('/search', {
    method: 'POST',
    body: JSON.stringify({ query, sources, top_k: topK }),
  })
}

/** Check source health */
export async function checkSourceHealth(sourceId: string): Promise<ISourceHealth> {
  return request<ISourceHealth>(`/sources/${sourceId}/health`)
}
