import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  getProviders,
  getConfig,
  saveConfig,
  testEmbedding,
  getSupportedFormats,
  type EmbeddingProviderInfo,
  type EmbeddingConfig,
  type EmbeddingConfigUpdate,
  type EmbeddingTestResult,
  type DocumentFormat
} from '@/api/embedding'

export const useEmbeddingStore = defineStore('embedding', () => {
  const providers = ref<EmbeddingProviderInfo[]>([])
  const currentConfig = ref<EmbeddingConfig>({
    provider: '',
    config: {}
  })
  const formats = ref<DocumentFormat[]>([])
  const loading = ref(false)
  const providersLoading = ref(false)
  const formatsLoading = ref(false)
  const testResult = ref<EmbeddingTestResult | null>(null)
  const testLoading = ref(false)

  const currentProvider = computed(() => {
    return providers.value.find(p => p.name === currentConfig.value.provider)
  })

  const configSchema = computed(() => {
    return currentProvider.value?.config_schema || { properties: {} }
  })

  const loadProviders = async () => {
    providersLoading.value = true
    try {
      const res: any = await getProviders()
      providers.value = res?.providers || res?.data?.providers || []
    } catch (error) {
      console.error('Failed to load providers:', error)
      throw error
    } finally {
      providersLoading.value = false
    }
  }

  const loadConfig = async () => {
    loading.value = true
    try {
      const res: any = await getConfig()
      const config = res?.data || res
      if (config) {
        currentConfig.value = {
          provider: config.provider || '',
          config: config.config || {},
          updated_at: config.updated_at
        }
      }
    } catch (error) {
      console.error('Failed to load config:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const saveCurrentConfig = async () => {
    loading.value = true
    try {
      const updateData: EmbeddingConfigUpdate = {
        provider: currentConfig.value.provider,
        config: currentConfig.value.config
      }
      const response = await saveConfig(updateData)
      return response
    } catch (error) {
      console.error('Failed to save config:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const runTest = async (testText?: string) => {
    testLoading.value = true
    testResult.value = null
    try {
      const result = await testEmbedding({
        test_text: testText,
        config: {
          provider: currentConfig.value.provider,
          config: currentConfig.value.config
        }
      })
      testResult.value = result
    } catch (error: any) {
      testResult.value = {
        success: false,
        dimension: 0,
        error: error?.message || '连接测试失败'
      }
    } finally {
      testLoading.value = false
    }
  }

  const loadFormats = async () => {
    formatsLoading.value = true
    try {
      const res: any = await getSupportedFormats()
      formats.value = res?.formats || res?.data?.formats || []
    } catch (error) {
      console.error('Failed to load formats:', error)
      throw error
    } finally {
      formatsLoading.value = false
    }
  }

  const setProvider = (providerName: string) => {
    currentConfig.value.provider = providerName
    const provider = providers.value.find(p => p.name === providerName)
    if (provider?.config_schema?.properties) {
      const newConfig: Record<string, any> = {}
      Object.entries(provider.config_schema.properties).forEach(([key, field]: [string, any]) => {
        newConfig[key] = field.default !== undefined ? field.default : ''
      })
      currentConfig.value.config = newConfig
    } else {
      currentConfig.value.config = {}
    }
  }

  const updateConfigValue = (key: string, value: any) => {
    currentConfig.value.config[key] = value
  }

  const clearTestResult = () => {
    testResult.value = null
  }

  return {
    providers,
    currentConfig,
    formats,
    loading,
    providersLoading,
    formatsLoading,
    testResult,
    testLoading,
    currentProvider,
    configSchema,
    loadProviders,
    loadConfig,
    saveCurrentConfig,
    runTest,
    loadFormats,
    setProvider,
    updateConfigValue,
    clearTestResult
  }
})
