using Microsoft.Extensions.Logging; using NordPool.Models; using NordPoolManager.Interface; namespace NordPoolManager; public class CheapestIntervalsFinder(ILogger logger) : ICheapestIntervalsFinder { public IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline) { if (prices.Prices is not { Count: > 0 }) { logger.LogWarning("No prices available for cheapest interval calculation"); return []; } if (numberOfIntervals <= 0) { logger.LogWarning("Number of intervals requested is {Count}, returning empty", numberOfIntervals); return []; } var eligible = prices.Prices .AsParallel() .Where(p => p is { Start: not null, End: not null, Price: not null }) .Where(p => p.End!.Value <= deadline) .Where(p => p.Price!.Value <= priceCap) .OrderBy(p => p.Price!.Value) .ThenBy(p => p.Start!.Value) .Take(numberOfIntervals) .ToList(); var ranked = eligible .Select((p, index) => new CheapestIntervalResult { Start = p.Start!.Value, End = p.End!.Value, Price = p.Price!.Value, Rank = index + 1 }) .OrderBy(r => r.Start) .ToList(); logger.LogInformation("Found {Count} cheapest intervals out of {Requested} requested (deadline: {Deadline}, price cap: {Cap})", ranked.Count, numberOfIntervals, deadline, priceCap); return ranked; } public bool IsCurrentIntervalCheap(IReadOnlyList cheapestIntervals, DateTime utcNow) { return cheapestIntervals.AsParallel().Any(interval => utcNow >= interval.Start && utcNow < interval.End); } }