scripts/modules/environment/wsl/setup-wsl-env.ps1

# strangeloop Setup - WSL Environment Setup Module
# Version: 1.0.0


param(
    [switch]$Verbose
)

# Import common functions

# Import shared modules
$SharedPath = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent | Join-Path -ChildPath "shared"
Import-Module "$SharedPath\write-functions.ps1" -Force -DisableNameChecking
Import-Module "$SharedPath\test-functions.ps1" -Force -DisableNameChecking
Import-Module "$SharedPath\path-functions.ps1" -Force -DisableNameChecking

function Initialize-WSLEnvironment {
    
    Write-Step "Setting up WSL Development Environment..."
    
    try {
        # Check if WSL is available
        Write-Progress "Checking WSL availability..."
        
        if (-not (Test-Command "wsl")) {
            Write-Error "WSL is not installed. Please install WSL first."
            return $false
        }
        
        Write-Success "WSL is available"
        
        # Check specifically for Ubuntu 24.04 distribution
        Write-Progress "Checking for Ubuntu 24.04 distribution..."
        
        $hasUbuntu2404 = $false
        $distributions = @()
        
        try {
            # Get WSL distribution list
            $wslOutput = wsl --list 2>&1
            
            # Parse the output looking specifically for Ubuntu 24.04
            foreach ($line in $wslOutput) {
                # Clean up the line - remove null chars and normalize whitespace
                $cleanLine = $line -replace '\x00', '' -replace '\s+', ' '
                $cleanLine = $cleanLine.Trim()
                
                # Skip header lines and error messages
                if ($cleanLine -and 
                    $cleanLine -notmatch "Windows Subsystem for Linux" -and
                    $cleanLine -notmatch "has no installed distributions" -and
                    $cleanLine -notmatch "You can resolve this by" -and
                    $cleanLine -notmatch "Use 'wsl.exe" -and
                    $cleanLine -notmatch "wsl.exe --install" -and
                    $cleanLine -ne "Distributions:") {
                    
                    # Remove (Default) marker and other annotations
                    $distroName = $cleanLine -replace '\s*\(Default\)', '' -replace '\s*\(default\)', ''
                    $distroName = $distroName.Trim()
                    
                    if ($distroName) {
                        $distributions += $distroName
                        
                        # Check if this is Ubuntu 24.04
                        if ($distroName -match "Ubuntu.*24\.04" -or $distroName -eq "Ubuntu-24.04") {
                            $hasUbuntu2404 = $true
                        }
                    }
                }
            }
            
            if ($distributions.Count -gt 0) {
                Write-Info "Found WSL distributions: $($distributions -join ', ')"
                if ($hasUbuntu2404) {
                    Write-Success "Ubuntu 24.04 distribution found"
                } else {
                    Write-Warning "Ubuntu 24.04 distribution not found"
                }
            } else {
                Write-Info "No WSL distributions found"
            }
        } catch {
            Write-Warning "Failed to check WSL distributions: $($_.Exception.Message)"
            $distributions = @()
            $hasUbuntu2404 = $false
        }
        
        # Install Ubuntu 24.04 if not found
        if (-not $hasUbuntu2404) {
            Write-Warning "Ubuntu 24.04 distribution not found. Installing Ubuntu 24.04..."
            
            try {
                Write-Info "Starting Ubuntu 24.04 installation..."
                Write-Info "📥 Downloading and installing Ubuntu 24.04..."
                Write-Info "💡 User setup will happen in a separate window after installation"
                Write-Host ""
                
                # Step 1: Install the distribution using a more controlled approach
                Write-Info "Step 1: Installing Ubuntu 24.04 distribution..."
                Write-Info "Executing: wsl --install -d Ubuntu-24.04 --no-launch"
                Write-Host "----------------------------------------" -ForegroundColor DarkGray
                
                # Use direct execution to show real-time output, with --no-launch to prevent inline setup
                $installProcess = Start-Process -FilePath "wsl" -ArgumentList "--install", "-d", "Ubuntu-24.04", "--no-launch" -NoNewWindow -PassThru -Wait
                $installExitCode = $installProcess.ExitCode
                
                Write-Host "----------------------------------------" -ForegroundColor DarkGray
                Write-Info "Installation completed with exit code: $installExitCode"
                
                $installResult = @{
                    Success = ($installExitCode -eq 0)
                    ExitCode = $installExitCode
                }
                
                if (-not $installResult.Success) {
                    # Fallback to generic Ubuntu if 24.04 specific version not available
                    Write-Info "Ubuntu 24.04 not available, trying latest Ubuntu..."
                    Write-Info "Executing: wsl --install -d Ubuntu --no-launch"
                    Write-Host "----------------------------------------" -ForegroundColor DarkGray
                    
                    # Use direct execution for fallback to show real-time output
                    $fallbackProcess = Start-Process -FilePath "wsl" -ArgumentList "--install", "-d", "Ubuntu", "--no-launch" -NoNewWindow -PassThru -Wait
                    $fallbackExitCode = $fallbackProcess.ExitCode
                    
                    Write-Host "----------------------------------------" -ForegroundColor DarkGray
                    Write-Info "Fallback installation completed with exit code: $fallbackExitCode"
                    
                    if ($fallbackExitCode -ne 0) {
                        Write-Error "Both Ubuntu 24.04 and Ubuntu installation failed"
                        return $false
                    }
                    
                    $targetDistroName = "Ubuntu"
                } else {
                    $targetDistroName = "Ubuntu-24.04"
                }

                Write-Success "Ubuntu distribution files installed successfully"
                
                # Step 2: Launch Ubuntu in a separate window for initial user setup
                Write-Info ""
                Write-Info "Step 2: Opening Ubuntu in a separate window for initial user setup..."
                Write-Info "🪟 A new Ubuntu terminal window will open where you need to:"
                Write-Info " • Create your username (recommend using your Windows username)"
                Write-Info " • Set a secure password"
                Write-Info " • Wait for the initial setup to complete"
                Write-Info " • Type 'exit' when done to return to this script"
                Write-Info ""
                Write-Warning "⚠️ Do NOT close this script window - it will wait for you"
                
                Start-Sleep -Seconds 3
                
                # Launch Ubuntu in a separate window using the best available method
                $launched = $false
                try {
                    # Method 1: Try Windows Terminal (best experience)
                    if (Get-Command "wt" -ErrorAction SilentlyContinue) {
                        Write-Info "Opening Ubuntu in Windows Terminal..."
                        $setupProcess = Start-Process "wt" -ArgumentList "wsl", "-d", $targetDistroName -Wait
                        $launched = $true
                    }
                } catch {
                    Write-Info "Windows Terminal not available, trying alternative..."
                }
                
                if (-not $launched) {
                    try {
                        # Method 2: Use cmd to open a new window
                        Write-Info "Opening Ubuntu in a new command window..."
                        $setupProcess = Start-Process "cmd" -ArgumentList "/c", "start", "cmd", "/k", "wsl -d $targetDistroName" -Wait
                        $launched = $true
                    } catch {
                        Write-Info "Command window approach failed, trying direct launch..."
                    }
                }
                
                if (-not $launched) {
                    # Method 3: Last resort - direct launch with warning
                    Write-Warning "Opening Ubuntu directly in this window (not ideal for user experience)..."
                    Write-Info "You'll need to complete setup here, then type 'exit' to continue"
                    & wsl -d $targetDistroName
                }
                
                Write-Success "Ubuntu user setup completed - continuing with verification..."
                
                Write-Success "Ubuntu distribution installation completed"
                
                # Re-check for distributions after installation
                Write-Info "Verifying installation..."
                Start-Sleep -Seconds 3  # Allow time for installation to settle
                
                try {
                    $wslOutput = wsl --list 2>&1
                    $newDistributions = @()
                    $foundUbuntu = $false
                    
                    foreach ($line in $wslOutput) {
                        $cleanLine = $line -replace '\x00', '' -replace '\s+', ' '
                        $cleanLine = $cleanLine.Trim()
                        
                        if ($cleanLine -and 
                            $cleanLine -notmatch "Windows Subsystem for Linux" -and
                            $cleanLine -notmatch "has no installed distributions" -and
                            $cleanLine -notmatch "You can resolve this by" -and
                            $cleanLine -notmatch "Use 'wsl.exe" -and
                            $cleanLine -notmatch "wsl.exe --install" -and
                            $cleanLine -ne "Distributions:") {
                            
                            $distroName = $cleanLine -replace '\s*\(Default\)', '' -replace '\s*\(default\)', ''
                            $distroName = $distroName.Trim()
                            
                            if ($distroName) {
                                $newDistributions += $distroName
                                if ($distroName -match "Ubuntu") {
                                    $foundUbuntu = $true
                                    $targetDistro = $distroName
                                }
                            }
                        }
                    }
                    
                    if ($foundUbuntu) {
                        Write-Success "Ubuntu installation verified: $targetDistro"
                        $distributions = $newDistributions
                        $hasUbuntu2404 = ($targetDistro -match "Ubuntu.*24\.04" -or $targetDistro -eq "Ubuntu-24.04")
                        
                        # Set the newly installed Ubuntu distribution as default
                        Write-Info "Setting $targetDistro as the default WSL distribution..."
                        try {
                            $setDefaultResult = & wsl.exe --set-default $targetDistro 2>&1
                            if ($LASTEXITCODE -eq 0) {
                                Write-Success "$targetDistro is now the default WSL distribution"
                            } else {
                                Write-Warning "Failed to set $targetDistro as default: $setDefaultResult"
                            }
                        } catch {
                            Write-Warning "Error setting $targetDistro as default: $($_.Exception.Message)"
                        }
                    } else {
                        Write-Error "Ubuntu installation could not be verified"
                        return $false
                    }
                } catch {
                    Write-Warning "Failed to verify installation: $($_.Exception.Message)"
                    return $false
                }
                
            } catch {
                Write-Error "Failed to install Ubuntu distribution: $($_.Exception.Message)"
                return $false
            }
        }
        
        # Determine which distribution to use
        $targetDistro = $null
        foreach ($distro in $distributions) {
            if ($distro -match "Ubuntu.*24\.04" -or $distro -eq "Ubuntu-24.04") {
                $targetDistro = $distro
                break
            }
        }
        
        # Fallback to any Ubuntu distribution
        if (-not $targetDistro) {
            foreach ($distro in $distributions) {
                if ($distro -match "Ubuntu") {
                    $targetDistro = $distro
                    Write-Warning "Using $targetDistro instead of Ubuntu 24.04"
                    break
                }
            }
        }
        
        # Final fallback to first available distribution
        if (-not $targetDistro -and $distributions.Count -gt 0) {
            $targetDistro = $distributions[0]
            Write-Warning "Using $targetDistro as fallback distribution"
        }
        
        if (-not $targetDistro) {
            Write-Error "No usable WSL distribution found"
            return $false
        }
        
        Write-Info "Using WSL distribution: $targetDistro"
        
        # Ensure the selected distribution is set as default
        Write-Progress "Configuring $targetDistro as default WSL distribution..."
        try {
            # Check current default
            $currentDefault = & wsl.exe --status 2>&1 | Select-String "Default Distribution" | ForEach-Object { 
                $line = $_.ToString()
                if ($line -match "Default Distribution:\s*(.+)") {
                    $matches[1].Trim()
                }
            }
            
            if ($currentDefault -and $currentDefault -ne $targetDistro) {
                Write-Info "Current default: $currentDefault, setting $targetDistro as default..."
                $setDefaultResult = & wsl.exe --set-default $targetDistro 2>&1
                if ($LASTEXITCODE -eq 0) {
                    Write-Success "$targetDistro is now the default WSL distribution"
                } else {
                    Write-Warning "Failed to set $targetDistro as default: $setDefaultResult"
                }
            } elseif ($currentDefault -eq $targetDistro) {
                Write-Success "$targetDistro is already the default WSL distribution"
            } else {
                # No default set or couldn't determine, try to set it anyway
                Write-Info "Setting $targetDistro as default WSL distribution..."
                $setDefaultResult = & wsl.exe --set-default $targetDistro 2>&1
                if ($LASTEXITCODE -eq 0) {
                    Write-Success "$targetDistro set as default WSL distribution"
                } else {
                    Write-Warning "Failed to set $targetDistro as default: $setDefaultResult"
                }
            }
        } catch {
            Write-Warning "Error configuring default WSL distribution: $($_.Exception.Message)"
        }
        
        # Test WSL connectivity
        Write-Progress "Testing WSL connectivity..."
        
        try {
            # Try to execute a simple command in WSL
            $testResult = wsl -d $targetDistro -- echo "WSL_TEST_SUCCESS" 2>&1
            
            # Check if the test was successful
            if ($testResult -and ($testResult -join "") -match "WSL_TEST_SUCCESS") {
                Write-Success "WSL connectivity test passed"
            } else {
                Write-Warning "WSL connectivity test failed - output: $($testResult -join ' ')"
                
                # Try with the default distribution without specifying -d
                $testResult2 = wsl -- echo "WSL_TEST_SUCCESS" 2>&1
                if ($testResult2 -and ($testResult2 -join "") -match "WSL_TEST_SUCCESS") {
                    Write-Success "WSL connectivity test passed (using default distribution)"
                } else {
                    Write-Warning "WSL connectivity test failed on both attempts"
                    return $false
                }
            }
        } catch {
            Write-Warning "WSL connectivity test failed: $($_.Exception.Message)"
            
            # Try one more time with basic wsl command
            try {
                $basicTest = wsl -- echo "test" 2>&1
                if ($basicTest) {
                    Write-Info "Basic WSL connectivity works, continuing..."
                } else {
                    return $false
                }
            } catch {
                Write-Error "WSL connectivity completely failed: $($_.Exception.Message)"
                return $false
            }
        }
        
        # Check if WSL distribution needs user setup
        Write-Progress "Checking if WSL distribution needs user setup..."
        
        $needsUserSetup = $false
        try {
            # Try to check if user is configured by running whoami
            $userTest = wsl -d $targetDistro -- whoami 2>&1
            
            # If whoami fails, returns root, or returns specific error patterns, user setup is needed
            if (-not $userTest -or 
                ($userTest -join " ") -match "Please create a default UNIX user account" -or
                ($userTest -join " ") -match "Installation incomplete" -or
                ($userTest -join " ") -match "The system cannot find the path specified" -or
                ($userTest -join "" -replace '\r?\n', '').Trim() -eq "root" -or
                $LASTEXITCODE -ne 0) {
                
                if (($userTest -join "" -replace '\r?\n', '').Trim() -eq "root") {
                    Write-Info "WSL distribution is running as root - user account setup needed"
                } else {
                    Write-Info "WSL distribution needs user setup"
                }
                $needsUserSetup = $true
            } else {
                $cleanUser = ($userTest -join "" -replace '\r?\n', '').Trim()
                Write-Success "WSL distribution is properly configured with user: $cleanUser"
            }
        } catch {
            Write-Info "Unable to determine user setup status, assuming setup needed"
            $needsUserSetup = $true
        }
        
        # If user setup is needed, launch Ubuntu in a separate window
        if ($needsUserSetup) {
            Write-Info ""
            Write-Info "🔧 WSL User Setup Required"
            Write-Info "Opening Ubuntu in a separate window for initial user setup..."
            Write-Info "🪟 A new Ubuntu terminal window will open where you need to:"
            Write-Info " • Create your username (recommend using your Windows username)"
            Write-Info " • Set a secure password"
            Write-Info " • Wait for the initial setup to complete"
            Write-Info " • Type 'exit' when done to return to this script"
            Write-Info ""
            Write-Warning "⚠️ Do NOT close this script window - it will wait for you"
            
            Start-Sleep -Seconds 3
            
            # Launch Ubuntu in a separate window using the best available method
            $launched = $false
            try {
                # Method 1: Try Windows Terminal (best experience)
                if (Get-Command "wt" -ErrorAction SilentlyContinue) {
                    Write-Info "Opening Ubuntu in Windows Terminal..."
                    $setupProcess = Start-Process "wt" -ArgumentList "wsl", "-d", $targetDistro -Wait
                    $launched = $true
                }
            } catch {
                Write-Info "Windows Terminal not available, trying alternative..."
            }
            
            if (-not $launched) {
                try {
                    # Method 2: Use cmd to open a new window
                    Write-Info "Opening Ubuntu in a new command window..."
                    $setupProcess = Start-Process "cmd" -ArgumentList "/c", "start", "cmd", "/k", "wsl -d $targetDistro" -Wait
                    $launched = $true
                } catch {
                    Write-Info "Command window approach failed, trying direct launch..."
                }
            }
            
            if (-not $launched) {
                # Method 3: Last resort - direct launch with warning
                Write-Warning "Opening Ubuntu directly in this window (not ideal for user experience)..."
                Write-Info "You'll need to complete setup here, then type 'exit' to continue"
                & wsl -d $targetDistro
            }
            
            Write-Success "Ubuntu user setup completed - continuing with verification..."
            
            # Re-verify user setup after manual configuration
            Start-Sleep -Seconds 2
            try {
                $verifyUser = wsl -d $targetDistro -- whoami 2>&1
                if ($verifyUser -and $LASTEXITCODE -eq 0) {
                    Write-Success "User setup verification passed: $($verifyUser -join '' -replace '\r?\n', '')"
                } else {
                    Write-Warning "User setup verification inconclusive, continuing..."
                }
            } catch {
                Write-Info "User verification failed, but continuing with setup..."
            }
        }
        
        # Collect sudo password for package management operations (only if needed)
        Write-Info ""
        Write-Info "🔐 WSL Package Management Setup"
        
        $sudoPassword = $null
        $needsSudo = $false
        
        # Check if we need sudo for any operations by testing package status
        try {
            # Check if we need to install/update packages
            $aptCheck = wsl -d $targetDistro -- bash -c "apt list --upgradable 2>/dev/null | wc -l" 2>&1
            $upgradableCount = [int]($aptCheck -join '' -replace '\D', '')
            
            # Check if git is installed
            $gitCheck = wsl -d $targetDistro -- which git 2>&1
            $gitInstalled = ($LASTEXITCODE -eq 0)
            
            # Check if git-lfs is installed
            $gitLfsCheck = wsl -d $targetDistro -- which git-lfs 2>&1
            $gitLfsInstalled = ($LASTEXITCODE -eq 0)
            
            if ($upgradableCount -gt 5 -or -not $gitInstalled -or -not $gitLfsInstalled) {
                $needsSudo = $true
                Write-Info "Package updates or installations are needed."
                Write-Info "This will be used only for 'sudo apt update', 'sudo apt upgrade', and package installation commands."
                Write-Info ""
            } else {
                Write-Info "System packages are up to date and required tools are installed."
                Write-Info "No sudo password required."
                Write-Info ""
            }
        } catch {
            # If we can't determine, assume we might need it
            $needsSudo = $true
            Write-Info "Unable to determine package status. May need sudo for package management."
            Write-Info ""
        }
        
        if ($needsSudo) {
            $maxAttempts = 3
            $attempt = 1
            
            while ($attempt -le $maxAttempts -and -not $sudoPassword) {
                try {
                    # Get current user for the prompt
                    $currentUser = wsl -d $targetDistro -- whoami 2>&1
                    $cleanUser = ($currentUser -join "" -replace '\r?\n', '').Trim()
                    
                    $securePassword = Read-Host "Enter your WSL password for user '$cleanUser'" -AsSecureString
                    
                    if ($securePassword.Length -gt 0) {
                        # Convert SecureString to plain text for use with echo command
                        $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword)
                        $plainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr)
                        [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr)
                        
                        # Test the password with a simple sudo command
                        Write-Info "Verifying password..."
                        $testResult = echo $plainPassword | wsl -d $targetDistro -- sudo -S whoami 2>&1
                        
                        if ($LASTEXITCODE -eq 0 -and ($testResult -join '') -match "root") {
                            $sudoPassword = $plainPassword
                            Write-Success "Password verified successfully"
                        } else {
                            Write-Warning "Password verification failed. Please try again."
                            $attempt++
                            if ($attempt -le $maxAttempts) {
                                Write-Info "Attempt $attempt of $maxAttempts"
                            }
                        }
                    } else {
                        Write-Warning "No password entered. Please try again."
                        $attempt++
                    }
                } catch {
                    Write-Warning "Error during password verification: $($_.Exception.Message)"
                    $attempt++
                }
            }
            
            if (-not $sudoPassword) {
                Write-Warning "Could not verify sudo password after $maxAttempts attempts"
                Write-Info "Skipping automatic package updates. You can run them manually later:"
                Write-Info " sudo apt update && sudo apt upgrade -y"
            }
        }
        
        # Update package lists and upgrade system packages (only if sudo password available)
        if ($sudoPassword) {
            Write-Progress "Updating WSL package lists..."
            
            try {
                Write-Info "Running: apt update"
                Write-Host "📦 Updating package lists..." -ForegroundColor Yellow
                Write-Host "----------------------------------------" -ForegroundColor DarkGray
                
                # Use password with sudo -S for non-interactive execution
                $updateResult = echo $sudoPassword | wsl -d $targetDistro -- sudo -S apt update 2>&1
                $updateExitCode = $LASTEXITCODE
                
                Write-Host "----------------------------------------" -ForegroundColor DarkGray
                if ($updateExitCode -eq 0) {
                    Write-Success "Package lists updated successfully"
                    $updateSuccessful = $true
                } else {
                    Write-Warning "Package update encountered issues (exit code: $updateExitCode)"
                    Write-Info "Output: $($updateResult -join ' ')"
                    $updateSuccessful = $false
                }
            } catch {
                Write-Warning "Failed to update package lists: $($_.Exception.Message)"
                $updateSuccessful = $false
            }
            
            # Only attempt upgrade if update was successful
            if ($updateSuccessful) {
                Write-Progress "Upgrading WSL system packages..."
                
                try {
                    Write-Info "Running: apt upgrade -y (this may take several minutes)"
                    Write-Host "📦 Upgrading system packages..." -ForegroundColor Yellow
                    Write-Host "----------------------------------------" -ForegroundColor DarkGray
                    
                    # Use password with sudo -S for non-interactive execution
                    echo $sudoPassword | wsl -d $targetDistro -- sudo -S apt upgrade -y
                    $upgradeExitCode = $LASTEXITCODE
                    
                    Write-Host "----------------------------------------" -ForegroundColor DarkGray
                    if ($upgradeExitCode -eq 0) {
                        Write-Success "System packages upgraded successfully"
                    } else {
                        Write-Warning "Package upgrade encountered issues (exit code: $upgradeExitCode)"
                    }
                } catch {
                    Write-Warning "Failed to upgrade packages: $($_.Exception.Message)"
                }
            } else {
                Write-Info "Skipping package upgrade due to update issues"
            }
        } else {
            Write-Info "Skipping package updates (no sudo access available)"
        }
        
        # Check Python availability in WSL
        Write-Progress "Checking Python in WSL..."
        
        try {
            $pythonVersion = wsl -d $targetDistro -- python3 --version 2>&1
            if ($pythonVersion -and $pythonVersion -match "Python \d+\.\d+") {
                Write-Success "Python is available in WSL: $($pythonVersion -join ' ')"
            } else {
                Write-Info "Python not found in WSL - may need installation during project setup"
            }
        } catch {
            Write-Info "Python availability check skipped - will be handled during project setup"
        }
        
        # Install and configure Git in WSL
        Write-Progress "Setting up Git in WSL..."
        
        try {
            # Check if git is already installed
            $gitVersion = wsl -d $targetDistro -- git --version 2>&1
            if ($LASTEXITCODE -eq 0 -and $gitVersion -match "git version") {
                Write-Success "Git is already available in WSL: $($gitVersion -join ' ')"
            } elseif ($sudoPassword) {
                Write-Info "Installing Git in WSL..."
                echo $sudoPassword | wsl -d $targetDistro -- sudo -S apt install -y git 2>&1
                if ($LASTEXITCODE -eq 0) {
                    Write-Success "Git installed successfully in WSL"
                } else {
                    Write-Warning "Git installation failed in WSL"
                }
            } else {
                Write-Warning "Git not found and no sudo access available. Manual installation may be needed."
            }
            
            # Install Git LFS if we have sudo access
            if ($sudoPassword) {
                Write-Info "Installing Git LFS in WSL..."
                echo $sudoPassword | wsl -d $targetDistro -- sudo -S apt-get install -y git-lfs 2>&1
                if ($LASTEXITCODE -eq 0) {
                    Write-Success "Git LFS installed successfully in WSL"
                } else {
                    Write-Warning "Git LFS installation failed in WSL"
                }
            } else {
                # Check if git-lfs is already installed
                $gitLfsCheck = wsl -d $targetDistro -- which git-lfs 2>&1
                if ($LASTEXITCODE -eq 0) {
                    Write-Success "Git LFS is already available in WSL"
                } else {
                    Write-Info "Git LFS not found. Install manually if needed: sudo apt install git-lfs"
                }
            }
            
            # Configure Git with settings from Windows git config
            Write-Info "Configuring Git in WSL..."
            
            # Get user name and email from Windows git config
            $windowsUserName = $null
            $windowsUserEmail = $null
            
            try {
                $windowsUserName = git config --global user.name 2>$null
                $windowsUserEmail = git config --global user.email 2>$null
            } catch {
                Write-Info "Could not read Windows git config, using defaults"
            }
            
            # Set user name
            if ($windowsUserName) {
                wsl -d $targetDistro -- git config --global user.name "$windowsUserName"
                Write-Info "Set Git user.name to '$windowsUserName' (from Windows git config)"
            } else {
                $userName = Read-Host "Enter your Git user.name for WSL (required)"
                while ([string]::IsNullOrWhiteSpace($userName)) {
                    $userName = Read-Host "Git user.name cannot be empty. Please enter your name:"
                }
                wsl -d $targetDistro -- git config --global user.name "$userName"
                Write-Info "Set Git user.name to '$userName' (entered by user)"
            }

            # Set user email
            if ($windowsUserEmail) {
                wsl -d $targetDistro -- git config --global user.email "$windowsUserEmail"
                Write-Info "Set Git user.email to '$windowsUserEmail' (from Windows git config)"
            } else {
                $userEmail = Read-Host "Enter your Git user.email for WSL (required)"
                while ([string]::IsNullOrWhiteSpace($userEmail)) {
                    $userEmail = Read-Host "Git user.email cannot be empty. Please enter your email:"
                }
                wsl -d $targetDistro -- git config --global user.email "$userEmail"
                Write-Info "Set Git user.email to '$userEmail' (entered by user)"
            }
            
            # Set default branch to main
            wsl -d $targetDistro -- git config --global init.defaultBranch main
            Write-Info "Set default branch to 'main'"
            
            # Configure credential manager to use Windows Git Credential Manager
            wsl -d $targetDistro -- git config --global credential.helper "/mnt/c/Program\ Files/Git/mingw64/bin/git-credential-manager.exe"
            Write-Info "Configured Git Credential Manager for Azure DevOps integration"
            
            # Set credential.useHttpPath for better Azure DevOps compatibility
            wsl -d $targetDistro -- git config --global credential.useHttpPath true
            Write-Info "Enabled HTTP path in credentials for Azure DevOps"
            
            # Configure VS Code as merge tool
            wsl -d $targetDistro -- git config --global merge.tool vscode
            wsl -d $targetDistro -- git config --global mergetool.vscode.cmd 'code --wait $MERGED'
            Write-Info "Configured VS Code as default merge tool"
            
            # Set additional git configurations for WSL environment
            wsl -d $targetDistro -- bash -c "git config --global --add safe.directory '*'"
            wsl -d $targetDistro -- git config --global pull.rebase false
            wsl -d $targetDistro -- git config --global core.autocrlf input
            
            Write-Success "Git configuration completed in WSL"
            
        } catch {
            Write-Warning "Failed to set up Git in WSL: $($_.Exception.Message)"
            Write-Info "Git may need manual configuration for strangeloop library access"
        }
        
        # Ensure basic project directory structure exists in WSL
        Write-Progress "Setting up WSL project directories..."
        
        try {
            # Create the AdsSnR_Containers\services directory if it doesn't exist
            Write-Info "Ensuring WSL project directory structure..."
            $createDirResult = wsl -d $targetDistro -- bash -c "mkdir -p /home/`$(whoami)/AdsSnR_Containers/services" 2>&1
            
            if ($LASTEXITCODE -eq 0) {
                Write-Success "WSL project directories ready"
                
                # Verify the directory was created
                $verifyDir = wsl -d $targetDistro -- bash -c "ls -la /home/`$(whoami)/AdsSnR_Containers/services" 2>&1
                if ($LASTEXITCODE -eq 0) {
                    Write-Info "Project directory verified: /home/\$(whoami)/AdsSnR_Containers/services"
                }
            } else {
                Write-Warning "Could not create project directories: $($createDirResult -join ' ')"
                Write-Info "Projects may need manual directory creation"
            }
        } catch {
            Write-Warning "Failed to set up project directories: $($_.Exception.Message)"
            Write-Info "You may need to manually create project directories in WSL"
        }
        
        Write-Success "WSL environment setup completed"
        return $true
        
    } catch {
        Write-Error "WSL environment setup failed: $($_.Exception.Message)"
        return $false
    }
}

# Main execution
if ($MyInvocation.InvocationName -ne '.') {
    $result = Initialize-WSLEnvironment
    $sudoPassword = $null

    if ($result) {
        Write-Success "WSL environment setup completed successfully"
        return $true
    } else {
        Write-Error "WSL environment setup failed"
        return $false
    }
}

# Export functions for module usage
# Export-ModuleMember -Function @(
# 'Initialize-WSLEnvironment'
# )