import { makeAutoObservable, runInAction } from "mobx"
import { getBots } from "@/server/api"

interface Bot {
  id: string
  name: string
  description: string
  icon_url: string
  created_time?: string
  updated_time?: string
}

class BotStore {
  bots: Bot[] = []
  loading = false
  error: string | null = null

  constructor() {
    makeAutoObservable(this)
  }

  /**
   * 加载工作空间内的所有智能体
   */
  loadBots = async () => {
    try {
      runInAction(() => {
        this.loading = true
        this.error = null
      })

      const response = await getBots()
      
      runInAction(() => {
        if (response.code === 10000) {
          this.bots = response.data || []
        } else {
          this.error = response.msg || "获取智能体列表失败"
        }
        this.loading = false
      })
    } catch (error) {
      runInAction(() => {
        this.error = "网络请求失败"
        this.loading = false
      })
      console.error("加载智能体失败:", error)
    }
  }

  /**
   * 根据ID查找智能体
   */
  getBotById = (botId: string): Bot | undefined => {
    return this.bots.find(bot => bot.id === botId)
  }

  /**
   * 重置状态
   */
  reset = () => {
    this.bots = []
    this.loading = false
    this.error = null
  }
}

export default new BotStore()
