/**
 * 数据源管理 Composable
 * 负责预定义数据源的加载和选择
 */

import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useTemplateStore } from '@/stores'
import { configApi } from '@/api'
import * as directoryApi from '@/api/directory'

export function useDataSource() {
  const templateStore = useTemplateStore()
  
  // 状态
  const isLoadingDataSources = ref(false)
  
  // 计算属性
  const dataSources = computed(() => templateStore.dataSources)
  const hasDataSources = computed(() => templateStore.hasDataSources)
  const activeDataSource = computed(() => templateStore.activeDataSource)
  const activeDataSourceName = computed(() => templateStore.activeDataSourceName)
  
  /**
   * 加载数据源列表
   */
  async function loadDataSources() {
    isLoadingDataSources.value = true
    try {
      const response = await configApi.listDataSources()
      templateStore.setDataSources(response.sources)
      ElMessage.success(`加载了 ${response.sources.length} 个数据源`)
      return response.sources
    } catch (error: any) {
      ElMessage.error(`加载数据源失败: ${error.message}`)
      throw error
    } finally {
      isLoadingDataSources.value = false
    }
  }
  
  /**
   * 选择数据源
   */
  async function selectDataSource(sourceFilename: string) {
    // 如果数据源列表为空，先加载
    if (templateStore.dataSources.length === 0) {
      try {
        await loadDataSources()
      } catch (error: any) {
        ElMessage.error(`加载数据源失败: ${error.message}`)
        return {
          success: false,
          error: `加载数据源失败: ${error.message}`
        }
      }
    }
    
    // 先检查数据源是否存在
    const source = templateStore.dataSources.find(ds => ds.filename === sourceFilename)
    
    if (!source) {
      ElMessage.error(`数据源不存在: ${sourceFilename}`)
      console.error('数据源查找失败:', {
        sourceFilename,
        availableFilenames: templateStore.dataSources.map(ds => ds.filename),
        dataSourcesCount: templateStore.dataSources.length,
        allDataSources: templateStore.dataSources.map(ds => ({
          filename: ds.filename,
          name: ds.name,
          hasFilename: 'filename' in ds
        }))
      })
      return {
        success: false,
        error: `数据源不存在: ${sourceFilename}`
      }
    }
    
    // 设置选中的数据源
    templateStore.selectDataSource(sourceFilename)
    
    // 再次获取（应该能找到了）
    const activeSource = templateStore.activeDataSource
    const displayName = activeSource?.name || source.name || sourceFilename
    ElMessage.success(`已选择数据源: ${displayName}`)
    
    // 自动导航到数据源的 base_dir
    if (activeSource) {
      try {
        const result = await directoryApi.browseDirectory(activeSource.base_dir)
        templateStore.setDirectory(result.current_path, result.items, result.parent_path)
        return {
          success: true,
          path: result.current_path
        }
      } catch (error: any) {
        ElMessage.warning(`无法浏览数据源目录: ${error.message}`)
        return {
          success: false,
          error: error.message
        }
      }
    }
    
    return { success: true }
  }
  
  /**
   * 清除数据源选择
   */
  function clearDataSource() {
    templateStore.selectDataSource(null)
  }
  
  /**
   * 获取数据源配置
   */
  function getDataSourceConfig(sourceFilename: string) {
    return templateStore.dataSources.find(s => s.filename === sourceFilename)
  }
  
  return {
    // 状态
    isLoadingDataSources,
    
    // 计算属性
    dataSources,
    hasDataSources,
    activeDataSource,
    activeDataSourceName,
    
    // 方法
    loadDataSources,
    selectDataSource,
    clearDataSource,
    getDataSourceConfig
  }
}
