#Requires -Version 7.4

function Get-vSEALOperatingSystemInfo {
    <#
    .SYNOPSIS
        Retrieves detailed operating system information.

    .DESCRIPTION
        Returns comprehensive OS information including version, edition,
        architecture, and platform detection (workstation/server/terminal server).
        Uses native Windows APIs for accurate detection.

    .EXAMPLE
        Get-vSEALOperatingSystemInfo

    .EXAMPLE
        $osInfo = Get-vSEALOperatingSystemInfo
        if ($osInfo.IsServer) { Write-Host "Running on Windows Server" }

    .OUTPUTS
        [PSCustomObject] with OS properties.
    #>
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param()

    Write-vSEALLog "Retrieving operating system information..." -Level VERBOSE

    # Call RtlGetVersion for accurate OS version info
    $osVersion = [vSEAL.Native.OSVERSIONINFOEXW]::new()
    $osVersion.dwOSVersionInfoSize = [System.Runtime.InteropServices.Marshal]::SizeOf($osVersion)
    $null = [vSEAL.Native.NativeMethods]::RtlGetVersion([ref]$osVersion)

    $suiteMask = [vSEAL.Native.SuiteMask]$osVersion.wSuiteMask
    $productType = [vSEAL.Native.ProductType]$osVersion.wProductType

    # Get product info (edition)
    $edition = 0
    $editionReturnValue = [vSEAL.Native.NativeMethods]::GetProductInfo(
        $osVersion.dwMajorVersion,
        $osVersion.dwMinorVersion,
        $osVersion.wServicePackMajor,
        $osVersion.wServicePackMinor,
        [ref]$edition
    )
    if (-not $editionReturnValue) {
        Write-vSEALLog "GetProductInfo failed; edition detection may be inaccurate" -Level WARNING
    }

    # Read supplemental info from registry (UBR, ReleaseId, DisplayVersion, EditionID only)
    $regPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
    $regData = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue

    $ubr = $regData.UBR
    $releaseId = $regData.ReleaseId
    $displayVersion = $regData.DisplayVersion
    $editionId = $regData.EditionID

    # Extract version components
    $majorVersion = [int]$osVersion.dwMajorVersion
    $minorVersion = [int]$osVersion.dwMinorVersion
    $buildNumber = [int]$osVersion.dwBuildNumber

    # Build version object
    $version = [Version]::new(
        $majorVersion,
        $minorVersion,
        $buildNumber,
        [int]($ubr ?? 0)
    )

    # Determine OS type flags
    $isWorkstation = $productType -eq [vSEAL.Native.ProductType]::VER_NT_WORKSTATION
    $isServer = -not $isWorkstation
    $isDomainController = $productType -eq [vSEAL.Native.ProductType]::VER_NT_DOMAIN_CONTROLLER

    # Terminal Server detection
    $isTerminalServer = (
        ($suiteMask -band [vSEAL.Native.SuiteMask]::VER_SUITE_TERMINAL) -and
        -not ($suiteMask -band [vSEAL.Native.SuiteMask]::VER_SUITE_SINGLEUSERTS)
    )

    # Determine OS name from build number thresholds (ported from OSVersionExt)
    # Reference: https://github.com/AaronKelley/detect-windows-version
    $osName = switch ($true) {
        # Windows 11 (Build >= 22000, Workstation)
        ($majorVersion -eq 10 -and $minorVersion -eq 0 -and $buildNumber -ge 22000 -and $isWorkstation) {
            'Windows 11'
            break
        }
        # Windows Server 2022 (Build >= 20348, Server)
        ($majorVersion -eq 10 -and $minorVersion -eq 0 -and $buildNumber -ge 20348 -and $isServer) {
            'Windows Server 2022'
            break
        }
        # Windows 10 (Major 10, Workstation, Build < 22000)
        ($majorVersion -eq 10 -and $minorVersion -eq 0 -and $isWorkstation) {
            'Windows 10'
            break
        }
        # Windows Server 2019 (Build >= 17763, Server)
        ($majorVersion -eq 10 -and $minorVersion -eq 0 -and $buildNumber -ge 17763 -and $isServer) {
            'Windows Server 2019'
            break
        }
        # Windows Server 2016 (Major 10, Server, Build < 17763)
        ($majorVersion -eq 10 -and $minorVersion -eq 0 -and $isServer) {
            'Windows Server 2016'
            break
        }
        # Windows 8.1 / Server 2012 R2
        ($majorVersion -eq 6 -and $minorVersion -eq 3 -and $isWorkstation) { 'Windows 8.1'; break }
        ($majorVersion -eq 6 -and $minorVersion -eq 3 -and $isServer) { 'Windows Server 2012 R2'; break }
        # Windows 8 / Server 2012
        ($majorVersion -eq 6 -and $minorVersion -eq 2 -and $isWorkstation) { 'Windows 8'; break }
        ($majorVersion -eq 6 -and $minorVersion -eq 2 -and $isServer) { 'Windows Server 2012'; break }
        # Windows 7 / Server 2008 R2
        ($majorVersion -eq 6 -and $minorVersion -eq 1 -and $isWorkstation) { 'Windows 7'; break }
        ($majorVersion -eq 6 -and $minorVersion -eq 1 -and $isServer) { 'Windows Server 2008 R2'; break }
        # Fallback
        default { "Windows $majorVersion.$minorVersion" }
    }

    # Append edition to name if available
    if ($editionId) {
        $osName = "$osName $editionId"
    }

    # Enterprise Multi-Session (AVD) detection
    $isEnterpriseMultiSession = $false
    if ($edition -eq 175) {  # PRODUCT_DATACENTER_SERVER
        if ($editionId -in @('EnterpriseMultiSession', 'ServerRdsh')) {
            $isEnterpriseMultiSession = $true
        }
    }

    $result = [PSCustomObject]@{
        Name                                  = $osName
        Edition                               = $editionId ?? 'Unknown'
        Version                               = $version
        BuildNumber                           = $buildNumber
        ReleaseId                             = $releaseId
        ReleaseIdName                         = $displayVersion
        Architecture                          = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture
        Is64BitOperatingSystem                = [Environment]::Is64BitOperatingSystem
        IsWorkstation                         = $isWorkstation
        IsServer                              = $isServer
        IsDomainController                    = $isDomainController
        IsTerminalServer                      = $isTerminalServer
        IsWorkstationEnterpriseMultiSessionOS = $isEnterpriseMultiSession
    }

    Write-vSEALLog "OS detected: $($result.Name) ($($result.Version))" -Level VERBOSE

    return $result
}
