dist/temp/WindowsUpdateTools/Private/Format-WUResult.ps1

function Format-WUResult {
    <#
    .SYNOPSIS
        Formats Windows Update results with smart remediation analysis.
 
    .DESCRIPTION
        Displays comprehensive Windows Update results including success/failure details,
        error analysis, and smart remediation recommendations with automatic fixes for safe operations.
 
    .PARAMETER Result
        The Windows Update result object to format.
 
    .EXAMPLE
        Format-WUResult -Result $updateResult
        Displays formatted results with smart remediation analysis.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [hashtable]$Result
    )

    $separator = "-" * 60
    
    # Header
    Write-Host "`n$separator" -ForegroundColor White
    Write-Host " Windows Update Results Summary" -ForegroundColor White
    Write-Host $separator -ForegroundColor White

    # Basic Statistics
    Write-Host " Updates Found: $($Result.UpdatesToInstall.Count)" -ForegroundColor Cyan
    Write-Host " Downloads: $($Result.UpdatesDownloaded)" -ForegroundColor Cyan
    Write-Host " Installations: $($Result.UpdatesInstalled)" -ForegroundColor Cyan
    Write-Host " Failed: $($Result.FailedUpdates.Count)" -ForegroundColor $(if ($Result.FailedUpdates.Count -gt 0) { 'Red' } else { 'Green' })
    Write-Host " Duration: $($Result.Duration)" -ForegroundColor Cyan

    # Success/Failure Status
    if ($Result.Success) {
        Write-Host " Status: SUCCESS" -ForegroundColor Green
    } else {
        Write-Host " Status: FAILED" -ForegroundColor Red
    }

    # Show successful installations
    if ($Result.InstalledUpdates.Count -gt 0) {
        Write-Host "`n Successful Installations:" -ForegroundColor Green
        $Result.InstalledUpdates | ForEach-Object {
            Write-Host " [OK] $($_.Title)" -ForegroundColor Green
        }
    }

    # Show failed installations with error details
    if ($Result.FailedUpdates.Count -gt 0) {
        Write-Host "`n Failed Installations:" -ForegroundColor Red
        $Result.FailedUpdates | ForEach-Object {
            $errorDescription = Get-WUHResultDescription -HResult $_.HResult
            Write-Host " [ERROR] $($_.Title)" -ForegroundColor Red
            Write-Host " Reason: $errorDescription" -ForegroundColor Yellow
        }
    }

    # Show general errors
    if ($Result.Errors.Count -gt 0) {
        Write-Host "`n General Errors:" -ForegroundColor Red
        $Result.Errors | ForEach-Object {
            if ($_.HResult) {
                $errorDescription = Get-WUHResultDescription -HResult $_.HResult
            } else {
                $errorDescription = "Unknown error (no error code provided)"
            }
            Write-Host " [ERROR] $($_.Title)" -ForegroundColor Red
            Write-Host " Reason: $errorDescription" -ForegroundColor Yellow
        }
    }

    # Smart Remediation Analysis
    $analysisSeparator = "-" * 20 + " Smart Remediation " + "-" * 21
    Write-Host "`n$analysisSeparator" -ForegroundColor White
    if ($Result.Success) {
        if ($Result.RebootRequired) {
            Write-Host " [WARNING] REBOOT REQUIRED to complete installation" -ForegroundColor Yellow -BackgroundColor Black
            Write-Host " > Run: Restart-Computer -Force" -ForegroundColor White -BackgroundColor DarkBlue
        } else {
            Write-Host " [OK] System is up-to-date" -ForegroundColor Green
        }
    } else {
        # Analyze failure patterns and execute smart remediation
        $downloadFailure = ($Result.UpdatesToInstall.Count -gt 0) -and ($Result.UpdatesDownloaded -eq 0)
        $installFailure = ($Result.UpdatesDownloaded -gt 0) -and ($Result.FailedUpdates.Count -gt 0)
        
        Write-Host " [INFO] Analyzing failure pattern..." -ForegroundColor Cyan
        
        if ($downloadFailure) {
            Write-Host " [ERROR] DOWNLOAD FAILURE: Found $($Result.UpdatesToInstall.Count) updates, downloaded 0" -ForegroundColor Red
            
            # Auto-fix: Check and start services
            Write-Host " [AUTO-FIX] Auto-fixing services..." -ForegroundColor Yellow
            try {
                $serviceResults = Test-WUServices
                $servicesFixed = 0
                
                if ($serviceResults -and (-not $serviceResults.AllServicesRunning)) {
                    if ($serviceResults.FailedServices) {
                        $serviceResults.FailedServices | ForEach-Object {
                            try {
                                Start-Service $_.Name -ErrorAction Stop
                                Write-Host " [OK] Started service: $($_.Name)" -ForegroundColor Green
                                $servicesFixed++
                            } catch {
                                Write-Host " [ERROR] Failed to start service: $($_.Name)" -ForegroundColor Red
                            }
                        }
                    }
                }
                
                # Check network connectivity
                $internetTest = Test-NetConnection -ComputerName "windowsupdate.microsoft.com" -Port 443 -InformationLevel Quiet -ErrorAction SilentlyContinue
                
                if ($servicesFixed -gt 0) {
                    Write-Host " [SUCCESS] Fixed $servicesFixed service(s). Try running Install-WindowsUpdate again." -ForegroundColor Green
                } elseif (-not $internetTest) {
                    Write-Host " [ERROR] NETWORK ISSUE: Cannot reach Windows Update servers" -ForegroundColor Red
                    Write-Host " > Run: Repair-WindowsUpdate -Level Network" -ForegroundColor White -BackgroundColor DarkBlue
                } else {
                    Write-Host " [ERROR] DOWNLOAD CACHE ISSUE detected" -ForegroundColor Red
                    Write-Host " > Run: Repair-WindowsUpdate -Level Downloads" -ForegroundColor White -BackgroundColor DarkBlue
                }
            } catch {
                Write-Host " [ERROR] SERVICE CHECK FAILED" -ForegroundColor Red
                Write-Host " > Run: Repair-WindowsUpdate -Level Services" -ForegroundColor White -BackgroundColor DarkBlue
            }
            
        } elseif ($installFailure) {
            Write-Host " [ERROR] INSTALLATION FAILURE: Downloaded $($Result.UpdatesDownloaded), failed to install $($Result.FailedUpdates.Count)" -ForegroundColor Red
            
            # Check for immediate fixes
            $rebootPending = Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -ErrorAction SilentlyContinue
            if ($rebootPending) {
                Write-Host " [ERROR] PENDING REBOOT blocking installation" -ForegroundColor Red
                Write-Host " > Run: Restart-Computer -Force" -ForegroundColor White -BackgroundColor DarkBlue
                Write-Host " Then retry: Install-WindowsUpdate" -ForegroundColor Yellow
            } else {
                # Check component store
                try {
                    $componentResults = Test-WUComponentStore
                    if ($componentResults -and (-not $componentResults.IsHealthy)) {
                        Write-Host " [ERROR] COMPONENT STORE CORRUPTION detected" -ForegroundColor Red
                        Write-Host " > Run: Repair-WindowsUpdate -Level ComponentStore" -ForegroundColor White -BackgroundColor DarkRed
                        Write-Host " [WARNING] This repair can take 30+ minutes" -ForegroundColor Yellow
                    } else {
                        Write-Host " [ERROR] INSTALLATION BLOCK detected" -ForegroundColor Red
                        Write-Host " > Run: Repair-WindowsUpdate -Level Installation" -ForegroundColor White -BackgroundColor DarkBlue
                    }
                } catch {
                    Write-Host " [ERROR] COMPONENT STORE CHECK FAILED" -ForegroundColor Red
                    Write-Host " > Run: Repair-WindowsUpdate -Level ComponentStore" -ForegroundColor White -BackgroundColor DarkRed
                    Write-Host " [WARNING] This repair can take 30+ minutes" -ForegroundColor Yellow
                }
            }
            
        } else {
            Write-Host " [ERROR] GENERAL FAILURE detected" -ForegroundColor Red
            
            # Auto-fix: Clear temp files and reset cache
            Write-Host " [AUTO-FIX] Auto-fixing: Clearing temporary files..." -ForegroundColor Yellow
            try {
                $tempCleared = 0
                $tempFiles = Get-ChildItem "$env:TEMP" -ErrorAction SilentlyContinue | Measure-Object
                if ($tempFiles.Count -gt 0) {
                    Remove-Item "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue
                    $tempCleared = $tempFiles.Count
                    Write-Host " [OK] Cleared $tempCleared temporary files" -ForegroundColor Green
                }
            } catch {
                Write-Host " [WARNING] Could not clear all temporary files" -ForegroundColor Yellow
            }
            
            # Get overall system health for specific recommendations
            try {
                $healthStatus = Test-WUSystemHealth
                if ($healthStatus -and $healthStatus.OverallScore -lt 60) {
                    Write-Host " [ERROR] POOR SYSTEM HEALTH: $($healthStatus.OverallScore)%" -ForegroundColor Red
                    Write-Host " > Run: Repair-WindowsUpdate" -ForegroundColor White -BackgroundColor DarkRed
                    Write-Host " [WARNING] This can take 1+ hours and may require reboots" -ForegroundColor Yellow
                } else {
                    Write-Host " > Run: Repair-WindowsUpdate -Level Basic" -ForegroundColor White -BackgroundColor DarkBlue
                }
            } catch {
                Write-Host " > Run: Repair-WindowsUpdate" -ForegroundColor White -BackgroundColor DarkBlue
            }
        }
    }
    Write-Host ("-"*60)
}