import { api } from './client'

export interface KnowledgeBase {
  id: string
  name: string
  root_dir: string
  description: string
  created_at: string
  updated_at: string
  index_status: {
    bm25: { exists: boolean; total_chunks?: number; total_files?: number }
    vector: { exists: boolean }
    wiki: { exists: boolean; total_pages?: number; subdirs?: Record<string, number> }
    pageindex: { exists: boolean; total_pages?: number; total_docs?: number }
  }
}

export interface KBFile {
  path: string
  relative_path: string
  name: string
  type: string
  size: number
  modified: number
  added: boolean
}

export interface KBDirNode {
  name: string
  relative_path: string
  ignored: boolean          // true if this specific path is in the ignore list
  has_children: boolean     // whether subdirs exist (for lazy expand arrow)
  children: KBDirNode[]    // loaded lazily on expand
}

export interface KBJob {
  id: string
  kb_id: string
  job_type: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  progress: number
  total: number
  current_file: string
  error: string
  log: string
  started_at: string
  completed_at: string
  created_at: string
}

export interface KBChunk {
  id: string
  source: string
  chunk_id: number
  text: string
  length: number
}

export interface KBChunkPage {
  total: number
  total_all: number
  page: number
  limit: number
  pages: number
  chunks: KBChunk[]
}

export interface WikiPage {
  name: string
  path: string
  size: number
  modified: number
}

export interface WikiTree {
  sources: WikiPage[]
  entities: WikiPage[]
  topics: WikiPage[]
  analyses: WikiPage[]
  index_content: string
}

export interface WikiSchedule {
  enabled: boolean
  interval: 'daily' | 'weekly'
  next_run: string
  last_run: string
}

export const knowledgeApi = {
  list: () => api.get<{ items: KnowledgeBase[] }>('/knowledge'),
  get: (id: string) => api.get<KnowledgeBase>(`/knowledge/${id}`),
  create: (data: { name: string; root_dir: string; description?: string }) =>
    api.post<KnowledgeBase>('/knowledge', data),
  delete: (id: string) => api.delete(`/knowledge/${id}`),

  listFiles: (kbId: string, params?: { path?: string; q?: string }) => {
    const qs = new URLSearchParams()
    if (params?.path) qs.set('path', params.path)
    if (params?.q)    qs.set('q', params.q)
    const query = qs.toString()
    return api.get<{ kb_id: string; root_dir: string; files: KBFile[]; dirs: KBDirNode[]; ignored_dirs: string[]; current_path: string }>(
      `/knowledge/${kbId}/files${query ? '?' + query : ''}`
    )
  },

  listDirs: (kbId: string, path?: string) => {
    const qs = path ? `?path=${encodeURIComponent(path)}` : ''
    return api.get<{ dirs: KBDirNode[]; path: string }>(`/knowledge/${kbId}/dirs${qs}`)
  },

  getIgnoreDirs: (kbId: string) =>
    api.get<{ ignored_dirs: string[] }>(`/knowledge/${kbId}/ignore-dirs`),
  updateIgnoreDirs: (kbId: string, ignored_dirs: string[]) =>
    api.put<{ ignored_dirs: string[] }>(`/knowledge/${kbId}/ignore-dirs`, { ignored_dirs }),
  addFiles: (kbId: string, file_paths: string[]) =>
    api.post<{ added: number }>(`/knowledge/${kbId}/files`, { file_paths }),
  removeFile: (kbId: string, fileId: string) =>
    api.delete(`/knowledge/${kbId}/files/${fileId}`),

  buildIndex: (kbId: string, index_type = 'bm25', mode = 'full', chunk_strategy: 'token' | 'contextual' | 'page' = 'token') =>
    api.post<{ job_id: string; chunk_strategy: string }>(`/knowledge/${kbId}/index`, { index_type, mode, chunk_strategy }),
  buildWiki: (kbId: string, mode = 'incremental', concurrency = 2) =>
    api.post<{ job_id: string }>(`/knowledge/${kbId}/wiki`, { mode, concurrency }),
  pauseWiki: (kbId: string) =>
    api.put<{ action: string }>(`/knowledge/${kbId}/wiki/pause`),

  wikiTree: (kbId: string) =>
    api.get<WikiTree>(`/knowledge/${kbId}/wiki/tree`),
  wikiPage: (kbId: string, path: string) =>
    api.get<{ path: string; content: string }>(`/knowledge/${kbId}/wiki/${path}`),
  deleteAnalysis: (kbId: string, name: string) =>
    api.delete(`/knowledge/${kbId}/wiki/analyses/${name}`),

  wikiSchedule: (kbId: string) =>
    api.get<WikiSchedule>(`/knowledge/${kbId}/wiki/schedule`),
  updateWikiSchedule: (kbId: string, data: Partial<WikiSchedule>) =>
    api.put<WikiSchedule>(`/knowledge/${kbId}/wiki/schedule`, data),

  search: (kbId: string, query: string, mode = 'lambda', top_k = 5) =>
    api.post<{ query: string; mode: string; results: any[] }>(`/knowledge/${kbId}/search`, {
      query, mode, top_k,
    }),

  listJobs: (kbId: string) =>
    api.get<{ jobs: KBJob[] }>(`/knowledge/${kbId}/jobs`),
  getJob: (kbId: string, jobId: string) =>
    api.get<KBJob>(`/knowledge/${kbId}/jobs/${jobId}`),

  listChunks: (kbId: string, params?: { q?: string; source?: string; page?: number; limit?: number }) => {
    const qs = new URLSearchParams()
    if (params?.q)      qs.set('q', params.q)
    if (params?.source) qs.set('source', params.source)
    if (params?.page)   qs.set('page', String(params.page))
    if (params?.limit)  qs.set('limit', String(params.limit))
    const query = qs.toString()
    return api.get<KBChunkPage>(`/knowledge/${kbId}/chunks${query ? '?' + query : ''}`)
  },
}
