import request from '@/utils/request'

// AI聊天消息接口
export interface ChatMessage {
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp?: number
}

// AI聊天请求参数
export interface ChatRequest {
  messages: ChatMessage[]
  model: string
  temperature?: number
  top_p?: number
  max_tokens?: number
  stream?: boolean
  api_key?: string
  api_endpoint?: string
}

// AI聊天响应
export interface ChatResponse {
  id: string
  object: string
  created: number
  model: string
  choices: Array<{
    index: number
    message: ChatMessage
    finish_reason: string
  }>
  usage?: {
    prompt_tokens: number
    completion_tokens: number
    total_tokens: number
  }
}

// 流式响应数据
export interface StreamChunk {
  id: string
  object: string
  created: number
  model: string
  choices: Array<{
    index: number
    delta: {
      content?: string
      role?: string
    }
    finish_reason: string | null
  }>
}

// 发送聊天消息（非流式）
export function sendChatMessage(data: ChatRequest) {
  return request<ChatResponse>({
    url: '/ai/chat',
    method: 'post',
    data
  })
}

// 发送聊天消息（流式）
export function sendChatMessageStream(data: ChatRequest): ReadableStream<StreamChunk> {
  return new ReadableStream({
    start(controller) {
      const eventSource = new EventSource(`/ai/chat/stream?${new URLSearchParams({
        messages: JSON.stringify(data.messages),
        model: data.model,
        temperature: data.temperature?.toString() || '0.7',
        top_p: data.top_p?.toString() || '1',
        max_tokens: data.max_tokens?.toString() || '2048',
        api_key: data.api_key || '',
        api_endpoint: data.api_endpoint || ''
      })}`)

      eventSource.onmessage = (event) => {
        try {
          if (event.data === '[DONE]') {
            controller.close()
            eventSource.close()
            return
          }

          const chunk: StreamChunk = JSON.parse(event.data)
          controller.enqueue(chunk)
        } catch (error) {
          console.error('解析流式数据失败:', error)
        }
      }

      eventSource.onerror = (error) => {
        console.error('流式请求错误:', error)
        controller.error(error)
        eventSource.close()
      }
    }
  })
}

// 获取聊天历史
export function getChatHistory(params?: {
  page?: number
  size?: number
  chatId?: string
}) {
  return request<{
    total: number
    list: Array<{
      id: string
      title: string
      messages: ChatMessage[]
      createdAt: string
      updatedAt: string
    }>
  }>({
    url: '/ai/chat/history',
    method: 'get',
    params
  })
}

// 保存聊天记录
export function saveChat(data: {
  title: string
  messages: ChatMessage[]
}) {
  return request<{ id: string }>({
    url: '/ai/chat/save',
    method: 'post',
    data
  })
}

// 删除聊天记录
export function deleteChat(chatId: string) {
  return request({
    url: `/ai/chat/${chatId}`,
    method: 'delete'
  })
}

// 更新聊天标题
export function updateChatTitle(chatId: string, title: string) {
  return request({
    url: `/ai/chat/${chatId}/title`,
    method: 'put',
    data: { title }
  })
}

// AI问答设置接口
export interface AiChatSettings {
  welcomeIcon: string
  welcomeTitle: string
  welcomeMessage: string
  presetQuestions: string[]
  historyCount: number
}

// 获取AI问答设置
export function getAiChatSettings() {
  return request<AiChatSettings>({
    url: '/ai/chat/settings',
    method: 'get'
  })
}

// 保存AI问答设置
export function saveAiChatSettings(data: AiChatSettings) {
  return request({
    url: '/ai/chat/settings',
    method: 'post',
    data
  })
}
