using Health.Application.Diets;

namespace Health.WebApi.BackgroundServices;

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("饮食图片识别持久化任务消费者已启动");
        var idleDelay = TimeSpan.FromSeconds(1);
        var nextRecovery = DateTime.MinValue;

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope = _scopeFactory.CreateScope();
                var queue = scope.ServiceProvider.GetRequiredService<IDietImageAnalysisQueue>();
                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 analyzer = scope.ServiceProvider.GetRequiredService<IDietImageAnalyzer>();
                    var result = await analyzer.AnalyzeAsync(job, stoppingToken);
                    await queue.CompleteAsync(job.Id, result, stoppingToken);
                    DeleteFiles(job.FilePaths);
                }
                catch (Exception ex) when (ex is not OperationCanceledException)
                {
                    _logger.LogError(ex, "饮食图片识别任务失败: {JobId}", job.Id);
                    var terminal = await queue.RetryAsync(job.Id, ex.Message, stoppingToken);
                    if (terminal) DeleteFiles(job.FilePaths);
                }
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "饮食图片识别消费者循环异常");
                await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
            }
        }
    }

    private static void DeleteFiles(IEnumerable<string> paths)
    {
        foreach (var path in paths)
        {
            try { if (File.Exists(path)) File.Delete(path); }
            catch (IOException) { }
            catch (UnauthorizedAccessException) { }
        }
    }
}
