using Predictalytics.Application.Interfaces;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Predictalytics.Worker.Services;

/// <summary>
/// Background worker that reports platform statistics every 5 minutes.
/// </summary>
public class ReportingWorker : BackgroundService
{
    private readonly IPlatformStatisticsService _statsService;
    private readonly ILogger<ReportingWorker> _logger;
    private const int IntervalMinutes = 5;

    public ReportingWorker(IPlatformStatisticsService statsService, ILogger<ReportingWorker> logger)
    {
        _statsService = statsService;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // Initial delay to align with the first 5-minute mark
        await Task.Delay(TimeSpan.FromMinutes(IntervalMinutes), stoppingToken);

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                ReportStats();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in ReportingWorker cycle");
            }

            await Task.Delay(TimeSpan.FromMinutes(IntervalMinutes), stoppingToken);
        }
    }

    private void ReportStats()
    {
        var statsMap = _statsService.GetAndResetStats();
        
        _logger.LogWarning("--- 📊 Platform Activity Report (Last {Min}m) ---", IntervalMinutes);

        if (statsMap.Count == 0)
        {
            _logger.LogWarning("No activity detected across platforms.");
        }

        foreach (var (platform, stats) in statsMap)
        {
            var dupStr = stats.DuplicateErrors > 0 ? $" | Duplikatfehler: {stats.DuplicateErrors}" : "";
            _logger.LogWarning("[{Platform}] Markets: {M} | New Traders: {T} | Analyzed: {An} | Activities: {A}{D}",
                platform, stats.MarketsSynced, stats.TradersDiscovered, stats.TradersAnalyzed, stats.TradesProcessed, dupStr);
        }

        _logger.LogWarning("------------------------------------------------");
    }
}
