using ClaudeDo.Worker.Hub;
using ClaudeDo.Worker.State;

namespace ClaudeDo.Worker.Lifecycle;

public sealed class StaleTaskRecovery : IHostedService
{
    public const string Phase = "stale-tasks";

    private readonly ITaskStateService _state;
    private readonly HubBroadcaster _broadcaster;
    private readonly ILogger<StaleTaskRecovery> _logger;

    public StaleTaskRecovery(ITaskStateService state, HubBroadcaster broadcaster, ILogger<StaleTaskRecovery> logger)
    {
        _state = state;
        _broadcaster = broadcaster;
        _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");

        await _broadcaster.OperationProgress(OperationProgressOpKeys.StartupRecovery, Phase, 0, 0);
    }

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