import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as kbApi from '@/api/kb'
import type { IKbSource, ISearchResult } from '@/api/kb'

export const useKnowledgeStore = defineStore('knowledge', () => {
  // --- State ---
  const sources = ref<IKbSource[]>([])
  const searchResults = ref<ISearchResult[]>([])
  const isLoading = ref(false)
  const isUploading = ref(false)
  const isSearching = ref(false)
  const error = ref<string | null>(null)

  // --- Getters ---
  const sourceCount = computed(() => sources.value.length)
  const localSources = computed(() => sources.value.filter((s) => s.type === 'local'))
  const externalSources = computed(() => sources.value.filter((s) => s.type !== 'local'))

  // --- Actions ---
  async function fetchSources(): Promise<void> {
    isLoading.value = true
    error.value = null
    try {
      const data = await kbApi.listSources()
      sources.value = data.sources
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取信息源列表失败'
      console.error('Failed to fetch sources:', err)
    } finally {
      isLoading.value = false
    }
  }

  async function addSource(
    name: string,
    type: 'local' | 'feishu' | 'confluence' | 'http',
    config: Record<string, unknown> = {}
  ): Promise<void> {
    isLoading.value = true
    error.value = null
    try {
      await kbApi.addSource({ name, type, config })
      await fetchSources()
    } catch (err) {
      error.value = err instanceof Error ? err.message : '添加信息源失败'
      console.error('Failed to add source:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  async function removeSource(sourceId: string): Promise<void> {
    isLoading.value = true
    error.value = null
    try {
      await kbApi.removeSource(sourceId)
      await fetchSources()
    } catch (err) {
      error.value = err instanceof Error ? err.message : '删除信息源失败'
      console.error('Failed to remove source:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  async function uploadDocument(file: File, sourceId?: string): Promise<void> {
    isUploading.value = true
    error.value = null
    try {
      await kbApi.uploadDocument(file, sourceId)
      await fetchSources()
    } catch (err) {
      error.value = err instanceof Error ? err.message : '上传文档失败'
      console.error('Failed to upload document:', err)
      throw err
    } finally {
      isUploading.value = false
    }
  }

  async function search(query: string, sourceIds?: string[], topK: number = 5): Promise<void> {
    isSearching.value = true
    error.value = null
    searchResults.value = []
    try {
      const data = await kbApi.searchKnowledge(query, sourceIds, topK)
      searchResults.value = data.results
    } catch (err) {
      error.value = err instanceof Error ? err.message : '检索失败'
      console.error('Failed to search:', err)
    } finally {
      isSearching.value = false
    }
  }

  async function checkHealth(sourceId: string): Promise<string> {
    try {
      const data = await kbApi.checkSourceHealth(sourceId)
      return data.status
    } catch (err) {
      console.error('Failed to check health:', err)
      return 'error'
    }
  }

  return {
    // State
    sources,
    searchResults,
    isLoading,
    isUploading,
    isSearching,
    error,
    // Getters
    sourceCount,
    localSources,
    externalSources,
    // Actions
    fetchSources,
    addSource,
    removeSource,
    uploadDocument,
    search,
    checkHealth,
  }
})
