// deepseek.js
export function fetchHuaweiResponse(message, callback, fileData) {
    // 修改为调用您自己的后端接口  /deepseek-api = http://10.19.13.166/deepseek
    const apiUrl = "/deepseek-api/v1/chat/completions";
    const apiKey = "sk-dbdcf76f25d94373bc4dfbab6bf0a286";

    // 直接调用DeepSeek API
    callDeepSeekAPI(message, apiUrl, apiKey, callback);
}

// 调用DeepSeek API的函数
function callDeepSeekAPI(messages, apiUrl, apiKey, callback) {
    const requestBody = {
        model: "deepseek",
        messages: messages,
        stream: true
    };

    fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify(requestBody)
    })
      .then(response => {
          // 检查响应是否成功
          if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
          }

          // 如果没有body（非流式响应），直接处理JSON
          if (!response.body) {
              return response.json().then(data => {
                  callback(data.reply || data.response || JSON.stringify(data), false, true);
                  return;
              });
          }

          // 流式响应处理
          const reader = response.body.getReader();
          let buffer = '';
          let fullResponse = '';
          let isThinking = false;

          function readStream() {
              return reader.read().then(({done, value}) => {
                  if (done) {
                      callback(fullResponse, isThinking, true);
                      return;
                  }

                  buffer += new TextDecoder().decode(value);
                  const lines = buffer.split('\n');
                  buffer = lines.pop();

                  lines.forEach(line => {
                      if (line.startsWith('data: ')) {
                          const content = line.slice(6);
                          if (content === "[DONE]") {
                              callback(fullResponse, isThinking, true);
                              return;
                          }
                          try {
                              const data = JSON.parse(content);
                              if (data.choices && data.choices[0].delta) {
                                  let content = '';
                                  if (data.choices[0].delta.reasoning_content) {
                                      content += data.choices[0].delta.reasoning_content;
                                  }
                                  if (data.choices[0].delta.content) {
                                      let ct = data.choices[0].delta.content;
                                      if (ct.includes("<think>")) {
                                          isThinking = true;
                                      } else if (ct.includes("</think>")) {
                                          isThinking = false;
                                          fullResponse = "【deepseek回复】\n";
                                      }
                                      content += ct;
                                  }
                                  if (content) {
                                      content = content.replace("<think>", '【思考过程】').replace("</think>", '');
                                      fullResponse += content;
                                      callback(fullResponse, isThinking, false);
                                  }
                              }
                          } catch (error) {
                              console.error('JSON解析错误:', error, "需要解析的内容为：", content);
                          }
                      }
                  });
                  return readStream();
              });
          }

          return readStream();
      })
      .catch(error => {
          console.error('API调用失败:', error);
          callback("抱歉，请求失败，请稍后再试。", false, true);
      });
}
