using System;
using System.Collections.Generic;

namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Host.Stability;

/// <summary>
///     Frequency-capped soft-recycle decision per <c>driver-stability.md §"Recycle Policy"</c>.
///     Default cap: 1 soft recycle per hour. Scheduled recycle at 03:00 local; supervisor reads
///     <see cref="ShouldSoftRecycleScheduled"/> to decide.
/// </summary>
public sealed class RecyclePolicy
{
    public TimeSpan SoftRecycleCap { get; init; } = TimeSpan.FromHours(1);
    public int DailyRecycleHourLocal { get; init; } = 3;

    private readonly List<DateTime> _recentRecyclesUtc = new();

    /// <summary>Returns true if a soft recycle would be allowed under the frequency cap.</summary>
    public bool TryRequestSoftRecycle(DateTime utcNow, out string? reason)
    {
        _recentRecyclesUtc.RemoveAll(t => utcNow - t > SoftRecycleCap);
        if (_recentRecyclesUtc.Count > 0)
        {
            reason = $"soft-recycle frequency cap: last recycle was {(utcNow - _recentRecyclesUtc[_recentRecyclesUtc.Count - 1]).TotalMinutes:F1} min ago";
            return false;
        }
        _recentRecyclesUtc.Add(utcNow);
        reason = null;
        return true;
    }

    public bool ShouldSoftRecycleScheduled(DateTime localNow, ref DateTime lastScheduledDateLocal)
    {
        if (localNow.Hour != DailyRecycleHourLocal) return false;
        if (localNow.Date <= lastScheduledDateLocal.Date) return false;

        lastScheduledDateLocal = localNow.Date;
        return true;
    }
}
