namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Supervisor;

/// <summary>
///     Respawn-with-backoff schedule for the FOCAS Host process. Matches Galaxy Tier-C:
///     5s → 15s → 60s cap. A sustained stable run (default 2 min) resets the index so a
///     one-off crash after hours of steady-state doesn't start from the top of the ladder.
/// </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;
    }

    public void RecordStableRun() => _index = 0;

    public int AttemptIndex => _index;
}
