scripts/modules/prerequisites/poetry/install-poetry.ps1

# strangeloop Setup - Poetry Installation Module
# Version: 1.0.0


param(
    [switch]$WSLMode,
    [switch]${test-only}
)

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

function Test-PoetryWindows {
    param(
        
    )
    
    try {
        {
            Write-Info "Testing Poetry installation (Windows)..."
        }
        
        # Check if Poetry is installed
        if (-not (Test-Command "poetry")) {
            {
                Write-Warning "Poetry command not found"
            }
            return $false
        }
        
        # Check Poetry version
        $poetryVersion = poetry --version 2>$null
        if (-not $poetryVersion) {
            {
                Write-Warning "Could not get Poetry version"
            }
            return $false
        }
        
        {
            Write-Success "Poetry is properly installed: $poetryVersion"
        }
        return $true
        
    } catch {
        {
            Write-Warning "Error testing Poetry: $($_.Exception.Message)"
        }
        return $false
    }
}

function Test-PoetryWSL {
    param(
        
    )
    
    try {
        {
            Write-Info "Testing Poetry installation (WSL)..."
        }
        
        # Check if WSL is available
        if (-not (Test-Command "wsl")) {
            {
                Write-Warning "WSL not available"
            }
            return $false
        }
        
        # Check Poetry in WSL
        $wslPoetryTest = wsl poetry --version 2>$null
        if (-not $wslPoetryTest) {
            {
                Write-Warning "Poetry not found in WSL"
            }
            return $false
        }
        
        {
            Write-Success "Poetry is properly installed in WSL: $wslPoetryTest"
        }
        return $true
        
    } catch {
        {
            Write-Warning "Error testing Poetry in WSL: $($_.Exception.Message)"
        }
        return $false
    }
}

function Install-Poetry {
    param(
        [switch]$WSLMode,
        [switch]${test-only}
    )
    
    # If test-only mode, just test current installation
    if (${test-only}) {
        if ($WSLMode) {
            return Test-PoetryWSL
        } else {
            return Test-PoetryWindows
        }
    }
    
    # Install and return result
    if ($WSLMode) {
        return Install-PoetryWSL
    } else {
        return Install-PoetryWindows
    }
}

function Install-PoetryWindows {
    param(
    )
    
    Write-Step "Installing Poetry (Windows)..."
    
    try {
        # Check if Poetry is already installed
        if (Test-Command "poetry") {
            $poetryVersion = poetry --version 2>$null
            if ($poetryVersion) {
                Write-Success "Poetry is already installed: $poetryVersion"
                return Set-Poetry -WSLMode:$false
            }
        }
        
        $installChoice = Read-UserPrompt -Prompt "Poetry not found. Install Poetry?" -ValidValues @("y","n")
        if (-not (Test-YesResponse $installChoice)) {
            Write-Warning "Skipping Poetry installation"
            return $false
        }
        
        # Ensure pipx is available
        if (-not (Test-Command "pipx")) {
            Write-Info "pipx not found. Installing pipx first..."
            python -m pip install --user pipx
            python -m pipx ensurepath
            
            # Refresh PATH
            $env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH", "User")
        }
        
        Write-Progress "Installing Poetry via pipx..."
        
        try {
            pipx install poetry
            Write-Success "Poetry installed successfully"
            
            # Configure Poetry
            return Set-Poetry -WSLMode:$false
            
        } catch {
            Write-Warning "pipx installation failed, trying alternative method..."
            
            # Fallback: Official Poetry installer
            try {
                Write-Info "Using official Poetry installer..."
                $installerUrl = "https://install.python-poetry.org"
                $installerScript = Invoke-WebRequest -Uri $installerUrl -UseBasicParsing
                
                # Execute the installer
                Invoke-Expression $installerScript.Content
                
                # Add Poetry to PATH
                $poetryPath = "$env:APPDATA\Python\Scripts"
                $currentPath = [Environment]::GetEnvironmentVariable("PATH", "User")
                if ($currentPath -notlike "*$poetryPath*") {
                    [Environment]::SetEnvironmentVariable("PATH", "$currentPath;$poetryPath", "User")
                    $env:PATH += ";$poetryPath"
                }
                
                Write-Success "Poetry installed via official installer"
                return Set-Poetry -WSLMode:$false
                
            } catch {
                Write-Error "Poetry installation failed: $($_.Exception.Message)"
                return $false
            }
        }
        
    } catch {
        Write-Error "Poetry installation failed: $($_.Exception.Message)"
        return $false
    }
}

