// PRE-GENERATED (design session). Polls the foreground app; raises AppChanged on change.
// Feeds SwitchRuleEvaluator for per-app auto-switching (M12). Win32 — untested here.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Threading;

namespace DansoriEQ.App.Switching;

public sealed class ForegroundAppWatcher : IDisposable
{
    [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);

    private readonly DispatcherTimer _timer;
    private string? _last;

    public event Action<string>? AppChanged;

    public ForegroundAppWatcher(double intervalMs = 1000)
    {
        _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(intervalMs) };
        _timer.Tick += (_, __) => Poll();
    }

    public void Start() => _timer.Start();
    public void Stop() => _timer.Stop();

    private void Poll()
    {
        try
        {
            var hwnd = GetForegroundWindow();
            if (hwnd == IntPtr.Zero) return;
            GetWindowThreadProcessId(hwnd, out uint pid);
            if (pid == 0) return;
            var name = Process.GetProcessById((int)pid).ProcessName;
            if (!string.Equals(name, _last, StringComparison.OrdinalIgnoreCase))
            {
                _last = name;
                AppChanged?.Invoke(name);
            }
        }
        catch { /* process may have exited between calls */ }
    }

    public void Dispose() => _timer.Stop();
}
