// PRE-GENERATED (design session). Pure logic.
using System.Linq;

namespace DansoriEQ.Core.Eq;

/// <summary>Computes a safe negative preamp to prevent digital clipping after EQ.</summary>
public static class PreampCalculator
{
    /// <summary>
    /// Scans the composite band response (ignoring any existing preamp) and returns
    /// -(max positive gain) - margin. Never returns a positive value.
    /// </summary>
    public static double ComputeSafePreamp(EqState state, double marginDb = 0.5,
                                           double fs = FrequencyResponse.DefaultSampleRate)
    {
        var bandsOnly = new EqState { PreampDb = 0, Filters = state.Filters };
        double peak = FrequencyResponse.Sample(bandsOnly, 512, fs).Max(p => p.Db);
        return peak <= 0 ? 0.0 : -(peak + marginDb);
    }
}
