"""Windows C++ runtime check - verifies minimum Visual C++ Redistributable version."""

import platform


def check_windows_cpp_runtime(
    min_major: int,
    min_minor: int,
    min_patch: int,
) -> bool:
    """
    Check if a sufficient Microsoft Visual C++ Redistributable is installed (Windows only).

    Returns True if not on Windows, or if a compatible runtime is installed.
    Returns False if on Windows and no compatible runtime is found.
    """
    if platform.system() != "Windows":
        return True

    try:
        import winreg
    except ImportError:
        return True

    arch = platform.machine().lower()
    if arch in ("amd64", "x86_64"):
        arch_key = "x64"
    elif arch in ("arm64", "aarch64"):
        arch_key = "ARM64"
    else:
        arch_key = "x86"

    base_path = r"SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes"
    wow_path = r"SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes"

    for root, subkey in [
        (winreg.HKEY_LOCAL_MACHINE, base_path),
        (winreg.HKEY_LOCAL_MACHINE, wow_path),
    ]:
        try:
            key_path = f"{subkey}\\{arch_key}"
            with winreg.OpenKey(root, key_path, 0, winreg.KEY_READ) as key:
                try:
                    version, _ = winreg.QueryValueEx(key, "Version")
                except OSError:
                    continue
                if isinstance(version, str):
                    version = version.lstrip("v").strip()
                    parts = version.split(".")
                    major = int(parts[0]) if parts else 0
                    minor = int(parts[1]) if len(parts) > 1 else 0
                    patch = int(parts[2]) if len(parts) > 2 else 0
                else:
                    continue
                if (
                    major > min_major
                    or (major == min_major and minor >= min_minor)
                    or (
                        major == min_major and minor == min_minor and patch >= min_patch
                    )
                ):
                    return True
        except OSError:
            continue

    return False
