StrangeLoopBootstrap.psm1

# StrangeLoopBootstrap PowerShell Module
# Main module file for PowerShell Gallery distribution

#Requires -Version 7.0

<#
.SYNOPSIS
    Bootstraps a strangeloop development environment
 
.DESCRIPTION
    This function provides a PowerShell module interface to the strangeloop bootstrap process.
    It downloads and sets up the complete development environment with minimal dependencies.
 
.PARAMETER LoopName
    The name of the loop template to use for project creation
 
.PARAMETER ProjectName
    The name of the project to create
 
.PARAMETER ProjectPath
    The path where the project should be created
 
.PARAMETER FromPhase
    Start execution from this specific phase
 
.PARAMETER OnlyPhase
    Execute only this specific phase and skip all others
 
.PARAMETER SkipPhases
    Array of phases to skip during execution
 
.PARAMETER WhatIf
    Show what would be executed without actually doing it
 
.PARAMETER Force
    Overwrite existing directories if they exist
 
.EXAMPLE
    Invoke-StrangeLoopBootstrap
     
    Runs interactive bootstrap setup with latest version
 
.EXAMPLE
    Invoke-StrangeLoopBootstrap -LoopName "python-mcp-server" -ProjectName "MyApp"
     
    Sets up a Python MCP server project named "MyApp"
 
.EXAMPLE
    Invoke-StrangeLoopBootstrap -OnlyPhase "environment" -WhatIf
     
    Shows what the environment phase would do without executing
 
.NOTES
    This module wraps the strangeloop bootstrap functionality in a native PowerShell module
    for easier distribution and management through PowerShell Gallery.
#>

function Invoke-StrangeLoopBootstrap {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]$LoopName,
        
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]$ProjectName,
        
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]$ProjectPath,
        
        [ValidateSet("prerequisites", "authentication", "discovery", "environment", "wsl", "project", "git", "pipelines", "vscode", "completion")]
        [string]$FromPhase,
        
        [ValidateSet("prerequisites", "authentication", "discovery", "environment", "wsl", "project", "git", "pipelines", "vscode", "completion")]
        [string]$OnlyPhase,
        
        [ValidateSet("prerequisites", "authentication", "discovery", "environment", "wsl", "project", "git", "pipelines", "vscode", "completion")]
        [string[]]$SkipPhases,
        
        [switch]$Force
    )
    
    Write-Host "🚀 StrangeLoop Bootstrap PowerShell Module" -ForegroundColor Cyan
    Write-Host "============================================" -ForegroundColor Cyan
    Write-Host ""
    
    # Get the script location - use only scripts from the module's scripts folder
    $moduleRoot = $PSScriptRoot
    if (-not $moduleRoot) {
        $moduleRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
    }
    
    # Use the main setup script directly from the scripts folder
    $setupScript = Join-Path $moduleRoot "scripts\setup-strangeloop.ps1"
    
    if (-not (Test-Path $setupScript)) {
        Write-Error "Could not locate setup script at: $setupScript"
        Write-Information "Module may be corrupted or incorrectly installed."
        return
    }
    
    # Build parameters for the setup script
    $params = @{}
    
    if ($LoopName) { $params['loop-name'] = $LoopName }
    if ($ProjectName) { $params['project-name'] = $ProjectName }
    if ($ProjectPath) { $params['project-path'] = $ProjectPath }
    if ($FromPhase) { $params['from-phase'] = $FromPhase }
    if ($OnlyPhase) { $params['only-phase'] = $OnlyPhase }
    if ($SkipPhases) { $params['skip-phases'] = $SkipPhases }
    if ($Force) { $params['force'] = $true }
    if ($WhatIfPreference -or $PSCmdlet.ShouldProcess("StrangeLoop Environment", "Bootstrap")) { 
        if ($WhatIfPreference) { $params['what-if'] = $true }
    }
    
    try {
        # Call the main setup script with parameters
        & $setupScript @params
        
        Write-Host ""
        Write-Host "✅ StrangeLoop Bootstrap completed successfully!" -ForegroundColor Green
    }
    catch {
        Write-Error "Bootstrap process failed: $($_.Exception.Message)"
        throw
    }
}

<#
.SYNOPSIS
    Gets the current version of StrangeLoop Bootstrap
 
.DESCRIPTION
    Retrieves version information for both the local module and available remote versions
 
