using ClaudeDo.Worker.State;

namespace ClaudeDo.Worker.Lifecycle;

public sealed class StaleTaskRecovery : IHostedService
{
    private readonly ITaskStateService _state;
    private readonly ILogger<StaleTaskRecovery> _logger;

    public StaleTaskRecovery(ITaskStateService state, ILogger<StaleTaskRecovery> logger)
    {
        _state = state;
        _logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var flipped = await _state.RecoverStaleRunningAsync("worker restart", cancellationToken);
        if (flipped > 0)
            _logger.LogWarning("Stale task recovery: flipped {Count} running task(s) to failed", flipped);
        else
            _logger.LogInformation("Stale task recovery: no stale tasks found");
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
