dist/temp/WindowsUpdateTools/Private/Get-WUWindows11ISO-Original-Backup.ps1

function Get-WUWindows11ISO {
    <#
    .SYNOPSIS
        Downloads Windows 11 ISO using multiple methods with fallback options for upgrade installations.
 
    .DESCRIPTION
        Downloads Windows 11 ISO using multiple methods: Fido script (primary), UUP dump (fallback),
        and Media Creation Tool (last resort). Automatically detects the system language and downloads
        the appropriate localized ISO. If Fido fails due to Microsoft server restrictions, automatically
        tries alternative methods.
 
    .PARAMETER OutputPath
        Directory where the ISO will be downloaded. Default: C:\Temp
 
    .PARAMETER Edition
        Windows 11 edition to download. Default: Pro
 
    .PARAMETER Language
        Override automatic language detection with a specific language.
        If not specified, the system's current display language will be detected automatically.
 
    .PARAMETER Method
        Preferred download method. Options: Auto (tries all methods), Fido, UUP, MediaCreationTool
        Default: Auto
 
    .PARAMETER LogPath
        Path to the log file for detailed logging.
 
    .EXAMPLE
        $isoPath = Get-WUWindows11ISO -OutputPath "D:\ISOs" -LogPath "C:\Logs\wu.log"
 
    .EXAMPLE
        $isoPath = Get-WUWindows11ISO -OutputPath "D:\ISOs" -Edition "Pro" -Language "German" -Method "UUP" -LogPath "C:\Logs\wu.log"
 
    .NOTES
        This is a private function used internally by the WindowsUpdateTools module.
        Requires internet connectivity and adequate disk space (8GB+ for ISO).
        Returns the full path to the downloaded ISO file.
        Supports automatic language detection and multiple download methods for reliability.
    #>


    [CmdletBinding()]
    param(
        [string]$OutputPath = "C:\Temp",
        
        [ValidateSet('Home', 'Pro', 'Enterprise', 'Education')]
        [string]$Edition = "Pro",
        
        [ValidateSet('Arabic', 'Brazilian Portuguese', 'Bulgarian', 'Chinese (Simplified)', 'Chinese (Traditional)', 
                     'Croatian', 'Czech', 'Danish', 'Dutch', 'English', 'English International', 'Estonian', 
                     'Finnish', 'French', 'French Canadian', 'German', 'Greek', 'Hebrew', 'Hungarian', 'Italian', 
                     'Japanese', 'Korean', 'Latvian', 'Lithuanian', 'Norwegian', 'Polish', 'Portuguese', 'Romanian', 
                     'Russian', 'Serbian Latin', 'Slovak', 'Slovenian', 'Spanish', 'Spanish (Mexico)', 'Swedish', 
                     'Thai', 'Turkish', 'Ukrainian')]
        [string]$Language,
        
        [ValidateSet('Auto', 'Fido', 'UUP', 'MediaCreationTool')]
        [string]$Method = "Auto",
        
        [string]$LogPath
    )
    
    # Helper function to detect and map system language to Fido language parameter
    function Get-SystemLanguageForFido {
        param([string]$LogPath)
        
        try {
            # Get the current system display language
            $systemLanguage = (Get-WinSystemLocale).DisplayName
            $cultureInfo = Get-Culture
            $cultureName = $cultureInfo.Name
            $displayName = $cultureInfo.DisplayName
            
            Write-WULog -Message "Detecting system language..." -LogPath $LogPath
            Write-WULog -Message "System Locale: $systemLanguage" -LogPath $LogPath
            Write-WULog -Message "Culture Name: $cultureName" -LogPath $LogPath
            Write-WULog -Message "Display Name: $displayName" -LogPath $LogPath
            
            # Language mapping table for Fido parameters
            $languageMap = @{
                'ar'    = 'Arabic'
                'ar-SA' = 'Arabic'
                'pt-BR' = 'Brazilian Portuguese'
                'bg'    = 'Bulgarian'
                'bg-BG' = 'Bulgarian'
                'zh-CN' = 'Chinese (Simplified)'
                'zh-Hans' = 'Chinese (Simplified)'
                'zh-TW' = 'Chinese (Traditional)'
                'zh-Hant' = 'Chinese (Traditional)'
                'hr'    = 'Croatian'
                'hr-HR' = 'Croatian'
                'cs'    = 'Czech'
                'cs-CZ' = 'Czech'
                'da'    = 'Danish'
                'da-DK' = 'Danish'
                'nl'    = 'Dutch'
                'nl-NL' = 'Dutch'
                'en-US' = 'English'
                'en-GB' = 'English International'
                'en-AU' = 'English International'
                'en-CA' = 'English International'
                'en'    = 'English'
                'et'    = 'Estonian'
                'et-EE' = 'Estonian'
                'fi'    = 'Finnish'
                'fi-FI' = 'Finnish'
                'fr-FR' = 'French'
                'fr'    = 'French'
                'fr-CA' = 'French Canadian'
                'de'    = 'German'
                'de-DE' = 'German'
                'el'    = 'Greek'
                'el-GR' = 'Greek'
                'he'    = 'Hebrew'
                'he-IL' = 'Hebrew'
                'hu'    = 'Hungarian'
                'hu-HU' = 'Hungarian'
                'it'    = 'Italian'
                'it-IT' = 'Italian'
                'ja'    = 'Japanese'
                'ja-JP' = 'Japanese'
                'ko'    = 'Korean'
                'ko-KR' = 'Korean'
                'lv'    = 'Latvian'
                'lv-LV' = 'Latvian'
                'lt'    = 'Lithuanian'
                'lt-LT' = 'Lithuanian'
                'nb'    = 'Norwegian'
                'nb-NO' = 'Norwegian'
                'no'    = 'Norwegian'
                'pl'    = 'Polish'
                'pl-PL' = 'Polish'
                'pt-PT' = 'Portuguese'
                'pt'    = 'Portuguese'
                'ro'    = 'Romanian'
                'ro-RO' = 'Romanian'
                'ru'    = 'Russian'
                'ru-RU' = 'Russian'
                'sr-Latn' = 'Serbian Latin'
                'sr'    = 'Serbian Latin'
                'sk'    = 'Slovak'
                'sk-SK' = 'Slovak'
                'sl'    = 'Slovenian'
                'sl-SI' = 'Slovenian'
                'es-ES' = 'Spanish'
                'es'    = 'Spanish'
                'es-MX' = 'Spanish (Mexico)'
                'sv'    = 'Swedish'
                'sv-SE' = 'Swedish'
                'th'    = 'Thai'
                'th-TH' = 'Thai'
                'tr'    = 'Turkish'
                'tr-TR' = 'Turkish'
                'uk'    = 'Ukrainian'
                'uk-UA' = 'Ukrainian'
            }
            
            # Try to map the culture name first (most specific)
            if ($languageMap.ContainsKey($cultureName)) {
                $detectedLanguage = $languageMap[$cultureName]
                Write-WULog -Message "Language mapped from culture name '$cultureName' to '$detectedLanguage'" -LogPath $LogPath
                return $detectedLanguage
            }
            
            # Try to map the language part only (e.g., 'en' from 'en-US')
            $languageCode = $cultureName.Split('-')[0]
            if ($languageMap.ContainsKey($languageCode)) {
                $detectedLanguage = $languageMap[$languageCode]
                Write-WULog -Message "Language mapped from language code '$languageCode' to '$detectedLanguage'" -LogPath $LogPath
                return $detectedLanguage
            }
            
            # Default to English if no mapping found
            Write-WULog -Message "No language mapping found for '$cultureName', defaulting to English" -Level Warning -LogPath $LogPath
            return 'English'
        }
        catch {
            Write-WULog -Message "Error detecting system language: $($_.Exception.Message), defaulting to English" -Level Warning -LogPath $LogPath
            return 'English'
        }
    }
    
    # Download method 1: UUP Dump (practical manual approach)
    function Get-Windows11UsingUUP {
        param(
            [string]$OutputPath,
            [string]$Edition,
            [string]$Language,
            [string]$LogPath
        )
        
        Write-WULog -Message "Setting up UUP dump download method..." -LogPath $LogPath
        
        try {
            # Create comprehensive UUP dump helper
            $uupHelper = @"
@echo off
title UUP Dump Windows 11 Download
echo ============================================================
echo UUP Dump Windows 11 ISO Download
echo ============================================================
echo.
echo UUP Dump downloads Windows 11 directly from Microsoft Update servers
echo and converts the files to a bootable ISO. This bypasses most restrictions.
echo.
echo Steps:
echo 1. Opening UUP Dump website...
echo 2. Search for "Windows 11 24H2" or latest version
echo 3. Select your language: $Language
echo 4. Select your edition: $Edition
echo 5. Download the conversion script package
echo 6. Extract and run the conversion script to create ISO
echo.
echo Press any key to open UUP Dump website...
pause > nul
 
echo Opening UUP Dump...
start "" "https://uupdump.net/"
 
echo.
echo UUP Dump website opened. Follow the steps above to download Windows 11.
echo The resulting ISO will be created in the download folder.
echo.
pause
"@

            
            $helperPath = Join-Path $OutputPath "Download_Windows11_UUP.bat"
            $uupHelper | Out-File -FilePath $helperPath -Encoding ASCII
            
            Write-WULog -Message "Created UUP dump helper script: $helperPath" -LogPath $LogPath
            Write-WULog -Message "UUP dump provides Windows 11 builds directly from Microsoft Update servers" -LogPath $LogPath
            
            return $helperPath
        }
        catch {
            Write-WULog -Message "UUP helper creation failed: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
            return $null
        }
    }
    
    # Download method 2: Guided Media Creation Tool process with real-time monitoring
    function Get-Windows11UsingMediaCreationTool {
        param(
            [string]$OutputPath,
            [string]$Edition,
            [string]$Language,
            [string]$LogPath
        )
        
        Write-WULog -Message "Starting guided Windows 11 ISO download using Media Creation Tool..." -LogPath $LogPath
        
        try {
            # Download Media Creation Tool
            $mctUrl = "https://go.microsoft.com/fwlink/?linkid=2156295"
            $mctPath = Join-Path $OutputPath "MediaCreationToolW11.exe"
            
            Write-WULog -Message "Downloading Windows 11 Media Creation Tool..." -LogPath $LogPath
            [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
            
            $webClient = New-Object System.Net.WebClient
            try {
                $webClient.DownloadFile($mctUrl, $mctPath)
                Write-WULog -Message "Media Creation Tool downloaded to: $mctPath" -LogPath $LogPath
            }
            finally {
                $webClient.Dispose()
            }
            
            # Create comprehensive guidance script
            $guidanceScript = @"
@echo off
title Windows 11 ISO Download - Media Creation Tool Guide
color 0B
echo =========================================================================
echo WINDOWS 11 MEDIA CREATION TOOL GUIDE
echo =========================================================================
echo.
echo IMPORTANT: Microsoft requires manual interaction for ISO downloads.
echo This guide will help you complete the process efficiently.
echo.
echo =========================================================================
echo STEP 1: LAUNCH MEDIA CREATION TOOL
echo =========================================================================
echo.
echo The Media Creation Tool will now launch.
echo.
echo =========================================================================
echo STEP 2: FOLLOW THESE SELECTIONS
echo =========================================================================
echo.
echo 1. Click "Accept" on the license terms
echo 2. Select "Create installation media (USB flash drive, DVD, or ISO file)"
echo 3. Click "Next"
echo 4. Choose your preferred settings:
echo - Language: $Language
echo - Edition: Windows 11 $Edition
echo - Architecture: 64-bit (x64)
echo 5. Click "Next"
echo 6. Select "ISO file"
echo 7. Click "Next"
echo 8. Choose save location: $OutputPath
echo 9. Let the download complete (this takes 15-30 minutes)
echo.
echo =========================================================================
echo STEP 3: MONITOR PROGRESS
echo =========================================================================
echo.
echo - Download progress will be shown in the Media Creation Tool
echo - The ISO file will be saved to: $OutputPath
echo - File size will be approximately 5-6 GB
echo - Do not close this window - it will monitor for completion
echo.
echo =========================================================================
echo Starting Media Creation Tool now...
echo =========================================================================
echo.
pause
 
rem Launch Media Creation Tool
start "" "$mctPath"
 
echo.
echo =========================================================================
echo MONITORING FOR ISO COMPLETION...
echo =========================================================================
echo.
echo Checking for ISO files every 30 seconds...
echo Press Ctrl+C to stop monitoring
echo.
 
:monitor_loop
timeout /t 30 /nobreak > nul
if exist "$OutputPath\*.iso" (
    echo.
    echo =========================================================================
    echo SUCCESS: ISO FILE DETECTED!
    echo =========================================================================
    echo.
    for %%f in ("$OutputPath\*.iso") do (
        echo File: %%f
        echo Size: %%~zf bytes
        echo Created: %%~tf
    )
    echo.
    echo Your Windows 11 ISO is ready!
    echo.
    goto :end
)
 
echo Still waiting... ^(checking every 30 seconds^)
goto :monitor_loop
 
:end
echo.
echo Press any key to exit...
pause > nul
"@

            
            $guidanceScriptPath = Join-Path $OutputPath "Windows11_ISO_Guide.bat"
            $guidanceScript | Out-File -FilePath $guidanceScriptPath -Encoding ASCII
            
            Write-WULog -Message "Created guided download script: $guidanceScriptPath" -LogPath $LogPath
            Write-WULog -Message "Starting guided process..." -LogPath $LogPath
            
            # Start the guidance script which will handle the process
            $guidanceProcess = Start-Process -FilePath $guidanceScriptPath -PassThru
            
            Write-WULog -Message "Guidance script launched (PID: $($guidanceProcess.Id))" -LogPath $LogPath
            Write-WULog -Message "Please follow the on-screen instructions to complete the ISO download" -LogPath $LogPath
            
            # Monitor for completion while the guidance script runs
            $startTime = Get-Date
            $maxWaitMinutes = 60  # Maximum wait time
            $endTime = $startTime.AddMinutes($maxWaitMinutes)
            
            while ((Get-Date) -lt $endTime -and -not $guidanceProcess.HasExited) {
                Start-Sleep -Seconds 30
                
                # Check for ISO files
                $isoFiles = Get-ChildItem -Path $OutputPath -Filter "*.iso" -ErrorAction SilentlyContinue | 
                           Where-Object { 
                               $_.LastWriteTime -gt $startTime -and
                               $_.Length -gt 3GB  # Reasonable minimum size for Windows 11 ISO
                           }
                
                if ($isoFiles) {
                    $isoFile = $isoFiles | Sort-Object LastWriteTime -Descending | Select-Object -First 1
                    
                    $fileSizeGB = [math]::Round($isoFile.Length / 1GB, 2)
                    Write-WULog -Message "ISO download completed successfully: $($isoFile.Name)" -LogPath $LogPath
                    Write-WULog -Message "ISO size: $fileSizeGB GB" -LogPath $LogPath
                    Write-WULog -Message "ISO path: $($isoFile.FullName)" -LogPath $LogPath
                    
                    # Try to close the guidance script
                    try { $guidanceProcess.Kill() } catch {}
                    
                    return $isoFile.FullName
                }
                
                $elapsed = (Get-Date) - $startTime
                Write-WULog -Message "Waiting for ISO completion... (Elapsed: $([math]::Round($elapsed.TotalMinutes, 1)) minutes)" -LogPath $LogPath
            }
            
            # Process completed or timed out
            if ($guidanceProcess.HasExited) {
                Write-WULog -Message "Guidance process completed" -LogPath $LogPath
            } else {
                Write-WULog -Message "Process monitoring timed out" -Level Warning -LogPath $LogPath
                try { $guidanceProcess.Kill() } catch {}
            }
            
            # Final check for ISO files
            $finalIsoFiles = Get-ChildItem -Path $OutputPath -Filter "*.iso" -ErrorAction SilentlyContinue | 
                            Where-Object { $_.LastWriteTime -gt $startTime }
            
            if ($finalIsoFiles) {
                $isoFile = $finalIsoFiles | Sort-Object LastWriteTime -Descending | Select-Object -First 1
                $fileSizeGB = [math]::Round($isoFile.Length / 1GB, 2)
                Write-WULog -Message "ISO found after process completion: $($isoFile.Name) ($fileSizeGB GB)" -LogPath $LogPath
                return $isoFile.FullName
            } else {
                Write-WULog -Message "No ISO file was created during the guided process" -Level Warning -LogPath $LogPath
                
                # Create a status report
                $statusReport = @"
@echo off
title Media Creation Tool Status
echo =========================================================================
echo DOWNLOAD STATUS REPORT
echo =========================================================================
echo.
echo Process Summary:
echo Started: $startTime
echo Duration: $([math]::Round(((Get-Date) - $startTime).TotalMinutes, 1)) minutes
echo Status: No ISO file detected
echo.
echo Possible reasons:
echo 1. Download was cancelled or interrupted
echo 2. ISO was saved to a different location
echo 3. Network issues during download
echo 4. Insufficient disk space
echo.
echo Please check these locations manually:
echo - Downloads folder: %USERPROFILE%\Downloads
echo - Desktop: %USERPROFILE%\Desktop
echo - Output folder: $OutputPath
echo.
echo If you find the ISO file, please move it to:
echo $OutputPath
echo.
echo Press any key to open the output folder...
pause > nul
explorer.exe "$OutputPath"
"@

                
                $statusPath = Join-Path $OutputPath "Download_Status_Report.bat"
                $statusReport | Out-File -FilePath $statusPath -Encoding ASCII
                
                Write-WULog -Message "Created status report: $statusPath" -LogPath $LogPath
                return $statusPath
            }
        }
        catch {
            Write-WULog -Message "Guided Media Creation Tool process failed: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
            return $null
        }
    }
    
    # Download method 3: Practical alternatives when all else fails
    function Get-Windows11UsingDirectAPI {
        param(
            [string]$OutputPath,
            [string]$Edition,
            [string]$Language,
            [string]$LogPath
        )
        
        Write-WULog -Message "Creating practical alternative download methods..." -LogPath $LogPath
        
        try {
            # Create comprehensive alternatives script
            $alternativesScript = @"
@echo off
title Windows 11 Download Alternatives
color 0A
echo =========================================================================
echo WINDOWS 11 ISO DOWNLOAD ALTERNATIVES
echo =========================================================================
echo.
echo Microsoft has restricted automated downloads. Here are proven alternatives:
echo.
echo =========================================================================
echo METHOD 1: RUFUS (HIGHLY RECOMMENDED - BYPASSES ALL RESTRICTIONS)
echo =========================================================================
echo 1. Download Rufus from: https://rufus.ie/
echo 2. Run Rufus, click dropdown arrow next to 'SELECT'
echo 3. Choose 'DOWNLOAD'
echo 4. Select Windows 11, $Language, $Edition
echo 5. Rufus downloads directly from Microsoft, bypassing restrictions
echo.
echo Opening Rufus website...
start "" "https://rufus.ie/"
timeout /t 3 /nobreak > nul
echo.
echo =========================================================================
echo METHOD 2: MICROSOFT OFFICIAL (MAY REQUIRE MOBILE USER AGENT)
echo =========================================================================
echo Visit: https://www.microsoft.com/software-download/windows11
echo - Use Edge or Chrome with mobile device emulation if restricted
echo - F12 Developer Tools ^> Device Toolbar ^> iPhone/Android
echo.
echo Opening Microsoft Download page...
start "" "https://www.microsoft.com/software-download/windows11"
timeout /t 3 /nobreak > nul
echo.
echo =========================================================================
echo METHOD 3: TECHBENCH (DIRECT MICROSOFT LINKS)
echo =========================================================================
echo Visit: https://tb.rg-adguard.net/public.php
echo - Select Windows 11, $Edition, $Language, x64
echo - Get direct Microsoft download links
echo.
echo Opening TechBench...
start "" "https://tb.rg-adguard.net/public.php"
timeout /t 3 /nobreak > nul
echo.
echo =========================================================================
echo METHOD 4: UUP DUMP (MICROSOFT UPDATE PACKAGES)
echo =========================================================================
echo Visit: https://uupdump.net/
echo - Search 'Windows 11 24H2'
echo - Select language and edition
echo - Download UUP conversion package
echo.
echo Opening UUP Dump...
start "" "https://uupdump.net/"
echo.
echo =========================================================================
echo All websites opened. Use any method above to download Windows 11 ISO.
echo Rufus is recommended as it bypasses most restrictions automatically.
echo =========================================================================
pause
"@

            
            $scriptPath = Join-Path $OutputPath "Windows11_Download_Alternatives.bat"
            $alternativesScript | Out-File -FilePath $scriptPath -Encoding ASCII
            
            # Also create a quick Rufus info file
            $rufusInfo = @"
RUFUS - RECOMMENDED SOLUTION FOR WINDOWS 11 ISO DOWNLOAD
 
What is Rufus?
- Free, open-source USB creation tool
- Built-in download feature for Windows ISOs
- Bypasses Microsoft's IP/region restrictions
- Downloads directly from Microsoft servers
 
How to use:
1. Download Rufus from https://rufus.ie/
2. Run Rufus.exe
3. Click the dropdown arrow next to 'SELECT' button
4. Choose 'DOWNLOAD' from the dropdown
5. Select 'Windows 11'
6. Choose your language ($Language) and edition ($Edition)
7. Select architecture (x64)
8. Choose download location
9. Rufus will download the ISO directly from Microsoft
 
Why it works:
- Rufus uses different API endpoints than Fido
- Has user-agent rotation and retry logic
- Maintained actively with Microsoft restriction workarounds
- Trusted by millions of users worldwide
 
File will be saved as: Win11_[version]_[language]_x64.iso
Size: Approximately 5GB
"@

            
            $infoPath = Join-Path $OutputPath "RUFUS_SOLUTION.txt"
            $rufusInfo | Out-File -FilePath $infoPath -Encoding UTF8
            
            Write-WULog -Message "Created comprehensive alternatives script: $scriptPath" -LogPath $LogPath
            Write-WULog -Message "Created Rufus solution guide: $infoPath" -LogPath $LogPath
            Write-WULog -Message "Multiple alternative download methods prepared" -LogPath $LogPath
            
            return $scriptPath
        }
        catch {
            Write-WULog -Message "Alternatives script creation failed: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
            return $null
        }
    }
    
    # Main Fido download method (existing implementation)
    function Get-Windows11UsingFido {
        param(
            [string]$OutputPath,
            [string]$Edition,
            [string]$Language,
            [string]$LogPath
        )
        
        Write-WULog -Message "Attempting Windows 11 ISO download using Fido..." -LogPath $LogPath
        
        try {
            # Download Fido script if not already present
            $fidoPath = Join-Path $OutputPath "Fido.ps1"
            
            if (-not (Test-Path $fidoPath)) {
                Write-WULog -Message "Downloading Fido script..." -LogPath $LogPath
                
                # Set up TLS 1.2 for download
                [Net.ServicePointManager]::SecurityProtocol = [Enum]::ToObject([Net.SecurityProtocolType], 3072)
                
                $fidoUrl = "https://github.com/pbatard/Fido/raw/master/Fido.ps1"
                $webClient = New-Object System.Net.WebClient
                
                try {
                    $webClient.DownloadFile($fidoUrl, $fidoPath)
                    Write-WULog -Message "Fido script downloaded successfully" -LogPath $LogPath
                }
                catch {
                    Write-WULog -Message "Failed to download Fido script: $($_.Exception.Message)" -Level Error -LogPath $LogPath
                    throw "Failed to download Fido script: $($_.Exception.Message)"
                }
                finally {
                    $webClient.Dispose()
                }
            } else {
                Write-WULog -Message "Fido script already exists at: $fidoPath" -LogPath $LogPath
            }
            
            # Check for existing ISO files and clean up if needed
            $existingIsos = Get-ChildItem -Path $OutputPath -Filter "*.iso" -ErrorAction SilentlyContinue
            if ($existingIsos) {
                Write-WULog -Message "Found $($existingIsos.Count) existing ISO file(s), removing to avoid conflicts..." -LogPath $LogPath
                foreach ($iso in $existingIsos) {
                    Remove-Item -Path $iso.FullName -Force -ErrorAction SilentlyContinue
                    Write-WULog -Message "Removed existing ISO: $($iso.Name)" -LogPath $LogPath
                }
            }
            
            # Execute Fido to download Windows 11 ISO
            Write-WULog -Message "Executing Fido to download Windows 11 24H2 $Edition ISO in $Language..." -LogPath $LogPath
            Write-WULog -Message "This may take several minutes depending on internet speed..." -LogPath $LogPath
            
            # Store current location and change to temp directory (ChrisTitusTech approach)
            $originalLocation = Get-Location
            Set-Location -Path $env:temp
            
            try {
                # Build Fido command parameters - Fido downloads to current directory by default
                $commandArgs = "-Win `"Windows 11`" -Rel `"Latest`" -Ed `"$Edition`" -Lang `"$Language`" -Arch `"x64`""
                
                Write-WULog -Message "Fido command (using Latest release): & '$fidoPath' $commandArgs" -LogPath $LogPath
                Write-WULog -Message "Fido will download to: $env:temp" -LogPath $LogPath
                
                # Execute Fido with proper error handling using Invoke-Expression
                try {
                    $fidoResult = Invoke-Expression "& '$fidoPath' $commandArgs" 2>&1
                }
                catch {
                    Write-WULog -Message "Exception during Fido execution: $($_.Exception.Message)" -Level Error -LogPath $LogPath
                    throw "Exception during Fido execution: $($_.Exception.Message)"
                }
                
                if ($LASTEXITCODE -ne 0) {
                    $fidoOutput = $fidoResult -join "`n"
                    Write-WULog -Message "Fido execution failed with exit code: $LASTEXITCODE" -Level Error -LogPath $LogPath
                    Write-WULog -Message "Fido output: $fidoOutput" -Level Error -LogPath $LogPath
                    
                    # Check for specific Microsoft server restrictions
                    if ($fidoOutput -match "715-123130" -or $fidoOutput -match "banned from using this service") {
                        $errorMsg = "Microsoft has temporarily restricted ISO downloads from your IP address or region. "
                        $errorMsg += "This is a server-side restriction by Microsoft (Error 715-123130). "
                        $errorMsg += "Will try alternative download methods."
                        Write-WULog -Message $errorMsg -Level Warning -LogPath $LogPath
                        throw $errorMsg
                    }
                    
                    throw "Fido execution failed with exit code: $LASTEXITCODE. Output: $fidoOutput"
                }
                
                Write-WULog -Message "Fido execution completed successfully" -LogPath $LogPath
                
                # Find the downloaded ISO file using ChrisTitusTech approach
                # Look for Win11*.iso pattern in temp directory and get the most recent
                Start-Sleep -Seconds 3  # Give file system time to update
                
                Write-WULog -Message "Searching for downloaded ISO in $env:temp..." -LogPath $LogPath
                $isoFile = Get-ChildItem -Path $env:temp -Filter "Win11*.iso" -ErrorAction SilentlyContinue | 
                           Sort-Object LastWriteTime -Descending | 
                           Select-Object -First 1
                
                if ($isoFile) {
                    $fileSizeGB = [math]::Round($isoFile.Length / 1GB, 2)
                    Write-WULog -Message "ISO download successful: $($isoFile.Name)" -LogPath $LogPath
                    Write-WULog -Message "ISO size: $fileSizeGB GB" -LogPath $LogPath
                    Write-WULog -Message "ISO found at: $($isoFile.FullName)" -LogPath $LogPath
                    
                    # Move ISO to the requested output path if different from temp
                    if ($OutputPath -ne $env:temp -and (Test-Path $OutputPath)) {
                        $destinationPath = Join-Path $OutputPath $isoFile.Name
                        Write-WULog -Message "Moving ISO to requested location: $destinationPath" -LogPath $LogPath
                        
                        try {
                            Move-Item -Path $isoFile.FullName -Destination $destinationPath -Force
                            Write-WULog -Message "ISO moved successfully to: $destinationPath" -LogPath $LogPath
                            return $destinationPath
                        }
                        catch {
                            Write-WULog -Message "Failed to move ISO to $OutputPath`: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
                            Write-WULog -Message "ISO remains at: $($isoFile.FullName)" -LogPath $LogPath
                            return $isoFile.FullName
                        }
                    } else {
                        return $isoFile.FullName
                    }
                } else {
                    # Additional diagnostic information
                    Write-WULog -Message "No Win11*.iso file found in $env:temp" -Level Error -LogPath $LogPath
                    $allIsos = Get-ChildItem -Path $env:temp -Filter "*.iso" -ErrorAction SilentlyContinue
                    if ($allIsos) {
                        Write-WULog -Message "Found other ISO files in temp: $($allIsos.Name -join ', ')" -LogPath $LogPath
                    } else {
                        Write-WULog -Message "No ISO files found at all in $env:temp" -Level Error -LogPath $LogPath
                    }
                    throw "No ISO file found after download attempt"
                }
            }
            finally {
                # Always restore the original location
                Set-Location -Path $originalLocation
            }
        }
        catch {
            Write-WULog -Message "Fido method failed: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
            throw
        }
    }
    
    Write-WULog -Message "Starting Windows 11 ISO download" -LogPath $LogPath
    Write-WULog -Message "Edition: $Edition" -LogPath $LogPath
    Write-WULog -Message "Method: $Method" -LogPath $LogPath
    
    # Validate and fix output path
    try {
        # Check if the drive exists
        $drive = Split-Path -Path $OutputPath -Qualifier
        if ($drive -and -not (Get-PSDrive -Name $drive.TrimEnd(':') -ErrorAction SilentlyContinue)) {
            Write-WULog -Message "Drive $drive does not exist, falling back to C:\Temp\WindowsISOs" -Level Warning -LogPath $LogPath
            $OutputPath = "C:\Temp\WindowsISOs"
        }
        
        # Ensure the path is valid and accessible
        if (-not (Test-Path $OutputPath -IsValid)) {
            Write-WULog -Message "Invalid output path specified, using C:\Temp\WindowsISOs" -Level Warning -LogPath $LogPath
            $OutputPath = "C:\Temp\WindowsISOs"
        }
        
        Write-WULog -Message "Output Path: $OutputPath" -LogPath $LogPath
    }
    catch {
        Write-WULog -Message "Error validating output path: $($_.Exception.Message), using C:\Temp\WindowsISOs" -Level Warning -LogPath $LogPath
        $OutputPath = "C:\Temp\WindowsISOs"
    }
    
    # Determine the language to use
    if (-not $Language) {
        $Language = Get-SystemLanguageForFido -LogPath $LogPath
        Write-WULog -Message "Auto-detected language: $Language" -LogPath $LogPath
    } else {
        Write-WULog -Message "Using specified language: $Language" -LogPath $LogPath
    }
    
    try {
        # Ensure output directory exists
        if (-not (Test-Path $OutputPath)) {
            Write-WULog -Message "Creating output directory: $OutputPath" -LogPath $LogPath
            New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
        }
        
        $result = $null
        
        # Try download methods based on preference
        if ($Method -eq "Auto") {
            Write-WULog -Message "Auto mode: Trying multiple download methods..." -LogPath $LogPath
            
            # Method 1: Try automated Media Creation Tool first (most reliable and automated)
            Write-WULog -Message "Trying method 1: Automated Media Creation Tool..." -LogPath $LogPath
            try {
                $result = Get-Windows11UsingMediaCreationTool -OutputPath $OutputPath -Edition $Edition -Language $Language -LogPath $LogPath
            }
            catch {
                Write-WULog -Message "Automated MCT method failed: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
                $result = $null
            }
            
            # Method 2: Try Fido if automated MCT failed
            if (-not $result -or -not $result.EndsWith('.iso')) {
                Write-WULog -Message "Trying method 2: Fido script..." -LogPath $LogPath
                try {
                    $result = Get-Windows11UsingFido -OutputPath $OutputPath -Edition $Edition -Language $Language -LogPath $LogPath
                }
                catch {
                    Write-WULog -Message "Fido method failed: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
                    $result = $null
                }
            }
            
            # Method 3: Try UUP dump if others failed
            if (-not $result) {
                Write-WULog -Message "Trying method 3: UUP dump..." -LogPath $LogPath
                try {
                    $result = Get-Windows11UsingUUP -OutputPath $OutputPath -Edition $Edition -Language $Language -LogPath $LogPath
                }
                catch {
                    Write-WULog -Message "UUP method failed: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
                    $result = $null
                }
            }
            
            # Method 4: Final fallback - create comprehensive helper script
            if (-not $result) {
                Write-WULog -Message "All automated methods failed, creating comprehensive helper script..." -LogPath $LogPath
                try {
                    $result = Get-Windows11UsingDirectAPI -OutputPath $OutputPath -Edition $Edition -Language $Language -LogPath $LogPath
                }
                catch {
                    Write-WULog -Message "Fallback helper creation failed: $($_.Exception.Message)" -Level Warning -LogPath $LogPath
                    $result = $null
                }
            }
        }
        elseif ($Method -eq "Fido") {
            $result = Get-Windows11UsingFido -OutputPath $OutputPath -Edition $Edition -Language $Language -LogPath $LogPath
        }
        elseif ($Method -eq "UUP") {
            $result = Get-Windows11UsingUUP -OutputPath $OutputPath -Edition $Edition -Language $Language -LogPath $LogPath
        }
        elseif ($Method -eq "MediaCreationTool") {
            $result = Get-Windows11UsingMediaCreationTool -OutputPath $OutputPath -Edition $Edition -Language $Language -LogPath $LogPath
        }
        
        if ($result) {
            if ($result.EndsWith(".iso")) {
                Write-WULog -Message "ISO download completed successfully: $result" -LogPath $LogPath
            } else {
                Write-WULog -Message "Alternative download method prepared: $result" -LogPath $LogPath
            }
            return $result
        } else {
            $errorMsg = "All download methods failed. Please try one of these alternatives:`n"
            $errorMsg += "1. Download Windows 11 manually from: https://www.microsoft.com/software-download/windows11`n"
            $errorMsg += "2. Use Rufus (https://rufus.ie/) with its built-in download feature`n"
            $errorMsg += "3. Check UUPdump.net for alternative Windows 11 builds`n"
            $errorMsg += "4. Try again later if Microsoft servers are temporarily restricting downloads"
            
            Write-WULog -Message $errorMsg -Level Error -LogPath $LogPath
            throw $errorMsg
        }
    }
    catch {
        Write-WULog -Message "Error during ISO download: $($_.Exception.Message)" -Level Error -LogPath $LogPath
        throw
    }
}