import { get, post } from "@/utils/request"
import { getApiUrl } from "@/utils/tools"

/**
 * 获取工作空间内的所有智能体
 */
export const getBots = () => {
  return get(`/api/bots`)
}

/**
 * 获取智能体详细信息
 */
export const getBotInfo = (botId: string) => {
  return get(`/api/bots/${botId}`)
}

/**
 * 创建新对话
 */
export const createConversation = (data: { bot_id: string }) => {
  return post(`/api/conversations`, data)
}

/**
 * 发送消息 - 流式聊天
 */
export const startChatStream = (
  data: {
    content: string
    bot_id: string
    conversation_id?: string
    user_id?: string
    file_ids?: string[]
    history_messages?: any[]
  },
  signal: AbortSignal
) => {
  const url = `${getApiUrl()}/api/chat/stream`
  // 直接使用原生 fetch 获取 ReadableStream，避免 axios 拦截器影响 SSE
  return fetch(url, {
    method: "POST",
    signal,
    headers: {
      "Content-Type": "application/json",
      Accept: "text/event-stream",
    },
    body: JSON.stringify(data),
  }).then((res) => {
    if (!res.ok) {
      throw new Error(`HTTP ${res.status}: ${res.statusText}`)
    }
    // 确保返回 ReadableStream
    if (!res.body) {
      throw new Error("Response body is null")
    }
    return res.body
  })
}

/**
 * 中断对话
 */
export const interruptChat = (data: {
  chat_id: string
  conversation_id: string
}) => {
  return post(`/api/chat/interrupt`, data)
}

/**
 * 删除对话
 */
export const deleteConversation = (conversationId: string) => {
  return fetch(`/api/conversations/${conversationId}`, { method: "DELETE" })
    .then(res => res.json())
}
