/**
 * Coze AI 相关 API
 */
import request from '../request'

// Coze会话相关类型
export interface CozeSession {
  sessionId: string
  conversationId: string
  botId: string
  createdAt: string
}

// Coze消息相关类型
export interface CozeMessage {
  messageId?: string
  role: 'user' | 'assistant' | 'system'
  content: string
  contentType?: 'text' | 'card'
  timestamp?: string
}

// 流式事件类型
export interface StreamEvent {
  event: 'message_delta' | 'message_completed' | 'error' | 'done'
  data: {
    content?: string
    contentType?: string
    messageId?: string
    error?: string
    sessionId?: string
    usage?: {
      tokens?: number
    }
  }
}

// 结束会话请求
export interface EndSessionRequest {
  reason?: string
  feedback?: {
    rating?: number
    comment?: string
  }
}

/**
 * 创建课程对话会话
 */
export const createCourseChatSession = (courseId: string) => {
  return request.get<{ data: CozeSession }>('/api/v1/course-chat/sessions', {
    params: { course_id: courseId }
  })
}

/**
 * 创建陪练会话
 */
export const createTrainingSession = (trainingTopic?: string) => {
  return request.get<{ data: CozeSession }>('/api/v1/training/sessions', {
    params: { training_topic: trainingTopic }
  })
}

/**
 * 结束陪练会话
 */
export const endTrainingSession = (sessionId: string, data: EndSessionRequest = {}) => {
  return request.post<{ data: any }>(`/api/v1/training/sessions/${sessionId}/end`, data)
}

/**
 * 发送消息（支持流式响应）
 * @param sessionId 会话ID
 * @param content 消息内容
 * @param stream 是否使用流式响应
 */
export const sendMessage = async (
  sessionId: string, 
  content: string, 
  stream: boolean = true,
  onMessage?: (event: StreamEvent) => void
) => {
  if (stream && onMessage) {
    // 流式响应处理
    // 开发环境使用空字符串（走代理），生产环境使用当前域名（支持多域名部署）
    const baseURL = (import.meta.env.DEV || import.meta.env.VITE_APP_ENV === 'development') 
      ? '' 
      : window.location.origin
    
    const response = await fetch(`${baseURL}/api/v1/chat/messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}` // 获取认证token
      },
      body: JSON.stringify({
        session_id: sessionId,
        content,
        stream: true
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body?.getReader()
    const decoder = new TextDecoder()

    if (!reader) {
      throw new Error('No response body')
    }

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.slice(6))
            onMessage(data)
          } catch (e) {
            console.error('Failed to parse SSE data:', e)
          }
        }
      }
    }
  } else {
    // 非流式响应
    return request.post<{ data: CozeMessage }>('/api/v1/chat/messages', {
      session_id: sessionId,
      content,
      stream: false
    })
  }
}

/**
 * 获取会话消息历史
 */
export const getSessionMessages = (sessionId: string, limit: number = 50, offset: number = 0) => {
  return request.get<{ data: { messages: CozeMessage[] } }>(`/api/v1/sessions/${sessionId}/messages`, {
    params: { limit, offset }
  })
}
