namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Proxy.Supervisor;

/// <summary>
///     Respawn-with-backoff schedule per <c>driver-stability.md §"Crash-loop circuit breaker"</c>:
///     5s → 15s → 60s, capped. Reset on a successful (&gt; <see cref="StableRunThreshold"/>)
///     run.
/// </summary>
public sealed class Backoff
{
    public static TimeSpan[] DefaultSequence { get; } =
        [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(60)];

    public TimeSpan StableRunThreshold { get; init; } = TimeSpan.FromMinutes(2);

    private readonly TimeSpan[] _sequence;
    private int _index;

    public Backoff(TimeSpan[]? sequence = null) => _sequence = sequence ?? DefaultSequence;

    public TimeSpan Next()
    {
        var delay = _sequence[Math.Min(_index, _sequence.Length - 1)];
        _index++;
        return delay;
    }

    /// <summary>Called when the spawned process has stayed up past the stable threshold.</summary>
    public void RecordStableRun() => _index = 0;
}
