using Predictalytics.Application.Interfaces;
using Predictalytics.Domain.Enums;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;

namespace Predictalytics.Worker.Services;

/// <summary>
/// Background service that periodically discovers new notable traders on platforms.
/// </summary>
public class DiscoveryWorker : BackgroundService
{
    private readonly IServiceProvider _services;
    private readonly IPlatformStatisticsService _statsService;
    private readonly ILogger<DiscoveryWorker> _logger;

    public DiscoveryWorker(IServiceProvider services, ILogger<DiscoveryWorker> logger, IPlatformStatisticsService statsService)
    { _services = services; _logger = logger; _statsService = statsService; }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("🔍 DiscoveryWorker started");
        await Task.Delay(10000, stoppingToken); // Delay to let other services initialize

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = _services.CreateScope();
                var discovery = scope.ServiceProvider.GetRequiredService<IDiscoveryService>();

                // Run discovery for all implemented platforms
                foreach (var platform in new[] { PlatformType.Polymarket, PlatformType.Limitless })
                {
                    var config = scope.ServiceProvider.GetRequiredService<Microsoft.Extensions.Configuration.IConfiguration>();
                    bool isEnabled = config.GetValue<bool>($"PlatformSettings:{platform}:EnableCrawling", platform == PlatformType.Polymarket);
                    if (!isEnabled) continue;

                    try
                    {
                        if (stoppingToken.IsCancellationRequested) break;

                        _logger.LogWarning("[{Platform}] Starting discovery scan...", platform);
                        var discovered = await discovery.RunDiscoveryAsync(platform, stoppingToken);
                        _statsService.TrackTraderDiscovery(platform, discovered.Count);
                        _logger.LogWarning("[{Platform}] Discovery found {Count} traders", platform, discovered.Count);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error in discovery for platform {Platform}", platform);
                    }
                }
            }
            catch (OperationCanceledException) { break; }
            catch (Exception ex) { _logger.LogError(ex, "DiscoveryWorker error"); }

            // Run discovery every 5 minutes
            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
        }

        _logger.LogInformation("🔍 DiscoveryWorker stopped");
    }
}
