using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Markup;
using System.Xml.Linq;

namespace WpfApp1.Tools
{
    internal class HttpRequest
    {
        public static async Task<string> GptRequest(string json, string apiKey, string apiUrl)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromSeconds(10);
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
            //httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
            try
            {
                HttpResponseMessage response = httpClient.PostAsync(apiUrl, new StringContent(json, Encoding.UTF8, "application/json")).Result;
                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    return responseContent;
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    Trace.WriteLine($"Http error: {response.StatusCode} - {errorContent}");
                    return "";
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Http error occurred: " + ex.Message);
                return "";
            }
        }
    }
}
