using ClaudeDo.Data;
using ClaudeDo.Worker.Usage.Interfaces;
using Microsoft.EntityFrameworkCore;
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;

namespace ClaudeDo.Worker.Usage;

/// <summary>
/// Answers "is anything running?" from the task table rather than the in-memory queue slots,
/// so override-slot runs, continued runs, and runs still marked Running after a worker restart
/// all count. A read failure reports idle — the usage monitor must never poll harder because
/// its activity probe broke.
/// </summary>
public sealed class RunningTaskProbe : IRunningTaskProbe
{
    private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;

    public RunningTaskProbe(IDbContextFactory<ClaudeDoDbContext> dbFactory) => _dbFactory = dbFactory;

    public async Task<bool> AnyRunningAsync(CancellationToken ct = default)
    {
        try
        {
            await using var context = await _dbFactory.CreateDbContextAsync(ct);
            return await context.Tasks.AnyAsync(t => t.Status == TaskStatus.Running, ct);
        }
        catch (OperationCanceledException) when (ct.IsCancellationRequested)
        {
            throw;
        }
        catch
        {
            return false;
        }
    }
}
