package main

import (
	"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 SendSemanticAnalysisRequest2(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": "马斯克",
			},
		},
		"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: ")
	}

	// 解析JSON响应
	var apiResponse ApiResponse
	if err = json.Unmarshal([]byte(responseStr), &apiResponse); err != nil {
		return "", fmt.Errorf("error unmarshalling response JSON: %v", err)
	}

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

func main() {
	// 要分析的句子
	sentence := "唐僧你怎么看这件事? 张三把罗翔老师抓到孙悟空的水帘洞，被白骨精救了。(回答这句话在向谁提问，只写名字)"
	response, err := SendSemanticAnalysisRequest2(sentence)
	if err != nil {
		fmt.Printf("Error making request: %v\n", err)
		return
	}

	fmt.Printf("Response: %s\n", response)
}
