/*
 * @Author: wrh
 * @Date: 2025-07-17 18:06:24
 * @LastEditors: wrh
 * @LastEditTime: 2026-05-14 19:52:03
 */
import request from '@/utils/request'
import { getToken } from '@/utils/auth'

// 查询智能体列表
export function listAgent(query) {
  return request({
    url: '/llm/agent/list',
    method: 'get',
    params: query
  })
}

// 查询智能体详细
export function getAgent(agentId) {
  return request({
    url: '/llm/agent/' + agentId,
    method: 'get'
  })
}

// 新增智能体
export function addAgent(data) {
  return request({
    url: '/llm/agent',
    method: 'post',
    data: data
  })
}

// 修改智能体
export function updateAgent(data) {
  return request({
    url: '/llm/agent',
    method: 'put',
    data: data
  })
}

// 删除智能体
export function delAgent(agentId) {
  return request({
    url: '/llm/agent/' + agentId,
    method: 'delete'
  })
}

// 上传单文件
export function uploadFile(file, agentName) {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('agentName', agentName)
  return request({
    url: '/llm/agent/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 上传修改文件
export function uploadModifyFile(topicId, file, agentName, selectedNode) {
  const formData = new FormData()
  formData.append('topicId', topicId)
  formData.append('file', file)
  formData.append('agentName', agentName)
  if (selectedNode) {
    formData.append('selectedNode', selectedNode)
  }
  return request({
    url: '/llm/agent/modifyFile',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 上传多文件
export function uploadFileList(fileList, agentName) {
  const formData = new FormData()
  for (let f of fileList) {
    formData.append('fileList', f)
  }
  formData.append('agentName', agentName)
  return request({
    url: '/llm/agent/uploadList',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 获取上传进度
export function getProcessValue() {
  return request({
    url: '/llm/agent/getProcess',
    method: 'get'
  })
}

//获取开场白, agentName：智能体名称
export function opening(agentName) {
  return request({
    url: '/llm/agent/opening',
    method: 'get',
    params: { agentName }
  })
}

// 保存目录到Word文件
export function writeTitles(data) {
  return request({
    url: '/llm/agent/writeTitles',
    method: 'post',
    data: data
  })
}

/**
 * 解析SSE事件 - 优化版
 * 正确处理多行data和事件类型
 */
function parseSseEvents(buffer) {
  const events = []
  const lines = buffer.split(/\r?\n/)
  let currentEvent = null
  let currentData = []
  let remaining = []
  let i = 0
  
  for (; i < lines.length; i++) {
    const line = lines[i]
    
    // 空行表示事件结束
    if (line === '') {
      if (currentData.length > 0) {
        const data = currentData.join('\n')
        events.push({
          event: currentEvent || 'message',
          data: data
        })
        currentEvent = null
        currentData = []
      }
      continue
    }
    
    // 解析事件类型
    if (line.startsWith('event:')) {
      currentEvent = line.slice(6).trim()
      continue
    }
    
    // 解析数据行
    if (line.startsWith('data:')) {
      const dataValue = line.slice(5).trimStart()
      currentData.push(dataValue)
      continue
    }
  }
  
  // 保存剩余未完成的数据
  if (i < lines.length) {
    remaining = lines.slice(i).join('\n')
  } else if (currentData.length > 0) {
    // 如果最后没有空行，但数据已完整，也要保留
    remaining = lines.slice(i - currentData.length - (currentEvent ? 1 : 0)).join('\n')
  } else {
    remaining = ''
  }
  
  return { events, rest: remaining }
}

/**
 * 规范化SSE数据
 */
function normalizeSseData(data) {
  if (data == null) return ''
  let s = String(data)
  // 移除可能的 "data:" 前缀
  while (s.startsWith('data:')) {
    s = s.slice(5)
    if (s.startsWith(' ')) s = s.slice(1)
  }
  return s
}

/**
 * 流式生成标书章节（SSE）- 支持逐字输出
 * @param {FormData} formData - 包含 topicId, agentName, file, selectedNode
 * @param {Function} onMessage - 收到消息时的回调，接收解析后的JSON对象
 * @param {Function} onError - 错误回调
 * @param {Function} onComplete - 完成回调
 * @returns {AbortController} 用于取消请求的控制器
 */
export function streamGenerateChapters(formData, onMessage, onError, onComplete) {
  const controller = new AbortController()

  fetch(process.env.VUE_APP_BASE_API + '/llm/agent/streamGenerate', {
    method: 'POST',
    body: formData,
    headers: {
      'Accept': 'text/event-stream',
      'Authorization': 'Bearer ' + getToken(),
      'Cache-Control': 'no-cache'
    },
    signal: controller.signal
  })
    .then(async (response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      if (!response.body) {
        throw new Error('ReadableStream not supported')
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder('utf-8')
      let buffer = ''

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

        buffer += decoder.decode(value, { stream: true })
        
        // 解析SSE事件
        const { events, rest } = parseSseEvents(buffer)
        buffer = rest

        for (const event of events) {
          const normalizedData = normalizeSseData(event.data)
          
          // 检查是否结束
          if (normalizedData === '[DONE]') {
            onComplete && onComplete()
            controller.abort()
            return
          }
          
          try {
            const jsonData = JSON.parse(normalizedData)
            // 根据事件名称分发
            onMessage && onMessage(jsonData, event.event)
          } catch (e) {
            console.warn('解析JSON失败，作为普通文本处理:', normalizedData)
            onMessage && onMessage({ content: normalizedData }, event.event)
          }
        }
      }
      
      onComplete && onComplete()
    })
    .catch((error) => {
      if (error.name === 'AbortError') {
        console.log('请求已取消')
        return
      }
      console.error('流式请求错误:', error)
      onError && onError(error)
    })

  return controller
}