using System;
using Microsoft.Win32;

namespace ModpackLauncher.Services;

/// <summary>
/// Detects whether Microsoft Edge WebView2 Runtime is installed.
/// Required by the Xbox Live SDK + WebView2 sign-in flow used by the launcher when
/// no custom Azure client ID is configured. Preinstalled on Windows 10/11 since
/// 2021 (came with Edge), but not guaranteed on older / cleaned Windows installs.
/// </summary>
public static class WebView2Check
{
    private const string ClientGuid = "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"; // Microsoft Edge WebView2 Runtime

    public const string DownloadUrl = "https://developer.microsoft.com/microsoft-edge/webview2/";

    public static bool IsInstalled()
    {
        // The runtime registers in one of three places depending on machine vs. per-user install.
        return GetVersion(RegistryHive.LocalMachine, $@"SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{ClientGuid}") is { } v1 && v1 != "0.0.0.0"
            || GetVersion(RegistryHive.LocalMachine, $@"SOFTWARE\Microsoft\EdgeUpdate\Clients\{ClientGuid}")            is { } v2 && v2 != "0.0.0.0"
            || GetVersion(RegistryHive.CurrentUser,  $@"Software\Microsoft\EdgeUpdate\Clients\{ClientGuid}")            is { } v3 && v3 != "0.0.0.0";
    }

    private static string? GetVersion(RegistryHive hive, string keyPath)
    {
        try
        {
            using var baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default);
            using var key = baseKey.OpenSubKey(keyPath);
            return key?.GetValue("pv") as string;
        }
        catch
        {
            return null;
        }
    }
}
