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

namespace IngredientsAI.Services
{
    public class OllamaService
    {
        private readonly HttpClient _http;
        private readonly IConfiguration _config;

        public OllamaService(IConfiguration config)
        {
            _config = config;
            var handler = new HttpClientHandler
            {
                // Ignore SSL errors (utile pour ton VPS si certificat pas reconnu en local)
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
            };

            _http = new HttpClient(handler)
            {
                BaseAddress = new Uri(_config["Ollama:Url"] ?? "https://ollama.byakurepo.online")
            };
        }

        // Exemple : récupère la liste des modèles disponibles
        public async Task<IEnumerable<string>> GetModelsAsync()
        {
            var res = await _http.GetAsync("/api/tags");
            res.EnsureSuccessStatusCode();

            var json = await res.Content.ReadAsStringAsync();
            using var doc = JsonDocument.Parse(json);

            return doc.RootElement
                      .GetProperty("models")
                      .EnumerateArray()
                      .Select(m => m.GetProperty("name").GetString() ?? string.Empty)
                      .ToList();
        }
    }
}
