// PRE-GENERATED (design session). Pure logic: parse an AutoEQ "ParametricEQ.txt" into EqState.
// No APO / no network needed. Unit-test with a sample AutoEQ file in the dev session.
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using DansoriEQ.Core.Eq;

namespace DansoriEQ.Core.Profiles;

public static class AutoEqParser
{
    private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;

    /// <summary>
    /// Parses lines like:
    ///   Preamp: -6.8 dB
    ///   Filter 1: ON PK Fc 105 Hz Gain 4.2 dB Q 0.70
    /// </summary>
    public static EqState Parse(string text)
    {
        var s = new EqState();
        if (string.IsNullOrWhiteSpace(text)) return s;

        foreach (var raw in text.Split('\n'))
        {
            var line = raw.Trim();
            if (line.StartsWith("Preamp:", StringComparison.OrdinalIgnoreCase))
            {
                var m = Regex.Match(line, @"-?\d+(\.\d+)?");
                if (m.Success) s.PreampDb = double.Parse(m.Value, Inv);
            }
            else if (line.StartsWith("Filter", StringComparison.OrdinalIgnoreCase) &&
                     Regex.IsMatch(line, @"\bON\b", RegexOptions.IgnoreCase))
            {
                var typeM = Regex.Match(line, @"\b(PK|LSC|LS|HSC|HS)\b");
                var fcM = Regex.Match(line, @"Fc\s+([\d.]+)\s*Hz", RegexOptions.IgnoreCase);
                var gainM = Regex.Match(line, @"Gain\s+(-?[\d.]+)\s*dB", RegexOptions.IgnoreCase);
                var qM = Regex.Match(line, @"Q\s+([\d.]+)", RegexOptions.IgnoreCase);
                if (!typeM.Success || !fcM.Success) continue;

                s.Filters.Add(new Filter
                {
                    Type = FilterTypeExtensions.FromApoToken(typeM.Value),
                    Fc = double.Parse(fcM.Groups[1].Value, Inv),
                    GainDb = gainM.Success ? double.Parse(gainM.Groups[1].Value, Inv) : 0,
                    Q = qM.Success ? double.Parse(qM.Groups[1].Value, Inv) : 1.0,
                    Enabled = true
                });
            }
        }
        return s;
    }
}
