using System.Text.Json; using AutoMapper; using Microsoft.Extensions.Logging; using NordPool.Models; using NordPool.Models.Dtos; using NordPoolManager.Interface; using NordPoolManager.Models.Consts; namespace NordPoolManager; /// /// Holds NordPool price state and performs price math. Must stay free of /// IHaContext/generated entity dependencies so it can be a singleton. /// Fetching prices from Home Assistant lives in . /// public class NordPoolPriceService(IMapper mapper, ILogger logger) : INordPoolPriceService { public NordPoolPrice? TodayNordPoolPrice { get; internal set; } public NordPoolPrice? TomorrowNordPoolPrice { get; internal set; } public double CurrentPrice { get; internal set; } public int DayQuartersIndex { get; internal set; } = -1; public DateTime? LastUpdatedDate { get; private set; } public DateOnly? LastFetchedDate { get; internal set; } public async Task FetchPricesAsync(Func> fetchPricesForDate) { var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); var dateNow = DateOnly.FromDateTime(nowCet); if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(dateNow)) { if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation("Fetching today's prices from API for CET date: {Today}", dateNow); } TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow, fetchPricesForDate); } if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(dateNow.AddDays(1))) { if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", dateNow.AddDays(1)); } TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow.AddDays(1), fetchPricesForDate); } LastUpdatedDate = DateTime.UtcNow; LastFetchedDate = dateNow; } public void UpdateCurrentPrice() { var index = GetTimeQuarterIndex(DateTime.UtcNow); if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0); } if (DayQuartersIndex == index) return; if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index) { var price = TodayNordPoolPrice.Prices[index].Price; if (price.HasValue) { CurrentPrice = price.Value; } else { logger.LogWarning("Price at index {Index} is null", index); } } else { logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0); } DayQuartersIndex = index; } public double GetCurrentPrice() { return CurrentPrice; } public bool ShouldFetchNewPrices(DateOnly date) { if (!LastFetchedDate.HasValue) return true; if (LastFetchedDate.Value < date) return true; if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true; if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false; var currentHour = DateTime.Now.Hour; return currentHour >= 13; } public void RollOverPrices(DateOnly date) { TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 } ? TomorrowNordPoolPrice : new NordPoolPrice(); TomorrowNordPoolPrice = null; DayQuartersIndex = -1; LastFetchedDate = date; } public NordPoolPrice ParseAndAdjust(JsonElement? element) { var todayNordPoolPrice = ParseNordPoolResult(element); return AdjustedNordPoolPrice(todayNordPoolPrice); } internal NordPoolPrice ParseNordPoolResult(JsonElement? element) { if (!element.HasValue) return new NordPoolPrice(); var priceResult = element.Value.Deserialize(); return priceResult != null ? mapper.Map(priceResult) : new NordPoolPrice(); } internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice) { var recalculatedPrice = new NordPoolPrice { Prices = new List() }; if (todayNordPoolPrice.Prices is null) return recalculatedPrice; foreach (var price in todayNordPoolPrice.Prices) { if (price.Price is null) continue; recalculatedPrice.Prices.Add(new NordPoolDayPrice { Start = price.Start, End = price.End, Price = PriceCorrection(price.Price.Value) }); } return recalculatedPrice; } internal static double PriceCorrection(double mwPrice) { var kwPrice = mwPrice / ConversionConsts.MegawattToKilowattDivisor; var kwhPrice = kwPrice * ConversionConsts.VatRate; var cntPrice = kwhPrice * ConversionConsts.EuroToCentsMultiplier; return Math.Round(cntPrice, ConversionConsts.PriceDecimalPlaces); } internal static int GetTimeQuarterIndex(DateTime utcDate) { var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); var cetDate = TimeZoneInfo.ConvertTimeFromUtc(utcDate, cetTimeZone); var totalMinutes = cetDate.Hour * 60 + cetDate.Minute; return totalMinutes / NordPoolConsts.MinutesPerInterval; } private async Task FetchPricesForDateWithRetryAsync(DateOnly date, Func> fetchPricesForDate) { for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++) try { return await fetchPricesForDate(date); } catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts) { var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1)); logger.LogWarning(ex, "Attempt {Attempt}/{MaxAttempts} to fetch prices for {Date} failed. Retrying in {Delay}", attempt, NordPoolConsts.MaxFetchRetryAttempts, date, delay); await Task.Delay(delay); } catch (Exception ex) { logger.LogError(ex, "Failed to fetch prices for {Date} on attempt {Attempt} with unexpected error", date, attempt); break; } logger.LogWarning("All {MaxAttempts} attempts to fetch prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, date); return new NordPoolPrice(); } }