using System.Diagnostics;
using System.Runtime.InteropServices;
using RioJoy.Core.Profiles;

namespace RioJoy.Tray.Os;

/// <summary>
/// <see cref="IForegroundProcessProvider"/> backed by Win32: resolves the
/// foreground window's owning process and returns its executable file name. Used
/// by the auto-switch watcher to detect native games vs. supported titles.
/// </summary>
public sealed class ForegroundProcessProvider : IForegroundProcessProvider
{
    public string? GetForegroundExecutable()
    {
        nint hwnd = GetForegroundWindow();
        if (hwnd == 0)
            return null;

        _ = GetWindowThreadProcessId(hwnd, out uint pid);
        if (pid == 0)
            return null;

        try
        {
            using Process process = Process.GetProcessById((int)pid);
            // MainModule can throw for protected/elevated processes; ProcessName is a safe fallback.
            return process.MainModule?.ModuleName ?? process.ProcessName;
        }
        catch
        {
            return null;
        }
    }

    [DllImport("user32.dll")]
    private static extern nint GetForegroundWindow();

    [DllImport("user32.dll")]
    private static extern uint GetWindowThreadProcessId(nint hWnd, out uint lpdwProcessId);
}