.PARAMETER ListAvailable
    List all available versions from the repository
 
.PARAMETER IncludePreRelease
    Include pre-release versions in the list
 
.EXAMPLE
    Get-StrangeLoopVersion
     
    Shows the current module version
 
.EXAMPLE
    Get-StrangeLoopVersion -ListAvailable
     
    Lists all available stable versions
 
.EXAMPLE
    Get-StrangeLoopVersion -ListAvailable -IncludePreRelease
     
    Lists all versions including pre-releases
#>

function Get-StrangeLoopVersion {
    [CmdletBinding()]
    param(
        [switch]$ListAvailable,
        [switch]$IncludePreRelease
    )
    
    # Get local module version
    $moduleInfo = Get-Module -Name StrangeLoopBootstrap -ListAvailable | Select-Object -First 1
    $localVersion = if ($moduleInfo) { $moduleInfo.Version } else { "Not installed" }
    
    Write-Host "StrangeLoop Bootstrap Version Information" -ForegroundColor Cyan
    Write-Host "=========================================" -ForegroundColor Cyan
    Write-Host "Local Module Version: $localVersion" -ForegroundColor Green
    
    if ($ListAvailable) {
        Write-Host ""
        Write-Host "Available Versions from PowerShell Gallery:" -ForegroundColor Yellow
        
        try {
            # Query PowerShell Gallery for available versions
            $galleryVersions = Find-Module -Name StrangeLoopBootstrap -AllVersions -ErrorAction SilentlyContinue
            
            if ($galleryVersions) {
                $filteredVersions = $galleryVersions
                if (-not $IncludePreRelease) {
                    $filteredVersions = $galleryVersions | Where-Object { -not $_.Version.PreReleaseLabel }
                }
                
                $filteredVersions | ForEach-Object {
                    $versionStr = $_.Version.ToString()
                    if ($_.Version.PreReleaseLabel) {
                        $versionStr += "-$($_.Version.PreReleaseLabel)"
                    }
                    $publishDate = if ($_.PublishedDate) { $_.PublishedDate.ToString("yyyy-MM-dd") } else { "Unknown" }
                    Write-Host " $versionStr (Published: $publishDate)" -ForegroundColor White
                }
            } else {
                Write-Host " No versions found in PowerShell Gallery" -ForegroundColor Yellow
                Write-Host " The module may not be published yet." -ForegroundColor Gray
            }
        }
        catch {
            Write-Warning "Could not retrieve version information from PowerShell Gallery: $($_.Exception.Message)"
        }
    }
    
    # Additional version info
    Write-Host ""
    Write-Host "Module Information:" -ForegroundColor Cyan
    if ($moduleInfo) {
        Write-Host " Path: $($moduleInfo.ModuleBase)" -ForegroundColor Gray
        Write-Host " Author: $($moduleInfo.Author)" -ForegroundColor Gray
        Write-Host " Description: $($moduleInfo.Description)" -ForegroundColor Gray
    } else {
        Write-Host " Module not currently installed" -ForegroundColor Gray
    }
}

<#
.SYNOPSIS
    Resets the strangeloop development environment
 
.DESCRIPTION
    Provides a clean reset of strangeloop environment settings and configurations
 
.PARAMETER WhatIf
    Show what would be reset without actually doing it
 
.PARAMETER Force
    Force reset without confirmation prompts
 
.EXAMPLE
    Reset-StrangeLoopEnvironment
     
    Interactively resets the environment with confirmation
 
.EXAMPLE
    Reset-StrangeLoopEnvironment -WhatIf
     
    Shows what would be reset without making changes
 
.EXAMPLE
    Reset-StrangeLoopEnvironment -Force
     
    Forces reset without prompts
#>

