package service

import (
	"WorldEpcho/src/config"
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

// ApiResponse 映射API响应体
type ApiResponse struct {
	Text      string `json:"text"`
	MessageID string `json:"message_id"`
}

// SendSemanticAnalysisRequest 发送语义分析请求
func SendSemanticAnalysisRequest(sentence string) (string, error) {
	// 构造请求体
	requestBody, err := json.Marshal(map[string]interface{}{
		"query": sentence, // 修改了这里，直接使用字符串作为查询条件
		"history": []map[string]string{
			{
				"role":    "system",
				"content": "语义理解大师，请分析接下来这句话在问谁，只回答名字",
			},
			{
				"role":    "user",
				"content": "潘金莲被贾宝玉打了,潘金莲请唐僧评理，白骨精你怎么看？(回答这句话在向谁提问，只写名字)",
			},
			{
				"role":    "assistant",
				"content": "白骨精",
			},
			{
				"role":    "user",
				"content": "马云在开讲啦节目上进行演讲，当主持人撒贝宁问马云是否对钱感兴趣，马云说对钱不感兴趣；马斯克,你对马云这句话,怎么理解?(回答这句话在向谁提问，只写名字)",
			},
			{
				"role":    "assistant",
				"content": "马斯克",
			},
			{
				"role":    "user",
				"content": "马斯克，马克思说你是资本家，你怎么看？(回答这句话在向谁提问，只写名字)",
			},
			{
				"role":    "assistant",
				"content": "马斯克",
			},
			{
				"role":    "user",
				"content": "马斯克说你是资本家马云你怎么看？(回答这句话在向谁提问，只写名字)",
			},
			{
				"role":    "assistant",
				"content": "马云",
			},
		},
		"stream":      false,
		"model_name":  "Awakener",
		"temperature": 0.27,
		"max_tokens":  0,
		"prompt_name": "default",
	})

	if err != nil {
		return "", fmt.Errorf("error marshalling request body: %v", err)
	}

	// 发送POST请求
	//quest_url := "http://52.83.116.11:13679/Think/chat/chat"
	quest_url := config.Conf.SemanticAnalysisUrl + "/Think/chat/chat"
	fmt.Println("语义解析请求的url: ", quest_url)
	resp, err := http.Post(quest_url, "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		return "", fmt.Errorf("error sending request: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("error reading response body: %v", err)
	}
	// 响应回来的数据 data: {"text": "唐僧", "message_id": "ca79a6c85c3c4d9c868d2966f9c960e0"}
	//检查并移除"data: "前缀
	responseStr := string(body)
	if strings.HasPrefix(responseStr, "data: ") {
		responseStr = strings.TrimPrefix(responseStr, "data: ")
	}
	var apiResponse ApiResponse
	// 解析JSON响应
	if responseStr == "" {
		fmt.Println("responseStr: ", responseStr)
		return "", nil
	}

	if err = json.Unmarshal([]byte(responseStr), &apiResponse); err != nil {
		fmt.Println("responseStr: ", responseStr)
		return "", fmt.Errorf("error unmarshalling response JSON: %v", err)
	}

	// 返回text字段的内容
	return apiResponse.Text, nil
}
