using EonaCat.LogStack.Core;
using System;

namespace EonaCat.LogStack.Boosters;

/// <summary>
/// Sampling booster that probabilistically filters log events
/// </summary>
public sealed class SamplingBooster : BoosterBase
{
    private readonly double _samplingRate;
    private readonly Random _random;
    private long _totalLogged;
    private long _totalSampled;

    public SamplingBooster(double samplingRate = 0.1) : base("Sampling")
    {
        if (samplingRate < 0.0 || samplingRate > 1.0)
        {
            throw new ArgumentOutOfRangeException(nameof(samplingRate), "Must be between 0.0 and 1.0");
        }

        _samplingRate = samplingRate;
        _random = new Random();
    }

    /// <summary>
    /// Always log critical and error events, sample the rest
    /// </summary>
    public override bool Boost(ref LogEventBuilder builder)
    {
        _totalLogged++;

        // Sample based on configured rate
        bool shouldLog = _random.NextDouble() < _samplingRate;
        if (shouldLog)
        {
            _totalSampled++;
        }

        return shouldLog;
    }

    /// <summary>
    /// Gets sampling statistics
    /// </summary>
    public (long total, long sampled, double rate) GetStatistics()
    {
        return (_totalLogged, _totalSampled, _totalLogged > 0 ? (double)_totalSampled / _totalLogged : 0.0);
    }
}
