using dotenv.net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace WpfApp1.Tools
{
    internal class GptTools
    {
        private static string apiKey = "";
        private static string apiUrl = "";

        public static void SetApi(string key, string url)
        {
            apiKey = key;
            apiUrl = url;
        }

        public static void GetApi()
        {
            DotEnv.Load();
            apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
            apiUrl = Environment.GetEnvironmentVariable("OPENAI_API_BASE");
        }

        public static string Talk(string model, string text)
        {
            var data = new
            {
                model = model,
                messages = new[]
            {
                new
                {
                    role = "user",
                    content = new[]
                    {
                        new
                        {
                            type = "text",
                            text = text
                        }
                    }
                }
            },
                max_tokens = 1000
            };

            string requestJson = JsonSerializer.Serialize(data);
            string responseJson = HttpRequest.GptRequest(requestJson, apiKey, apiUrl).GetAwaiter().GetResult();
            if (responseJson.Length == 0)
            {
                System.Windows.MessageBox.Show("请求错误");
                return "";
            }

            JsonElement root = JsonDocument.Parse(responseJson).RootElement;
            string content = root.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
            return content;
        }
    }
}
