using System.Management;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusUsbService
{
    public IReadOnlyList<NexusUsbDeviceInfo> GetConnectedDevices()
    {
        var devices = new List<NexusUsbDeviceInfo>();

        try
        {
            using var searcher = new ManagementObjectSearcher(
                "SELECT Name, Manufacturer, PNPClass, Description FROM Win32_PnPEntity WHERE PNPClass='USB'");
            foreach (ManagementObject obj in searcher.Get())
            {
                var name = obj["Name"]?.ToString()?.Trim();
                if (string.IsNullOrWhiteSpace(name))
                {
                    continue;
                }

                var manufacturer = obj["Manufacturer"]?.ToString()?.Trim();
                var deviceType = obj["Description"]?.ToString()?.Trim()
                    ?? obj["PNPClass"]?.ToString()?.Trim()
                    ?? "USB";

                devices.Add(new NexusUsbDeviceInfo
                {
                    Name = name,
                    DeviceType = deviceType,
                    Manufacturer = string.IsNullOrWhiteSpace(manufacturer) ? "—" : manufacturer,
                });
            }
        }
        catch
        {
            // WMI unavailable
        }

        return devices
            .DistinctBy(static d => d.Name, StringComparer.OrdinalIgnoreCase)
            .OrderBy(static d => d.Name, StringComparer.OrdinalIgnoreCase)
            .Take(50)
            .ToList();
    }
}
