// PRE-GENERATED (design session). Shared JSON -> EqDelta parser (used by all providers).
using System.Text.Json;

namespace DansoriEQ.Core.Ai;

public static class EqDeltaParser
{
    public static EqDelta FromJson(JsonElement input)
    {
        var delta = new EqDelta
        {
            PreampDb = input.TryGetProperty("preamp_db", out var pd) && pd.ValueKind == JsonValueKind.Number ? pd.GetDouble() : 0,
            Replace = input.TryGetProperty("replace", out var rp) && rp.ValueKind == JsonValueKind.True,
            Explanation = input.TryGetProperty("explanation", out var ex) ? ex.GetString() ?? "" : ""
        };
        if (input.TryGetProperty("filters", out var fs) && fs.ValueKind == JsonValueKind.Array)
            foreach (var f in fs.EnumerateArray())
                delta.Filters.Add(new EqDeltaFilter
                {
                    Type = f.TryGetProperty("type", out var ty) ? ty.GetString() ?? "PK" : "PK",
                    Fc = f.TryGetProperty("fc", out var fc) && fc.ValueKind == JsonValueKind.Number ? fc.GetDouble() : 1000,
                    Gain = f.TryGetProperty("gain", out var g) && g.ValueKind == JsonValueKind.Number ? g.GetDouble() : 0,
                    Q = f.TryGetProperty("q", out var q) && q.ValueKind == JsonValueKind.Number ? q.GetDouble() : 1.0,
                    Enabled = !f.TryGetProperty("enabled", out var en) || en.ValueKind != JsonValueKind.False
                });
        if (input.TryGetProperty("effects", out var fx) && fx.ValueKind == JsonValueKind.Object)
        {
            var e = new EqDeltaEffects();
            if (fx.TryGetProperty("crossfeed", out var cf) && cf.ValueKind == JsonValueKind.Number) e.Crossfeed = cf.GetDouble();
            if (fx.TryGetProperty("bass_boost_db", out var bb) && bb.ValueKind == JsonValueKind.Number) e.BassBoostDb = bb.GetDouble();
            if (fx.TryGetProperty("preamp_left_db", out var pl) && pl.ValueKind == JsonValueKind.Number) e.PreampLeftDb = pl.GetDouble();
            if (fx.TryGetProperty("preamp_right_db", out var pr) && pr.ValueKind == JsonValueKind.Number) e.PreampRightDb = pr.GetDouble();
            delta.Effects = e;
        }
        return delta;
    }

    /// <summary>Parse a JSON string that itself is the EqDelta object (json-mode providers).</summary>
    public static EqDelta FromJsonText(string json)
    {
        using var doc = JsonDocument.Parse(json);
        return FromJson(doc.RootElement);
    }
}
