// PRE-GENERATED (design session). Ties app + device watchers + rules + PresetLibrary:
// when the foreground app OR default output device matches a rule, apply that preset (M12).
using System;
using System.Collections.Generic;
using DansoriEQ.Core.Presets;
using DansoriEQ.Core.Switching;

namespace DansoriEQ.App.Switching;

public sealed class ProfileSwitcher : IDisposable
{
    private readonly ForegroundAppWatcher _appWatcher = new();
    private readonly DefaultDeviceWatcher _deviceWatcher = new();
    private readonly PresetLibrary _library;
    private readonly Action<EqPreset> _apply;
    private List<SwitchRule> _rules;
    private string? _app;
    private string? _device;
    private string? _lastApplied;

    public ProfileSwitcher(PresetLibrary library, Action<EqPreset> apply)
    {
        _library = library;
        _apply = apply;
        _rules = SwitchRulesStore.Load();
        _appWatcher.AppChanged += a => { _app = a; Evaluate(); };
        _deviceWatcher.DeviceChanged += d => { _device = d; Evaluate(); };
    }

    public void ReloadRules() => _rules = SwitchRulesStore.Load();

    public void Start() { _appWatcher.Start(); _deviceWatcher.Start(); }
    public void Stop() { _appWatcher.Stop(); _deviceWatcher.Stop(); }

    private void Evaluate()
    {
_rules = SwitchRulesStore.Load();   // runtime reload
        var rule = SwitchRuleEvaluator.Match(_rules, new SwitchContext { AppProcess = _app, DeviceName = _device });
        if (rule is null || rule.PresetName == _lastApplied) return;
        try
        {
            _apply(_library.Load(rule.PresetName));
            _lastApplied = rule.PresetName;
        }
        catch { /* preset missing/renamed — ignore */ }
    }

    public void Dispose()
    {
        _appWatcher.Dispose();
        _deviceWatcher.Dispose();
    }
}
