import { ref, computed } from 'vue'

const API_BASE = 'http://localhost:8082'

// Tool 接口
export interface Tool {
  id: string
  name: string
  description: string
  category: string
  provider: string
  security_level: string
  require_approval: boolean
  parameters: string
  status: string
  created_at?: string
  updated_at?: string
}

export function useTools() {
  const tools = ref<Tool[]>([])
  const toolsLoading = ref(false)

  // 获取工具列表
  const fetchTools = async (category?: string, status?: string) => {
    toolsLoading.value = true
    try {
      let url = `${API_BASE}/tool/list?`
      if (category) url += `category=${category}&`
      if (status) url += `status=${status}&`

      const response = await fetch(url)
      const data = await response.json()

      if (data.list) {
        tools.value = data.list
      }
      return data.list || []
    } catch (error) {
      console.error('Failed to fetch tools:', error)
      return []
    } finally {
      toolsLoading.value = false
    }
  }

  // 同步工具到数据库
  const syncTools = async () => {
    try {
      const response = await fetch(`${API_BASE}/tool/sync`)
      const data = await response.json()
      await fetchTools() // 重新获取列表
      return data
    } catch (error) {
      console.error('Failed to sync tools:', error)
      throw error
    }
  }

  // 获取工具详情
  const fetchToolById = async (id: string) => {
    try {
      const response = await fetch(`${API_BASE}/tool/${id}`)
      const data = await response.json()
      return data.tool
    } catch (error) {
      console.error('Failed to fetch tool:', error)
      throw error
    }
  }

  // 创建工具
  const createTool = async (tool: Partial<Tool>) => {
    try {
      const response = await fetch(`${API_BASE}/tool/add`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(tool),
      })
      const data = await response.json()
      await fetchTools() // 重新获取列表
      return data
    } catch (error) {
      console.error('Failed to create tool:', error)
      throw error
    }
  }

  // 更新工具
  const updateTool = async (id: string, tool: Partial<Tool>) => {
    try {
      const response = await fetch(`${API_BASE}/tool/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(tool),
      })
      const data = await response.json()
      await fetchTools() // 重新获取列表
      return data
    } catch (error) {
      console.error('Failed to update tool:', error)
      throw error
    }
  }

  // 删除工具
  const deleteTool = async (id: string) => {
    try {
      const response = await fetch(`${API_BASE}/tool/${id}`, {
        method: 'DELETE',
      })
      const data = await response.json()
      await fetchTools() // 重新获取列表
      return data
    } catch (error) {
      console.error('Failed to delete tool:', error)
      throw error
    }
  }

  // 按分类获取工具
  const getToolsByCategory = (category: string) => {
    return tools.value.filter(tool => tool.category === category)
  }

  // 获取所有分类
  const categories = computed(() => {
    const cats = new Set(tools.value.map(tool => tool.category))
    return Array.from(cats)
  })

  return {
    tools,
    toolsLoading,
    categories,
    fetchTools,
    syncTools,
    fetchToolById,
    createTool,
    updateTool,
    deleteTool,
    getToolsByCategory,
  }
}
