using Health.Application.Reports;

namespace Health.WebApi.BackgroundServices;

public sealed class ReportAnalysisWorker(
    IServiceScopeFactory scopeFactory,
    ILogger<ReportAnalysisWorker> logger) : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
    private readonly ILogger<ReportAnalysisWorker> _logger = logger;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("报告 AI 持久化任务消费者已启动");
        var idleDelay = TimeSpan.FromSeconds(1);
        var nextRecovery = DateTime.MinValue;
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = _scopeFactory.CreateScope();
                var queue = scope.ServiceProvider.GetRequiredService<IReportAnalysisQueue>();
                if (DateTime.UtcNow >= nextRecovery)
                {
                    await queue.RecoverStaleAsync(stoppingToken);
                    nextRecovery = DateTime.UtcNow.AddMinutes(1);
                }
                var job = await queue.TryTakeAsync(stoppingToken);
                if (job == null)
                {
                    await Task.Delay(idleDelay, stoppingToken);
                    idleDelay = TimeSpan.FromSeconds(Math.Min(idleDelay.TotalSeconds * 2, 5));
                    continue;
                }

                idleDelay = TimeSpan.FromSeconds(1);
                try
                {
                    var analysisService = scope.ServiceProvider.GetRequiredService<IReportAnalysisService>();
                    await analysisService.AnalyzeAsync(job, stoppingToken);
                    await queue.CompleteAsync(job.TaskId, stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "报告 AI 分析任务执行异常: {ReportId}", job.ReportId);
                    await queue.RetryAsync(job.TaskId, ex.Message, stoppingToken);
                }
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "报告任务消费者循环异常");
                await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
            }
        }
    }
}
