using System.Text;
using System.Text.Json;
using ToolsServices;

namespace Services.Ollama
{
    public static class EmbeddingService
    {
        public static async Task<(bool, float[]?)> GetEmbeddingAsync(string text, bool isOnDemand)
        {
            LoggerService.LogDebug("EmbeddingService.GetEmbeddingAsync");
            try
            {
                ParametresOllamaService? ollama = OllamaService.LoadParametres();
                if (ollama == null)
                {
                    var msg = "Erreur de chargement des paramètres Ollama.";
                    LoggerService.LogWarning(msg);
                    return (false, null);
                }
                var url = "";
                if (isOnDemand)
                    url = $"{ollama.Ollama_URL}/api/embeddings";
                else
                    url = $"{ollama.Ollama_Batch_URL}/api/embeddings";

                var request = new
                {
                    model = "nomic-embed-text",
                    prompt = text,
                    stream = false
                };
                HttpClient httpClient = new();
                var json = JsonSerializer.Serialize(request);
                var response = await httpClient.PostAsync(url,
                    new StringContent(json, Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();
                var result = await response.Content.ReadAsStringAsync();

                using var doc = JsonDocument.Parse(result);
                var retour = doc.RootElement
                    .GetProperty("embedding")
                    .EnumerateArray()
                    .Select(e => e.GetSingle())
                    .ToArray();
                return (true, retour);
            }
            catch (Exception ex)
            {
                LoggerService.LogError($"Erreur lors de la récupération de l'embedding : {ex.Message}");
                return (false, null);
            }
        }
    }
}
