#Requires -Version 7.4

function Test-CIMHealthPrerequisite {
    <#
    .SYNOPSIS
        Validates that the CIM/WMI service is responsive.

    .DESCRIPTION
        Performs a lightweight CIM probe with a short timeout to detect an
        unresponsive WMI service early. This prerequisite sorts alphabetically
        before all other prerequisites (C < E, M, O, P, W), ensuring it runs
        first and fails fast rather than letting downstream CIM-dependent
        checks hang indefinitely.

    .EXAMPLE
        Test-CIMHealthPrerequisite

        Returns a result object indicating whether CIM/WMI is responsive.

    .OUTPUTS
        [PSCustomObject] with Name, Passed, Message, Required, Current, and HelpUrl properties.
    #>
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param()

    $timeoutSeconds = 5

    try {
        $null = Get-CimInstance -ClassName Win32_OperatingSystem -Property BuildNumber -OperationTimeoutSec $timeoutSeconds -ErrorAction Stop

        [PSCustomObject]@{
            Name     = 'CIM/WMI Health'
            Passed   = $true
            Message  = 'CIM/WMI service is responsive.'
            Required = "WMI service must respond within ${timeoutSeconds}s"
            Current  = 'Responsive'
            HelpUrl  = $null
        }
    }
    catch {
        [PSCustomObject]@{
            Name     = 'CIM/WMI Health'
            Passed   = $false
            Message  = "CIM/WMI service is unresponsive (timed out after ${timeoutSeconds}s). Run: Restart-Service winmgmt -Force"
            Required = "WMI service must respond within ${timeoutSeconds}s"
            Current  = "Unresponsive: $($_.Exception.Message)"
            HelpUrl  = 'https://learn.microsoft.com/en-us/windows/win32/wmisdk/wmi-troubleshooting'
        }
    }
}
