namespace SirayaPrinter.Sync;

public static class HealthChecker
{
    private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(3) };

    public static async Task<int?> FindHealthyPortAsync(CancellationToken ct)
    {
        for (var port = 5000; port <= 5010; port++)
        {
            try
            {
                var url = $"http://127.0.0.1:{port}/health";
                using var response = await Http.GetAsync(url, ct);
                if (response.IsSuccessStatusCode)
                    return port;
            }
            catch
            {
                // try next port
            }
        }
        return null;
    }

    public static async Task<bool> WaitForHealthAsync(int timeoutSec, CancellationToken ct)
    {
        var deadline = DateTime.UtcNow.AddSeconds(timeoutSec);
        while (DateTime.UtcNow < deadline)
        {
            var port = await FindHealthyPortAsync(ct);
            if (port != null) return true;
            await Task.Delay(2000, ct);
        }
        return false;
    }
}
