using System.Diagnostics;
using NostrServices.Client;

namespace NostrServices.Services;

public class PubkeyStatsService : BackgroundService
{
    private readonly RedisStore _store;
    private readonly ILogger<PubkeyStatsService> _logger;

    public PubkeyStatsService(RedisStore store, ILogger<PubkeyStatsService> logger)
    {
        _store = store;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                var sw = Stopwatch.StartNew();
                var results = new List<PubKeyStat>();
                var allKeys = new HashSet<string>();
                await foreach (var k in _store.EnumerateProfiles().WithCancellation(stoppingToken))
                {
                    allKeys.Add(k);
                }

                _logger.LogInformation("Collected {count:#,##0} pubkeys in: {n:#,##0}ms", allKeys.Count, sw.Elapsed.TotalMilliseconds);

                sw.Restart();
                foreach (var pk in allKeys)
                {
                    var evs = await _store.CountUserEvents(pk);
                    if (evs > 3)
                    {
                        var stat = new PubKeyStat
                        {
                            PubKey = Convert.FromHexString(pk),
                            LastUpdate = DateTime.UtcNow,
                            TotalEvents = evs
                        };

                        results.Add(stat);
                    }
                }

                _logger.LogInformation("Computed {count:#,##0} pubkey stats in: {n:#,##0}ms", results.Count, sw.Elapsed.TotalMilliseconds);

                await _store.StorePubkeyStats(results);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.Message);
            }

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