scripts/modules/discovery/setup-discovery.ps1

# strangeloop Setup - Discovery Setup Module
# Version: 1.0.0


param(
    [string]$Platform = "Windows",
    [switch]${test-only},
    [switch]${what-if}
)

# Import shared modules
$SharedPath = Split-Path $PSScriptRoot -Parent | Join-Path -ChildPath "shared"
Import-Module "$SharedPath\Write-Functions.ps1" -Force -DisableNameChecking
Import-Module "$SharedPath\Test-Functions.ps1" -Force -DisableNameChecking

function Show-LoopSelection {
    param(
        [Parameter(Mandatory)]
        [array]$AvailableLoops
    )
    
    try {
        Write-Host ""
        Write-Step "Available strangeloop Templates"
        Write-Host ""
        
        # Group loops by platform (WSL vs Windows) for better organization
        $windowsOnlyLoops = @('asp-dotnet-framework-api', 'ads-snr-basic', 'flask-windows')
        
        $platformGroups = @{
            'Windows' = @()
            'WSL' = @()
        }
        
        foreach ($loop in $AvailableLoops) {
            if ($loop -in $windowsOnlyLoops) {
                $platformGroups['Windows'] += $loop
            } else {
                $platformGroups['WSL'] += $loop
            }
        }
        
        $index = 1
        $loopIndex = @{}
        
        foreach ($platform in @('Windows', 'WSL')) {
            if ($platformGroups[$platform].Count -gt 0) {
                Write-Host " ${platform} Loops:" -ForegroundColor Cyan
                
                foreach ($loop in $platformGroups[$platform] | Sort-Object) {
                    Write-Host " [$index] $loop" -ForegroundColor White
                    $loopIndex[$index] = $loop
                    $index++
                }
                Write-Host ""
            }
        }
        
        do {
            $selection = Read-UserPrompt -Prompt "Select a template (1-$($AvailableLoops.Count)) or 'q' to quit"
            
            if ($selection -eq 'q' -or $selection -eq 'quit') {
                return $null
            }
            
            $selectedIndex = $null
            if ([int]::TryParse($selection, [ref]$selectedIndex) -and $loopIndex.ContainsKey($selectedIndex)) {
                $selectedLoop = $loopIndex[$selectedIndex]
                Write-Host ""
                Write-Success "Selected: $selectedLoop"
                return $selectedLoop
            } else {
                Write-Warning "Invalid selection. Please enter a number between 1 and $($AvailableLoops.Count) or 'q' to quit."
            }
        } while ($true)
        
    } catch {
        Write-Warning "Error in loop selection: $($_.Exception.Message)"
        return $null
    }
}

function Initialize-Discovery {
    param(
        [string]${loop-name},
        [switch]${what-if}
    )
    
    Write-Step "Setting up Loop Discovery & Analysis..."
    
    if (${what-if}) {
        Write-Host "what if: Would check if strangeloop CLI is available" -ForegroundColor Yellow
        Write-Host "what if: Would execute 'strangeloop library loops' to discover available templates" -ForegroundColor Yellow
        if (${loop-name}) {
            Write-Host "what if: Would use pre-selected loop: ${loop-name}" -ForegroundColor Yellow
        } else {
            Write-Host "what if: Would show interactive loop selection menu" -ForegroundColor Yellow
        }
        Write-Host "what if: Would analyze environment requirements (Windows vs WSL)" -ForegroundColor Yellow
        Write-Host "what if: Would return loop selection and platform requirements" -ForegroundColor Yellow
        return @{
            Success = $true
            SelectedLoop = if (${loop-name}) { ${loop-name} } else { "example-loop" }
            EnvironmentRequirements = @{
                RequiresWSL = $true
                RequiresWindows = $false
                Platform = "WSL"
            }
            AvailableLoops = @("example-loop1", "example-loop2")
        }
    }
    
    try {
        # Check if strangeloop CLI is available
        if (-not (Test-Command "strangeloop")) {
            Write-Error "strangeloop CLI is not installed. Please install strangeloop CLI first."
            return @{ Success = $false }
        }
        
        # Get available loops
        Write-Progress "Discovering available loops..."
        
        try {
            $loopsList = strangeloop library loops 2>$null
            if (-not $loopsList) {
                Write-Error "Could not retrieve loops list from strangeloop CLI"
                return @{ Success = $false }
            }
            
            # Parse available loops - strangeloop uses format: "loop-name Description"
            $availableLoops = $loopsList | Where-Object { $_ -match "^[a-z]" -and $_ -notmatch "INFO|loading|__" } | ForEach-Object {
                ($_ -split "\s+")[0].Trim()
            }
            
            Write-Success "Found $($availableLoops.Count) available loops"
            
            # Select loop
            $selectedLoop = $null
            
            if (${loop-name}) {
                if (${loop-name} -in $availableLoops) {
                    $selectedLoop = ${loop-name}
                    Write-Success "Pre-selected loop: $selectedLoop"
                } else {
                    Write-Error "Specified loop '${loop-name}' not found in available loops"
                    return @{ Success = $false }
                }
            } else {
                # Interactive loop selection
                $selectedLoop = Show-LoopSelection -AvailableLoops $availableLoops
                if (-not $selectedLoop) {
                    Write-Info "No loop selected, exiting discovery"
                    return @{ Success = $false }
                }
            }
            
            # Determine environment requirements based on exact loop categorization
            Write-Progress "Analyzing environment requirements..."
            
            # Define Windows-only loops (everything else defaults to WSL)
            $windowsOnlyLoops = @('asp-dotnet-framework-api', 'ads-snr-basic', 'flask-windows')
            $requiresWindows = $selectedLoop -in $windowsOnlyLoops
            $requiresWSL = -not $requiresWindows
            
            $environmentRequirements = @{
                RequiresWSL = $requiresWSL
                RequiresWindows = $requiresWindows
                SelectedLoop = $selectedLoop
                Platform = if ($requiresWSL) { "WSL" } else { "Windows" }
            }
            
            Write-Success "Environment analysis completed"
            Write-Info "Selected loop: $selectedLoop"
            Write-Info "Target platform: $($environmentRequirements.Platform)"
            
            return @{
                Success = $true
                SelectedLoop = $selectedLoop
                EnvironmentRequirements = $environmentRequirements
                AvailableLoops = $availableLoops
            }
            
        } catch {
            Write-Error "Loop discovery failed: $($_.Exception.Message)"
            return @{ Success = $false }
        }
        
    } catch {
        Write-Error "Discovery setup failed: $($_.Exception.Message)"
        return @{ Success = $false }
    }
}

# Main execution
if ($MyInvocation.InvocationName -ne '.') {
    $result = Initialize-Discovery -loop-name ${loop-name} -what-if:${what-if}
    
    if ($result.Success) {
        Write-Success "Discovery setup completed successfully"
        Write-Host "Selected Loop: $($result.SelectedLoop)" -ForegroundColor Green
        Write-Host "Platform: $($result.EnvironmentRequirements.Platform)" -ForegroundColor Green
    } else {
        Write-Error "Discovery setup failed"
    }
    
    # Return the result for Invoke-Phase to capture
    return $result
}

# Export functions for module usage
# Export-ModuleMember -Function @(
# 'Setup-Discovery'
# )