using System.Text; using Mercados.Infrastructure; using Mercados.Infrastructure.DataFetchers; using Mercados.Infrastructure.Persistence; using Mercados.Infrastructure.Persistence.Repositories; using Mercados.Worker; using Polly; using Polly.Extensions.Http; using Mercados.Infrastructure.Services; using DotNetEnv; using DotNetEnv.Configuration; var envFilePath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../../.env")); // Cargamos el archivo .env desde la ruta explícita. // Si no lo encuentra, Load retornará false. if (!Env.Load(envFilePath).Any()) { Console.WriteLine($"ADVERTENCIA: No se pudo encontrar el archivo .env en la ruta: {envFilePath}"); } Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { // La línea 'config.AddDotNetEnv(optional: true);' ha sido eliminada. IConfiguration configuration = hostContext.Configuration; // --- 1. Registro de Servicios de Infraestructura --- services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); //services.AddScoped(); services.AddScoped(); // --- 2. Registro de los Data Fetchers --- // Descomentados para la versión final y funcional. services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // --- 3. Configuración de Clientes HTTP con Polly --- services.AddHttpClient("MercadoAgroFetcher").AddPolicyHandler(GetRetryPolicy()); services.AddHttpClient("BcrDataFetcher").AddPolicyHandler(GetRetryPolicy()); services.AddHttpClient("FinnhubDataFetcher").AddPolicyHandler(GetRetryPolicy()); // --- 4. Registro del Worker Principal --- services.AddHostedService(); }) .Build(); static IAsyncPolicy GetRetryPolicy() { return HttpPolicyExtensions .HandleTransientHttpError() .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.RequestTimeout) .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), onRetry: (outcome, timespan, retryAttempt, context) => { Console.WriteLine($"[Polly] Reintentando petición... Intento {retryAttempt}. Esperando {timespan.TotalSeconds}s. Causa: {outcome.Exception?.Message ?? outcome.Result.ReasonPhrase}"); }); } await host.RunAsync();