using System.Globalization;
using System.Management;
using Microsoft.Win32;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusGpuService
{
    private static readonly CultureInfo DaDk = CultureInfo.GetCultureInfo("da-DK");

    public NexusGpuSnapshot Capture()
    {
        var wmi = TryReadFromWmi();
        if (wmi.IsAvailable)
        {
            return wmi;
        }

        var registryName = ReadFromRegistry();
        return new NexusGpuSnapshot
        {
            Name = registryName,
            VramLabel = "—",
            LoadPercent = null,
            IsAvailable = !string.Equals(registryName, "Ukendt grafik", StringComparison.Ordinal),
        };
    }

    private static NexusGpuSnapshot TryReadFromWmi()
    {
        try
        {
            using var searcher = new ManagementObjectSearcher(
                "SELECT Name, AdapterRAM, VideoProcessor FROM Win32_VideoController");
            foreach (ManagementObject obj in searcher.Get())
            {
                var name = obj["Name"]?.ToString()?.Trim();
                if (string.IsNullOrWhiteSpace(name) ||
                    name.Contains("Microsoft Basic", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                var vramBytes = Convert.ToUInt64(obj["AdapterRAM"] ?? 0UL);
                var vramGb = vramBytes > 0 ? vramBytes / (1024d * 1024 * 1024) : 0;

                return new NexusGpuSnapshot
                {
                    Name = name,
                    VramLabel = vramGb >= 0.5 ? $"{vramGb.ToString("0.#", DaDk)} GB VRAM" : "—",
                    LoadPercent = null,
                    IsAvailable = true,
                };
            }
        }
        catch
        {
            // WMI unavailable
        }

        return new NexusGpuSnapshot { IsAvailable = false };
    }

    private static string ReadFromRegistry()
    {
        try
        {
            using var key = Registry.LocalMachine.OpenSubKey(
                @"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}");
            if (key is null)
            {
                return "Ukendt grafik";
            }

            foreach (var subKeyName in key.GetSubKeyNames())
            {
                using var sub = key.OpenSubKey(subKeyName);
                var desc = sub?.GetValue("DriverDesc") as string;
                if (!string.IsNullOrWhiteSpace(desc))
                {
                    return desc.Trim();
                }
            }
        }
        catch
        {
            // ignore
        }

        return "Ukendt grafik";
    }
}