function Install-PoetryWSL {
    param(
    )
    
    Write-Step "Installing Poetry (WSL)..."
    
    try {
        # Check for WSL
        if (-not (Test-Command "wsl")) {
            Write-Error "WSL is not available"
            return $false
        }
        
        # Get default WSL distribution
        $defaultDistro = wsl -l -q | Select-Object -First 1
        if (-not $defaultDistro) {
            Write-Error "No WSL distribution found"
            return $false
        }
        
        Write-Info "Installing Poetry in WSL distribution: $defaultDistro"
        
        # Check if Poetry is already installed in WSL
        $poetryCheck = wsl -d $defaultDistro -- which poetry 2>/dev/null
        if ($poetryCheck) {
            $poetryVersion = wsl -d $defaultDistro -- poetry --version 2>/dev/null
            Write-Success "Poetry is already installed in WSL: $poetryVersion"
            return Set-Poetry -WSLMode:$true
        }
        
        # Ensure pipx is available in WSL
        $pipxCheck = wsl -d $defaultDistro -- which pipx 2>/dev/null
        if (-not $pipxCheck) {
            Write-Info "Installing pipx in WSL..."
            wsl -d $defaultDistro -- sudo apt install -y pipx
            wsl -d $defaultDistro -- pipx ensurepath
        }
        
        Write-Progress "Installing Poetry via pipx in WSL..."
        
        try {
            wsl -d $defaultDistro -- pipx install poetry
            
            # Verify installation
            $poetryVersion = wsl -d $defaultDistro -- poetry --version 2>/dev/null
            if ($poetryVersion) {
                Write-Success "Poetry installed in WSL: $poetryVersion"
                return Set-Poetry -WSLMode:$true
            } else {
                Write-Warning "Poetry installation verification failed"
                return $false
            }
            
        } catch {
            Write-Error "Poetry WSL installation failed: $($_.Exception.Message)"
            return $false
        }
        
    } catch {
        Write-Error "Poetry WSL installation failed: $($_.Exception.Message)"
        return $false
    }
}

function Set-Poetry {
    param(
        [switch]$WSLMode
    )
    
    Write-Step "Configuring Poetry..."
    
    try {
        if ($WSLMode) {
            # Configure Poetry in WSL
            $defaultDistro = wsl -l -q | Select-Object -First 1
            
            Write-Info "Configuring Poetry virtual environments in WSL..."
            wsl -d $defaultDistro -- poetry config virtualenvs.in-project true
            
            # Verify configuration
            $configCheck = wsl -d $defaultDistro -- poetry config virtualenvs.in-project 2>/dev/null
            if ($configCheck -eq "true") {
                Write-Success "Poetry configured to create virtual environments in project directories (WSL)"
                return $true
            } else {
                Write-Warning "Poetry configuration verification failed in WSL"
                return $false
            }
        } else {
            # Configure Poetry on Windows
            Write-Info "Configuring Poetry virtual environments..."
            poetry config virtualenvs.in-project true
            
            # Verify configuration
            $configCheck = poetry config virtualenvs.in-project 2>$null
            if ($configCheck -eq "true") {
                Write-Success "Poetry configured to create virtual environments in project directories"
                return $true
            } else {
                Write-Warning "Poetry configuration verification failed"
                return $false
            }
        }
        
    } catch {
        Write-Warning "Poetry configuration failed: $($_.Exception.Message)"
        return $false
    }
}

# Main execution
if ($MyInvocation.InvocationName -ne '.') {
    $result = Install-Poetry -WSLMode:$WSLMode -test-only:${test-only}
    
    if ($result) {
        if (${test-only}) {
            Write-Success "Poetry test completed successfully"
        } else {
            Write-Success "Poetry installation completed successfully"
        }
        exit 0
    } else {
        if (${test-only}) {
            Write-Error "Poetry test failed"
        } else {
            Write-Error "Poetry installation failed"
        }
        exit 1
    }
}

# Export functions for module usage
if ($MyInvocation.MyCommand.ModuleName) {
    Export-ModuleMember -Function @(
        'Install-Poetry',
        'Install-PoetryWindows', 
        'Install-PoetryWSL',
        'Set-Poetry'
    )
}