function Reset-StrangeLoopEnvironment {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [switch]$Force
    )
    
    Write-Host "🔄 StrangeLoop Environment Reset" -ForegroundColor Yellow
    Write-Host "================================" -ForegroundColor Yellow
    
    # Get the script location - use only scripts from the module's scripts folder
    $moduleRoot = $PSScriptRoot
    if (-not $moduleRoot) {
        $moduleRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
    }
    
    # Use the reset script directly from the scripts folder
    $resetScript = Join-Path $moduleRoot "scripts\reset_strangeloop.ps1"
    
    if (-not (Test-Path $resetScript)) {
        Write-Error "Reset script not found at: $resetScript"
        Write-Information "Module may be corrupted or incorrectly installed."
        return
    }
    
    $params = @{}
    if ($Force) { $params['Force'] = $true }
    if ($WhatIfPreference -or $PSCmdlet.ShouldProcess("StrangeLoop Environment", "Reset")) {
        if ($WhatIfPreference) { $params['WhatIf'] = $true }
    } else {
        return
    }
    
    try {
        & $resetScript @params
        
        if (-not $WhatIfPreference) {
            Write-Host ""
            Write-Host "✅ StrangeLoop Environment reset completed!" -ForegroundColor Green
        }
    }
    catch {
        Write-Error "Reset process failed: $($_.Exception.Message)"
        throw
    }
}

<#
.SYNOPSIS
    Installs only the prerequisites for StrangeLoop development
 
.DESCRIPTION
    Installs just the prerequisite tools without setting up a full project environment.
    Useful for preparing a system for StrangeLoop development.
 
.PARAMETER WhatIf
    Show what would be installed without actually doing it
 
.PARAMETER Force
    Force installation without confirmation prompts
 
.EXAMPLE
    Install-StrangeLoopPrerequisites
     
    Installs prerequisites with user confirmations
 
.EXAMPLE
    Install-StrangeLoopPrerequisites -WhatIf
     
    Shows what prerequisites would be installed
 
.EXAMPLE
    Install-StrangeLoopPrerequisites -Force
     
    Installs prerequisites without prompts
#>

function Install-StrangeLoopPrerequisites {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [switch]$Force
    )
    
    Write-Host "📋 StrangeLoop Prerequisites Installation" -ForegroundColor Cyan
    Write-Host "==========================================" -ForegroundColor Cyan
    
    # Use the main bootstrap function with only-phase parameter
    $params = @{
        'OnlyPhase' = 'prerequisites'
    }
    
    if ($Force) { $params['Force'] = $true }
    if ($WhatIfPreference -or $PSCmdlet.ShouldProcess("StrangeLoop Prerequisites", "Install")) {
        if ($WhatIfPreference) { 
            Write-Host "Would install prerequisites only..." -ForegroundColor Yellow
            $params['WhatIf'] = $true 
        }
    } else {
        return
    }
    
    try {
        Invoke-StrangeLoopBootstrap @params
    }
    catch {
        Write-Error "Prerequisites installation failed: $($_.Exception.Message)"
        throw
    }
}

<#
.SYNOPSIS
    Initializes a new StrangeLoop project without full environment setup
 
.DESCRIPTION
    Creates a new project from a StrangeLoop template assuming prerequisites are already installed.
 
.PARAMETER LoopName
    The name of the loop template to use
 
.PARAMETER ProjectName
    The name of the project to create
 
.PARAMETER ProjectPath
    The path where the project should be created
 
.PARAMETER IncludeGit
    Include Git repository initialization
 
.PARAMETER IncludeVSCode
    Include VS Code workspace setup
 
.EXAMPLE
    Initialize-StrangeLoopProject -LoopName "python-mcp-server" -ProjectName "MyApp"
     
    Creates a new Python MCP server project
 
.EXAMPLE
    Initialize-StrangeLoopProject -LoopName "flask-api" -ProjectName "WebAPI" -ProjectPath "C:\Projects" -IncludeGit -IncludeVSCode
     
    Creates a Flask API project with Git and VS Code setup
#>

