using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using ToolsServices;

namespace Services.Whisper
{
    public static class WhisperService
    {
        #region Variables
        private static HttpClient? _HttpClient;
        private static readonly string NomFichierData = FichiersInternesService.ParamsWhisper;// "paramsWhisper.txt";
        private static List<string> ImagesFullFilename = new();
        #endregion

        #region InterActions
        public static async Task<bool> IsWhisperActif()
        {
            LoggerService.LogInfo($"WhisperService.IsWhisperActif");
            try
            {
                ParametresWhisperService? whisper = LoadParametres();
                if (whisper == null)
                {
                    var msg = "Erreur de chargement des paramètres Whisper.";
                    LoggerService.LogWarning(msg);
                    return false;
                }
                var url = $"{whisper.Whisper_URL}/status";
                _HttpClient = new HttpClient();

                _HttpClient.Timeout = TimeSpan.FromSeconds(30);
                var response = await _HttpClient.GetAsync(url);
                LoggerService.LogDebug($"WhisperService.IsWhisperActif : {response.IsSuccessStatusCode}");
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                LoggerService.LogError($"WhisperService.IsWhisperActif : False --> {ex.Message}");
                return false;
            }
        }

        public static async Task<(bool, string)> TranscribeAudio(string fullFileName)
        {
            LoggerService.LogInfo($"WhisperService.TranscribeAudio");
            try
            {
                ParametresWhisperService? whisper = LoadParametres();
                if (whisper == null)
                    whisper = new ParametresWhisperService();

                var _HttpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(whisper.Whisper_TimeOut) };
                using var form = new MultipartFormDataContent();

                // Charger le fichier en mémoire
                if (!System.IO.File.Exists(fullFileName))
                {
                    return (false, $"Le fichier n'existe pas : {fullFileName}");
                }
                using var fileStream = System.IO.File.OpenRead(fullFileName);
                var fileContent = new StreamContent(fileStream);
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("audio/wav");

                // Ajouter le fichier sous le champ "file"
                form.Add(fileContent, "file", System.IO.Path.GetFileName(fullFileName));

                var url = $"{whisper.Whisper_URL}/transcribe/";
                var response = await _HttpClient.PostAsync($"{url}", form);

                if (!response.IsSuccessStatusCode)
                {
                    var err = await response.Content.ReadAsStringAsync();
                    var msg = $"Erreur Whipster ({response.StatusCode}) : {err}";
                    LoggerService.LogWarning(msg);
                    return (false, $"{msg}");
                }

                var json = await response.Content.ReadFromJsonAsync<JsonElement>();

                var sReturn = json!.GetProperty("text")!.GetString();
                if (sReturn is null)
                    return (false, "réponse vide");

                return (true, sReturn);
            }
            catch (Exception ex)
            {
                LoggerService.LogError($"WhisperService.TranscribeAudio : {ex.Message}");
                return (false, ex.Message);
            }
        }
        #endregion

        #region Gestion des paramètres
        public static ParametresWhisperService? LoadParametres()
        {
            LoggerService.LogInfo("WhisperService.LoadParametres");
            ParametresWhisperService SelectedItem = new();

            try
            {
                if (File.Exists(NomFichierData))
                {

                    string[] lignes = File.ReadAllLines(NomFichierData);

                    if (lignes.Length > 0)
                        SelectedItem.Whisper_URL = lignes[0];

                    if (lignes.Length > 1)
                    {
                        if (int.TryParse(lignes[1], out int timeout))
                            SelectedItem.Whisper_TimeOut = timeout;
                    }

                }
                return SelectedItem;

            }
            catch
            {
                return null;
            }
        }

        public static bool SaveParametres(ParametresWhisperService selectedItem)
        {
            LoggerService.LogInfo("WhisperService.SaveParametres");
            try
            {
                StringBuilder sb = new();
                sb.AppendLine(selectedItem.Whisper_URL);
                sb.AppendLine(selectedItem.Whisper_TimeOut.ToString());

                File.WriteAllText(NomFichierData, sb.ToString());

                return true;
            }
            catch
            {
                return false;
            }

        }
        #endregion
    }
}
