package util

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type RequestBody struct {
	Model    string    `json:"model"`
	Messages []Message `json:"messages"`
}

const ChatGptUrl = "https://api.openai.com/v1/chat/completions"
const ApiKey = "sk-proj-gmxWE5taNAc3blthTDOrT3BlbkFJa2ZkQJAoqdjNSRihG4ZY"

func SendOpenAIRequest(Query string) (string, error) {
	requestBody := RequestBody{
		Model: "gpt-4o-mini",
		Messages: []Message{
			{
				Role:    "system",
				Content: "下面单词来自方舟ARk，将他们翻译成中文。提问格式为:'item,item2,item3'。要求返回格式为:'物品1,物品2，物品3'",
			},
			{
				Role:    "user",
				Content: Query,
			},
		},
	}
	body, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatalf("封发请求正文失败: %v", err)
		return "", err
	}
	req, err := http.NewRequest("POST", ChatGptUrl, bytes.NewBuffer(body))
	if err != nil {
		log.Fatalf("创建请求失败: %v", err)
		return "", err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+ApiKey)
	// Set up proxy
	proxy, err := url.Parse(ProxyHost)
	if err != nil {
		log.Fatalf("Failed to parse proxy URL: %v", err)
		return "", err
	}
	transport := &http.Transport{
		Proxy: http.ProxyURL(proxy),
	}

	client := &http.Client{Transport: transport}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("发送请求失败: %v", err)
		return "", err
	}
	defer resp.Body.Close()

	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("读取响应正文失败: %v", err)
		return "", err
	}
	if resp.StatusCode != http.StatusOK {
		return "", errors.New("web status error")
	} else {
		return string(responseBody), nil
	}
}