function Initialize-StrangeLoopProject {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [string]$LoopName,
        
        [Parameter(Mandatory)]
        [string]$ProjectName,
        
        [string]$ProjectPath,
        
        [switch]$IncludeGit,
        
        [switch]$IncludeVSCode,
        
        [switch]$Force
    )
    
    Write-Host "🚀 StrangeLoop Project Initialization" -ForegroundColor Cyan
    Write-Host "=====================================" -ForegroundColor Cyan
    
    # Build the phases to run
    $phases = @('project')
    if ($IncludeGit) { $phases += 'git' }
    if ($IncludeVSCode) { $phases += 'vscode' }
    
    $params = @{
        'LoopName' = $LoopName
        'ProjectName' = $ProjectName
        'FromPhase' = 'project'
        'SkipPhases' = @('prerequisites', 'authentication', 'discovery', 'environment', 'wsl', 'pipelines', 'completion')
    }
    
    if ($ProjectPath) { $params['ProjectPath'] = $ProjectPath }
    if ($Force) { $params['Force'] = $true }
    
    # Adjust skip phases based on included features
    if (-not $IncludeGit) { 
        $params['SkipPhases'] += 'git' 
    }
    if (-not $IncludeVSCode) { 
        $params['SkipPhases'] += 'vscode' 
    }
    
    if ($WhatIfPreference -or $PSCmdlet.ShouldProcess("Project: $ProjectName", "Initialize")) {
        if ($WhatIfPreference) { 
            Write-Host "Would initialize project: $ProjectName using template: $LoopName" -ForegroundColor Yellow
            $params['WhatIf'] = $true 
        }
    } else {
        return
    }
    
    try {
        Invoke-StrangeLoopBootstrap @params
    }
    catch {
        Write-Error "Project initialization failed: $($_.Exception.Message)"
        throw
    }
}

<#
.SYNOPSIS
    Configures the development environment for StrangeLoop
 
.DESCRIPTION
    Sets up the development environment components without creating a specific project.
    Includes Docker, WSL, and other environment-specific configurations.
 
.PARAMETER Platform
    Target platform (Windows, WSL, or Both)
 
.PARAMETER IncludeDocker
    Include Docker installation and configuration
 
.PARAMETER IncludeWSL
    Include WSL setup and configuration
 
.EXAMPLE
    Set-StrangeLoopEnvironment -Platform "Both" -IncludeDocker -IncludeWSL
     
    Sets up environment for both Windows and WSL with Docker
 
.EXAMPLE
    Set-StrangeLoopEnvironment -Platform "Windows" -IncludeDocker
     
    Sets up Windows environment with Docker only
#>

function Set-StrangeLoopEnvironment {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [ValidateSet("Windows", "WSL", "Both")]
        [string]$Platform = "Both",
        
        [switch]$IncludeDocker,
        
        [switch]$IncludeWSL,
        
        [switch]$Force
    )
    
    Write-Host "🏗️ StrangeLoop Environment Configuration" -ForegroundColor Cyan
    Write-Host "=========================================" -ForegroundColor Cyan
    
    $skipPhases = @('discovery', 'project', 'git', 'pipelines', 'vscode', 'completion')
    
    # Configure phases based on platform
    if ($Platform -eq "Windows" -or -not $IncludeWSL) {
        $skipPhases += 'wsl'
    }
    
    $params = @{
        'FromPhase' = 'environment'
        'SkipPhases' = $skipPhases
    }
    
    if ($Force) { $params['Force'] = $true }
    
    if ($WhatIfPreference -or $PSCmdlet.ShouldProcess("StrangeLoop Environment", "Configure")) {
        if ($WhatIfPreference) { 
            Write-Host "Would configure environment for platform: $Platform" -ForegroundColor Yellow
            $params['WhatIf'] = $true 
        }
    } else {
        return
    }
    
    try {
        Invoke-StrangeLoopBootstrap @params
    }
    catch {
        Write-Error "Environment configuration failed: $($_.Exception.Message)"
        throw
    }
}

# Create aliases for common operations
New-Alias -Name "strangeloop-setup" -Value "Invoke-StrangeLoopBootstrap" -Description "Alias for Invoke-StrangeLoopBootstrap" -Force
New-Alias -Name "sl-bootstrap" -Value "Invoke-StrangeLoopBootstrap" -Description "Short alias for Invoke-StrangeLoopBootstrap" -Force
New-Alias -Name "sl-reset" -Value "Reset-StrangeLoopEnvironment" -Description "Alias for Reset-StrangeLoopEnvironment" -Force
New-Alias -Name "sl-version" -Value "Get-StrangeLoopVersion" -Description "Alias for Get-StrangeLoopVersion" -Force

# Export module functions
Export-ModuleMember -Function @(
    'Invoke-StrangeLoopBootstrap',
    'Get-StrangeLoopVersion', 
    'Reset-StrangeLoopEnvironment',
    'Install-StrangeLoopPrerequisites',
    'Initialize-StrangeLoopProject',
    'Set-StrangeLoopEnvironment'
) -Alias @(
    'strangeloop-setup',
    'sl-bootstrap',
    'sl-reset',
    'sl-version'
)