src/Start-AZSCWizard.ps1

#Requires -Version 7.0
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

<#
.SYNOPSIS
    Guided, interactive setup wizard for Azure Scout.
 
.DESCRIPTION
    Walks an operator through a Scout run without them having to know a single
    switch. A bare `Invoke-AzureScout` in an interactive session opens this
    wizard automatically; you can also call it directly.
 
    The wizard runs five steps:
 
        1. Tenant — show the signed-in context, or sign in / pick a tenant.
                         When the account can reach more than one tenant, also
                         offers scanning several selected tenants or every
                         accessible tenant (AB#7105).
        2. Permissions — verify the account actually holds the rights the run
                         needs, and let the operator bail out before a long scan
                         fails halfway through.
        3. What to run — inventory, assessment, or both, then a checklist of the
                         individual categories/assessments. Everything is
                         pre-selected; the operator unchecks what they don't want.
        4. Output — report formats and the report directory (Enter accepts
                         the default).
        5. Confirm — echo the equivalent one-line command, then run it.
 
    Step 5 prints the exact `Invoke-AzureScout` command the answers map to, so
    the wizard doubles as a way to learn the parameters for later automation.
 
.PARAMETER AzureEnvironment
    Azure cloud environment to sign in against. Defaults to 'AzureCloud'.
 
.PARAMETER PlatOS
    Host platform as detected by Test-AZSCPS. Used to skip the interactive
    sign-in prompt in Azure Cloud Shell, which is already authenticated.
 
.OUTPUTS
    A hashtable with two keys:
      Answers — parameter name/value pairs to splat onto Invoke-AzureScout.
      RunBoth — $true when the operator asked for inventory *and* assessment.
    Returns $null if the operator cancels at any step.
 
.EXAMPLE
    PS C:\> Invoke-AzureScout
    Opens the wizard (interactive sessions only).
 
.EXAMPLE
    PS C:\> Invoke-AzureScout -NoWizard
    Skips the wizard and runs the default full ARM inventory.
 
.NOTES
    Tracks AB#5541. Never prompts in a non-interactive host — Invoke-AzureScout
    gates the call on Test-AZSCInteractiveHost so CI and scheduled runs can
    never block waiting for input.
#>

function Start-AZSCWizard {
    # The 'Start' verb trips PSUseShouldProcessForStateChangingFunctions, but this
    # function only prompts and returns a hashtable — it changes nothing. The
    # caller (Invoke-AzureScout) is what acts on the answers.
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param(
        [string]$AzureEnvironment = 'AzureCloud',
        [string]$PlatOS
    )

    # Microsoft's eighteen published service categories (AB#6741). Kept in the same order and
    # spelling as Invoke-AzureScout's -Category ValidateSet so the wizard cannot offer a value the
    # command would then reject.
    $inventoryCategories = @(
        'AI', 'Analytics', 'Compute', 'Containers', 'Databases', 'DevOps', 'General', 'Hybrid',
        'Identity', 'Integration', 'IoT', 'Management', 'Migration', 'Monitor', 'Networking',
        'Security', 'Storage', 'Web'
    )
    # One honest format pool for every run type. Legacy names remain accepted by the public
    # parameter for compatibility, but the wizard only offers the three formats that are live.
    $liveFormats = @('React', 'Json', 'JsonEvidence')

    Write-AZSCWizardBanner

    # ── Step 1: tenant ───────────────────────────────────────────────────────
    Write-AZSCWizardStep -Number 1 -Total 5 -Title 'Tenant'

    $tenantId = $null
    $context = $null
    $needsSignIn = $false
    try { $context = Get-AzContext -ErrorAction Stop } catch { $context = $null }

    if ($context -and $context.Tenant) {
        $contextIdentity = Resolve-AZSCContextIdentity -Context $context
        Write-Host " Signed in as : " -NoNewline -ForegroundColor DarkGray
        Write-Host $contextIdentity.AccountDisplayName -ForegroundColor Cyan
        Write-Host " Tenant : " -NoNewline -ForegroundColor DarkGray
        Write-Host $contextIdentity.TenantDisplayName -ForegroundColor Cyan
        Write-Host ''
        if (Read-AZSCWizardConfirm -Prompt 'Use this signed-in account?' -Default $true) {
            $tenantId = $context.Tenant.Id
        }
        else {
            $needsSignIn = $true
        }
    }
    else {
        Write-Host ' No active Azure session found.' -ForegroundColor Yellow
        Write-Host ''
        $needsSignIn = $true
    }

    if ($needsSignIn) {
        if ($PlatOS -eq 'Azure CloudShell') {
            Write-Host ' Running in Cloud Shell — using the ambient session.' -ForegroundColor DarkGray
            try { $tenantId = (Get-AzContext -ErrorAction Stop).Tenant.Id } catch { $tenantId = $null }
        }
        else {
            $useDeviceLogin = Read-AZSCWizardConfirm -Prompt 'Sign in with a device code (needed on headless/SSH hosts)?' -Default $false
            Write-Host ' Opening Azure sign-in...' -ForegroundColor DarkGray
            try {
                $tenantId = Connect-AZSCLoginSession -AzureEnvironment $AzureEnvironment -DeviceLogin:$useDeviceLogin -ForceLogin
            }
            catch {
                Write-Host " Sign-in failed: $_" -ForegroundColor Red
                return $null
            }
        }
    }

    # Discover once, then choose scope before asking for an individual tenant.
    $accessibleTenants = @(Get-AZSCAccessibleTenant)
    if (-not $tenantId) { return $null }
    $tenantIds = @($tenantId)
    $allAccessibleTenantsAnswer = $false
    if ($accessibleTenants.Count -gt 1) {

        Write-Host ''
        Write-Host " This account can directly reach $($accessibleTenants.Count) tenants." -ForegroundColor DarkGray
        $tenantScope = Read-AZSCWizardChoice -Title 'How many tenants do you want to scan?' -Items @(
            [pscustomobject]@{ Label = "One tenant (choose next)";                      Value = 'Single' }
            [pscustomobject]@{ Label = 'Choose specific tenants from the list';                  Value = 'Select' }
            [pscustomobject]@{ Label = "Every accessible tenant ($($accessibleTenants.Count))";  Value = 'All' }
        )
        if ($null -eq $tenantScope) { return $null }

        if ($tenantScope -eq 'All') {
            $allAccessibleTenantsAnswer = $true
        }
        elseif ($tenantScope -eq 'Single') {
            $tenantId = Read-AZSCWizardChoice -Title 'Select the tenant to scan' -Items @(
                $accessibleTenants | ForEach-Object { [pscustomobject]@{ Label = "$($_.Name) ($($_.Id))"; Value = $_.Id } }
            )
            if (-not $tenantId) { return $null }
            $tenantIds = @($tenantId)
        }
        elseif ($tenantScope -eq 'Select') {
            Write-Host ''
            $tenantLabelMap = @{}
            $tenantLabels = @($accessibleTenants | ForEach-Object {
                $label = if ($_.Name) { "$($_.Name) ($($_.Id))" } else { $_.Id }
                $tenantLabelMap[$label] = $_.Id
                $label
            })
            $defaultLabel = @($tenantLabels | Where-Object { $tenantLabelMap[$_] -eq $tenantId })
            $chosenLabels = Read-AZSCWizardChecklist -Title 'Select the tenants to scan' -Items $tenantLabels -DefaultSelected $defaultLabel
            if ($null -eq $chosenLabels) { return $null }
            $tenantIds = @($chosenLabels | ForEach-Object { $tenantLabelMap[$_] })
            if ($tenantIds.Count -eq 0) { return $null }
            $tenantId = $tenantIds[0]
        }
    }

    # ── Step 2: permissions ──────────────────────────────────────────────────
    Write-AZSCWizardStep -Number 2 -Total 5 -Title 'Permissions'
    # The required Graph checks are unknowable until Step 3 establishes whether Entra was
    # selected. Running an ARM audit here and the selected-scope audit after confirmation made
    # every guided run enumerate subscriptions/providers twice. Defer the one authoritative
    # audit to Invoke-AzureScout after all answers are known (AB#7279).
    Write-Host ' Access will be validated once per tenant after you confirm the selected run scope.' -ForegroundColor DarkGray
    Write-Host ''

    $scopeAnswer = 'ArmOnly'

    # ── Step 3: what to run ──────────────────────────────────────────────────
    Write-AZSCWizardStep -Number 3 -Total 5 -Title 'What to run'

    $mode = Read-AZSCWizardChoice -Title 'Choose a run type' -Items @(
        [pscustomobject]@{ Label = 'Inventory — list everything in the tenant';                      Value = 'Inventory' }
        [pscustomobject]@{ Label = 'Assessment — score the tenant against CAF/WAF';                   Value = 'Assessment' }
        [pscustomobject]@{ Label = 'Both — inventory first, then the scored assessment';        Value = 'Both' }
    )
    if ($null -eq $mode) { return $null }

    Write-Host ''
    Write-Host ' Entra ID collection requires a separate Microsoft Graph token.' -ForegroundColor DarkGray
    if (Read-AZSCWizardConfirm -Prompt 'Also collect Entra ID data (users, groups, conditional access, etc.)?' -Default $false) {
        $scopeAnswer = 'All'
    }

    $answers = if ($allAccessibleTenantsAnswer) {
        @{ AllAccessibleTenants = [switch]$true }
    }
    else {
        @{ TenantID = if ($tenantIds.Count -gt 1) { $tenantIds } else { $tenantId } }
    }
    if ($scopeAnswer -eq 'All') { $answers.Scope = 'All' }
    $runBoth = ($mode -eq 'Both')
    $wantsInventory = ($mode -in @('Inventory', 'Both'))
    $wantsAssessment = ($mode -in @('Assessment', 'Both'))

    if ($wantsInventory) {
        Write-Host ''
        # AB#7101/AB#7102 -- label each category with its live collector coverage
        # (Collected/Published, from the manifest tree) instead of a bare name, and let the
        # operator drill into which specific collectors are behind that figure without leaving
        # the checklist. A coverage read failure (e.g. a packaging fault that hides the
        # manifest tree) degrades to bare names rather than blocking the step.
        $categoryLabels = @{}
        $categoryDetail = @{}
        try {
            foreach ($coverage in @(Get-ScoutCategoryCoverage -Category $inventoryCategories)) {
                $categoryLabels[$coverage.Category] = "$($coverage.Category) ($($coverage.Collected)/$($coverage.Published))"
                $categoryDetail[$coverage.Category] = @(@($coverage.Services) | ForEach-Object {
                    $status = if ($_.Collected) { 'collected' } else { 'NOT collected' }
                    "$($_.Name): $status"
                })
            }
        }
        catch { Write-Verbose "Start-AZSCWizard: could not compute category coverage, showing bare names: $_" }

        $categories = Read-AZSCWizardChecklist -Title 'Resource categories to inventory' -Items $inventoryCategories -ItemLabels $categoryLabels -ItemDetail $categoryDetail
        if ($null -eq $categories) { return $null }
        # All 15 selected is exactly what -Category All means — keep the command
        # line short and let the default sentinel through instead.
        $answers.Category = if ($categories.Count -eq $inventoryCategories.Count) { @('All') } else { $categories }

        Write-Host ''
        # Every item here changes what the run does. 'Quota usage' used to be listed, but
        # -QuotaUsage is read nowhere in the pipeline: VM quota is gathered on every run as part
        # of VM details, so the checkbox did nothing whether ticked or not (AB#7104). A menu item
        # that does nothing is removed rather than explained.
        # Network diagrams are on by default: they are a headline deliverable, and leaving the
        # box unticked silently added -SkipDiagram to every run that accepted the defaults.
        $extras = Read-AZSCWizardChecklist -Title 'Optional report and enrichment features' -Items @(
            'Include resource tags in reports', 'Security Center findings', 'Cost data', 'Network diagrams'
        ) -DefaultSelected @('Include resource tags in reports', 'Network diagrams')
        if ($null -eq $extras) { return $null }
        if ($extras -contains 'Include resource tags in reports') { $answers.IncludeTags = [switch]$true }
        if ($extras -contains 'Security Center findings')  { $answers.SecurityCenter = [switch]$true }
        if ($extras -contains 'Cost data') {
            # Cost data silently comes back empty later in the run if Az.CostManagement isn't
            # installed -- catch that here, at the point of choice, instead. Scout never installs
            # Az modules automatically (a past Az.Accounts version conflict bricked module import),
            # so any install is an explicit, user-confirmed action. See ADO Task 6738.
            if (-not (Get-Module -ListAvailable -Name Az.CostManagement)) {
                Write-Host ''
                Write-Host ' Cost data requires the Az.CostManagement module, which is not installed.' -ForegroundColor Yellow
                if (Read-AZSCWizardConfirm -Prompt 'Install Az.CostManagement now (CurrentUser scope)?' -Default $true) {
                    try {
                        Install-Module -Name Az.CostManagement -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop
                        Write-Host ' Installed Az.CostManagement.' -ForegroundColor Green
                        $answers.IncludeCosts = [switch]$true
                    }
                    catch {
                        Write-Host " Install failed: $_ -- continuing without cost data." -ForegroundColor Red
                    }
                }
                else {
                    Write-Host ' Continuing without cost data.' -ForegroundColor DarkGray
                }
            }
            else {
                $answers.IncludeCosts = [switch]$true
            }
        }
        if ($extras -notcontains 'Network diagrams')       { $answers.SkipDiagram = [switch]$true }
    }

    if ($wantsAssessment) {
        Write-Host ''
        # $PSScriptRoot is <module>/src, so the manifest is ONE level up. It used to climb three,
        # which lands outside the repository entirely -- the path never existed, the try block
        # never ran, and the wizard silently offered a hard-coded list of one assessment on every
        # release. Found while adding the SMART entry below (AB#6832).
        $moduleRoot = Split-Path $PSScriptRoot -Parent
        $manifestPath = Join-Path $moduleRoot 'manifests/assessments.psd1'
        $assessmentNames = @('CAF: Azure Landing Zone')
        $assessmentManifest = $null
        if (Test-Path $manifestPath) {
            try {
                $assessmentManifest = Import-PowerShellDataFile $manifestPath
                # AB#6763 -- the menu lists only what Scout can actually run: an entry with no
                # rule file behind it runs and returns nothing, which reads as "no findings".
                # ('Estate' used to be the example that motivated this — it declared Rules = @()
                # and scored nothing. AB#6795 removed it from the registry entirely rather than
                # leaving it to this gate to hide, because a full-inventory pull is a different
                # product from an assessment, not a broken one.)
                $assessmentNames = @(Get-ScoutAvailableAssessment -Manifest $assessmentManifest)
                if ($assessmentNames.Count -eq 0) {
                    Write-Warning 'Start-AZSCWizard: no assessment has rules behind it — offering ''CAF: Azure Landing Zone'' only.'
                    $assessmentNames = @('CAF: Azure Landing Zone')
                }
            }
            catch { Write-Verbose "Start-AZSCWizard: could not read the assessment manifest, falling back to 'CAF: Azure Landing Zone': $_" }
        }
        else {
            # AB#6754 -- this used to be reached on every run, because the path climbed three
            # directory levels to a file one level up. Test-Path returned false, the fallback
            # ran, and the wizard offered a hard-coded list of one. It was silent, so nobody
            # noticed for several releases. It is a warning now: reaching it means the module
            # layout is wrong, and the operator should see a short menu explained rather than a
            # short menu asserted.
            Write-Warning "Start-AZSCWizard: the assessment registry was not found at '$manifestPath' — offering 'CAF: Azure Landing Zone' only. This is a packaging fault, not an empty catalogue."
        }

        # An assessment declaring RequiresData is hidden until the data it scores actually exists
        # (AB#6832). SMART is the case that forced this: an estate with no Azure Migrate project
        # has nothing for it to read, and offering it there invites a score built on nothing.
        # The check reads the most recent collect.json this machine produced; with none, the entry
        # stays hidden, which is the safe direction. `Invoke-Assessment` enforces the same
        # prerequisite independently, so a user naming -Assessment SMART explicitly still gets an
        # honest Unknown rather than a fabricated pass.
        if ($assessmentManifest) {
            # Look where runs are actually written. This used to search only
            # Documents\AzureScout, but the wizard's own default report directory is
            # C:\AzureScout on Windows and ~/AzureScout elsewhere, so on a default install the
            # search found nothing and every data-gated assessment stayed hidden for good.
            $latestCollect = $null
            try {
                $collectRoots = @(
                    $(if ($IsWindows) { 'C:\AzureScout' } else { Join-Path "$HOME" 'AzureScout' })
                    (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'AzureScout')
                ) | Where-Object { $_ -and (Test-Path -LiteralPath $_ -PathType Container) } | Select-Object -Unique
                $latestCollect = $collectRoots | ForEach-Object {
                    Get-ChildItem -LiteralPath $_ -Filter 'collect.json' -Recurse -File -ErrorAction SilentlyContinue
                } | Sort-Object LastWriteTime -Descending | Select-Object -First 1
            }
            catch { $latestCollect = $null }

            $assessmentNames = @(Select-AZSCWizardDataGatedAssessment -Names $assessmentNames -Manifest $assessmentManifest -CollectPath $(if ($latestCollect) { $latestCollect.FullName }))
        }
        # AB#7188 — presentation only. The 40+ entry flat menu mixed three naming
        # generations with no visible structure; group by source framework instead.
        # Registry keys and the returned selection are untouched — grouping changes
        # what the operator SEES, never what the checklist RETURNS.
        $assessmentGroups = Group-AZSCWizardAssessment -Names $assessmentNames
        $chosen = Read-AZSCWizardChecklist -Title 'Assessments to run' -Groups $assessmentGroups -DefaultSelected @('CAF: Azure Landing Zone')
        if ($null -eq $chosen) { return $null }
        $answers.Assessment = $chosen
    }

    # ── Step 4: output ───────────────────────────────────────────────────────
    Write-AZSCWizardStep -Number 4 -Total 5 -Title 'Output'

    $formatPool = $liveFormats
    $defaultFormats = @('React')
    $formats = Read-AZSCWizardChecklist -Title 'Report formats' -Items $formatPool -DefaultSelected $defaultFormats
    if ($null -eq $formats) { return $null }
    $answers.OutputFormat = $formats

    # Build the fallback folder based on OS
    if ($IsWindows) {
        $defaultDir = 'C:\AzureScout'
    } else {
        $defaultDir = Join-Path "$HOME" 'AzureScout'
    }
    $dir = Read-AZSCWizardText -Prompt 'Report directory' -Default $defaultDir
    if ($dir) { $answers.ReportDir = $dir }

    # AB#6930 -- report identity, wizard parity with -ReportIdentity. Asked whenever the React
    # report will be produced: the identity block is that report's cover/header. Inventory-only
    # runs render the React report too (they have since 3.11.0), so gating this on an assessment
    # left every inventory report with a blank client name and no way to set one from the menu.
    # Every prompt defaults to blank (Enter accepts it), and a blank answer is simply never
    # added to the hashtable -- Export-React's own neutral defaults
    # (Get-ScoutReportIdentityDefault) fill anything the operator skipped, so this step can be
    # skipped in full with four Enters and the report still reads as neutral, never as this
    # product's own name.
    if ($formats -contains 'React') {
        Write-Host ''
        Write-Host ' Report identity (optional -- blank uses a neutral default; Enter to skip)' -ForegroundColor White
        $reportIdentity = @{}
        $clientName = Read-AZSCWizardText -Prompt ' Client / organization name' -Default ''
        if ($clientName) { $reportIdentity.clientName = $clientName }
        $engagementName = Read-AZSCWizardText -Prompt ' Engagement name' -Default ''
        if ($engagementName) { $reportIdentity.engagementName = $engagementName }
        $classification = Read-AZSCWizardText -Prompt ' Classification banner' -Default ''
        if ($classification) { $reportIdentity.classification = $classification }
        $preparedBy = Read-AZSCWizardText -Prompt ' Prepared by' -Default ''
        if ($preparedBy) { $reportIdentity.preparedBy = $preparedBy }
        if ($reportIdentity.Count -gt 0) { $answers.ReportIdentity = $reportIdentity }
    }

    # ── Step 5: confirm ──────────────────────────────────────────────────────
    Write-AZSCWizardStep -Number 5 -Total 5 -Title 'Confirm'
    Write-Host ' Equivalent command:' -ForegroundColor DarkGray
    Write-Host ''
    Write-Host " $(Format-AZSCWizardCommand -Answers $answers)" -ForegroundColor Cyan
    Write-Host ''
    Write-Host ' Save that line to skip the wizard next time.' -ForegroundColor DarkGray
    Write-Host ''

    if (-not (Read-AZSCWizardConfirm -Prompt 'Start the run?' -Default $true)) { return $null }
    Write-Host ''

    return @{ Answers = $answers; RunBoth = $runBoth }
}

<#
.SYNOPSIS
    Returns $true when the current host can safely prompt the operator.
 
.DESCRIPTION
    Guards the wizard. A prompt in a non-interactive host hangs the process
    forever, which would break every CI job, scheduled task, and container that
    calls Invoke-AzureScout with no arguments — so this returns $false unless
    the session is genuinely interactive.
 
    Checked, in order: the -NonInteractive host switch, redirected stdin, an
    explicit CI environment variable, and finally [Environment]::UserInteractive.
#>

function Test-AZSCInteractiveHost {
    [CmdletBinding()]
    [OutputType([bool])]
    param()

    # PowerShell launched with -NonInteractive.
    if ($null -ne $Host.UI -and $null -ne $Host.UI.RawUI) {
        try { if (-not [Environment]::UserInteractive) { return $false } }
        catch { return $false }
    }
    else { return $false }

    # stdin redirected from a file or pipe — no operator on the other end.
    try { if ([Console]::IsInputRedirected) { return $false } }
    catch { Write-Verbose "Test-AZSCInteractiveHost: console stdin state unavailable in this host, continuing: $_" }

    # Common CI signals. Any of these means an automated runner, not a person.
    foreach ($var in @('CI', 'TF_BUILD', 'GITHUB_ACTIONS', 'JENKINS_URL', 'SYSTEM_TEAMPROJECTID')) {
        if (-not [string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($var))) { return $false }
    }

    return $true
}

# ── Wizard UI primitives ─────────────────────────────────────────────────────
# Small, dependency-free console helpers. Kept private to the module (they are
# not exported) so they can change shape without breaking anyone's script.

function Write-AZSCWizardBanner {
    Write-Host ''
    Write-Host ' ╭────────────────────────────────────────────────────────╮' -ForegroundColor Cyan
    Write-Host ' │ Azure Scout — guided setup │' -ForegroundColor Cyan
    Write-Host ' │ Press Enter to accept the default shown in [brackets] │' -ForegroundColor Cyan
    Write-Host ' ╰────────────────────────────────────────────────────────╯' -ForegroundColor Cyan
}

function Write-AZSCWizardStep {
    param([int]$Number, [int]$Total, [string]$Title)
    Write-Host ''
    Write-Host " Step $Number/$Total — $Title" -ForegroundColor White
    Write-Host " $('─' * 56)" -ForegroundColor DarkGray
}

function Read-AZSCWizardConfirm {
    param([string]$Prompt, [bool]$Default = $true)
    $hint = if ($Default) { 'Y/n' } else { 'y/N' }
    while ($true) {
        $raw = (Read-Host " $Prompt [$hint]").Trim()
        if ([string]::IsNullOrWhiteSpace($raw)) { return $Default }
        switch -Regex ($raw) {
            '^(y|yes)$' { return $true }
            '^(n|no)$'  { return $false }
            default     { Write-Host ' Enter y or n.' -ForegroundColor Yellow }
        }
    }
}

function Read-AZSCWizardText {
    param([string]$Prompt, [string]$Default)
    $raw = (Read-Host " $Prompt [$Default]").Trim()
    if ([string]::IsNullOrWhiteSpace($raw)) { return $Default }
    return $raw
}

<#
.SYNOPSIS
    Single-select menu. Returns the chosen item's Value, or $null if cancelled.
#>

function Read-AZSCWizardChoice {
    param([string]$Title, [object[]]$Items)

    Write-Host ''
    Write-Host " $Title" -ForegroundColor White
    for ($i = 0; $i -lt $Items.Count; $i++) {
        Write-Host (" {0}. {1}" -f ($i + 1), $Items[$i].Label)
    }
    Write-Host ''

    while ($true) {
        $raw = (Read-Host ' Selection (number, or q to quit)').Trim()
        if ($raw -match '^(q|quit)$') { return $null }
        if ([string]::IsNullOrWhiteSpace($raw)) { $raw = '1' }
        $n = 0
        if ([int]::TryParse($raw, [ref]$n) -and $n -ge 1 -and $n -le $Items.Count) {
            return $Items[$n - 1].Value
        }
        Write-Host " Enter a number between 1 and $($Items.Count)." -ForegroundColor Yellow
    }
}

<#
.SYNOPSIS
    Keep the assessments whose RequiresData gate is met by the newest collect.json.
 
.DESCRIPTION
    An assessment that declares RequiresData is offered only when one of its JSONPath gates finds
    rows in the newest collect.json on this machine (AB#6832). With no file, gated entries stay
    hidden. Ungated entries are always kept.
 
    The file is parsed ONCE, straight into a Newtonsoft token, and every gate queries that token.
    This used to ConvertFrom-Json the file and then call Resolve-JsonPath once per gate, and
    Resolve-JsonPath converts its input back to JSON text and re-parses it on every call without a
    shared query context. On a 28 MB collect.json each gate cost about 5 seconds and the eight gates
    in the registry cost about 40 seconds: the pause operators saw after the "Optional report and
    enrichment features" checklist, before the assessment list appeared.
#>

function Select-AZSCWizardDataGatedAssessment {
    param(
        [string[]] $Names,
        [hashtable] $Manifest,
        [AllowNull()] [AllowEmptyString()] [string] $CollectPath
    )

    $token = $null
    if (-not [string]::IsNullOrWhiteSpace($CollectPath) -and (Test-Path -LiteralPath $CollectPath -PathType Leaf)) {
        try { $token = [Newtonsoft.Json.Linq.JToken]::Parse([System.IO.File]::ReadAllText($CollectPath)) }
        catch { Write-Verbose "Select-AZSCWizardDataGatedAssessment: could not parse '$CollectPath'; data-gated assessments stay hidden: $($_.Exception.Message)" }
    }

    foreach ($name in @($Names)) {
        $entry = $Manifest[$name]
        if ($null -eq $entry -or $entry -isnot [hashtable] -or -not $entry.ContainsKey('RequiresData')) { $name; continue }
        if ($null -eq $token) { continue }
        foreach ($path in @($entry.RequiresData)) {
            try {
                if (@($token.SelectTokens($path, $false)).Count -gt 0) { $name; break }
            }
            catch { Write-Debug "RequiresData path '$path' could not be resolved: $($_.Exception.Message)" }
        }
    }
}

<#
.SYNOPSIS
    Sorts assessment registry keys into the wizard's four display groups.
 
.DESCRIPTION
    AB#7188 — presentation-only grouping for the assessment checklist. Every key
    lands in exactly one group, decided by its prefix:
 
        CAF:* → Cloud Adoption Framework (CAF)
        WAF:* → Well-Architected Framework (WAF)
        Assess:* → Service category deep-dives
        (anything else, including future/unknown keys) → Specialized reviews
 
    Unknown keys fall into Specialized reviews rather than disappearing — the
    wizard must never hide an assessment the registry offers (AB#6763). The keys
    themselves are returned verbatim inside the group arrays; nothing is renamed.
 
.OUTPUTS
    An ordered dictionary of heading → string[] of registry keys, in the fixed
    display order CAF, WAF, Specialized reviews, Service category deep-dives.
#>

function Group-AZSCWizardAssessment {
    param([string[]]$Names)

    $groups = [ordered]@{
        'Cloud Adoption Framework (CAF)'   = [System.Collections.Generic.List[string]]::new()
        'Well-Architected Framework (WAF)' = [System.Collections.Generic.List[string]]::new()
        'Specialized reviews'              = [System.Collections.Generic.List[string]]::new()
        'Service category deep-dives'      = [System.Collections.Generic.List[string]]::new()
    }
    foreach ($name in @($Names)) {
        if ([string]::IsNullOrWhiteSpace($name)) { continue }
        $heading = switch -Wildcard ($name) {
            'CAF:*'    { 'Cloud Adoption Framework (CAF)'; break }
            'WAF:*'    { 'Well-Architected Framework (WAF)'; break }
            'Assess:*' { 'Service category deep-dives'; break }
            default    { 'Specialized reviews' }
        }
        $groups[$heading].Add($name)
    }
    $result = [ordered]@{}
    foreach ($key in $groups.Keys) { $result[$key] = @($groups[$key]) }
    return $result
}

<#
.SYNOPSIS
    Multi-select checklist. Everything is selected by default; the operator
    unchecks what they don't want. Returns the selected items, or $null if
    cancelled.
 
.DESCRIPTION
    Pass -Groups (an ordered dictionary of heading → item array) instead of
    -Items to render non-selectable heading lines between item runs (AB#7188).
    Numbering stays continuous across groups and toggling/select-all/return
    values are identical to the flat form — the items ARE the flattened groups,
    in group order. Empty groups render nothing.
 
    Pass -ItemLabels (item → display string) to show something richer than the
    bare item next to its checkbox -- e.g. a category's collector coverage,
    "Analytics (12/12)" (AB#7101) -- without changing what gets toggled,
    counted, or returned: selection and the answer hashtable always deal in
    the plain item names.
 
    Pass -ItemDetail (item → string[] of detail lines) to let the operator type
    `i<n>` and see those lines inline -- e.g. which collectors in a category
    are/aren't working -- without leaving the checklist. Omit it and the `i`
    command is simply not offered.
#>

function Read-AZSCWizardChecklist {
    param(
        [string]$Title,
        [string[]]$Items,
        [string[]]$DefaultSelected,
        [System.Collections.Specialized.OrderedDictionary]$Groups,
        [hashtable]$ItemLabels,
        [hashtable]$ItemDetail
    )

    if ($null -ne $Groups) {
        # The flat item list is derived from the groups, so every existing code
        # path (numbering, toggling, all/none, the returned selection) operates
        # on exactly the same array the grouped render displays.
        $Items = @(foreach ($heading in $Groups.Keys) { @($Groups[$heading]) | Where-Object { $_ } })
    }

    $selected = [System.Collections.Generic.HashSet[string]]::new()
    $initial = if ($PSBoundParameters.ContainsKey('DefaultSelected')) { $DefaultSelected } else { $Items }
    foreach ($item in $initial) { [void]$selected.Add($item) }

    $writeItemLine = {
        param([int]$Index)
        $mark = if ($selected.Contains($Items[$Index])) { 'x' } else { ' ' }
        $colour = if ($selected.Contains($Items[$Index])) { 'Green' } else { 'DarkGray' }
        $label = $Items[$Index]
        if ($ItemLabels -and $ItemLabels.ContainsKey($label)) { $label = $ItemLabels[$label] }
        Write-Host (" [{0}] {1,2}. {2}" -f $mark, ($Index + 1), $label) -ForegroundColor $colour
    }

    while ($true) {
        Write-Host ''
        Write-Host " $Title" -ForegroundColor White
        if ($null -ne $Groups) {
            $i = 0
            foreach ($heading in $Groups.Keys) {
                $groupItems = @(@($Groups[$heading]) | Where-Object { $_ })
                if ($groupItems.Count -eq 0) { continue }
                Write-Host ''
                Write-Host " ── $heading ──" -ForegroundColor Cyan
                for ($j = 0; $j -lt $groupItems.Count; $j++) { & $writeItemLine -Index $i; $i++ }
            }
        }
        else {
            for ($i = 0; $i -lt $Items.Count; $i++) { & $writeItemLine -Index $i }
        }
        Write-Host ''
        Write-Host ' Toggle with numbers (e.g. "3" or "3,5,9"), a = all, n = none,' -ForegroundColor DarkGray
        if ($ItemDetail) {
            Write-Host ' i<n> = detail on an item (e.g. "i3"), Enter = accept, q = quit' -ForegroundColor DarkGray
        } else {
            Write-Host ' Enter = accept, q = quit' -ForegroundColor DarkGray
        }

        $raw = (Read-Host ' >').Trim()

        if ([string]::IsNullOrWhiteSpace($raw)) {
            if ($selected.Count -eq 0) {
                Write-Host ' Select at least one item.' -ForegroundColor Yellow
                continue
            }
            # Preserve the caller's original ordering rather than hash order.
            return @($Items | Where-Object { $selected.Contains($_) })
        }
        if ($raw -match '^(q|quit)$') { return $null }
        if ($raw -match '^a(ll)?$')   { foreach ($item in $Items) { [void]$selected.Add($item) }; continue }
        if ($raw -match '^n(one)?$')  { $selected.Clear(); continue }
        if ($ItemDetail -and $raw -match '^i\s*(\d+)$') {
            $n = [int]$Matches[1]
            if ($n -ge 1 -and $n -le $Items.Count) {
                $item = $Items[$n - 1]
                Write-Host ''
                Write-Host " $item detail:" -ForegroundColor White
                if ($ItemDetail.ContainsKey($item) -and @($ItemDetail[$item]).Count -gt 0) {
                    foreach ($line in @($ItemDetail[$item])) { Write-Host " $line" -ForegroundColor DarkGray }
                } else {
                    Write-Host ' (no detail available)' -ForegroundColor DarkGray
                }
            } else {
                Write-Host " Enter a number between 1 and $($Items.Count)." -ForegroundColor Yellow
            }
            continue
        }

        foreach ($token in ($raw -split '[,\s]+' | Where-Object { $_ })) {
            $n = 0
            if ([int]::TryParse($token, [ref]$n) -and $n -ge 1 -and $n -le $Items.Count) {
                $item = $Items[$n - 1]
                if ($selected.Contains($item)) { [void]$selected.Remove($item) } else { [void]$selected.Add($item) }
            }
            else {
                Write-Host " Ignored '$token' — not a number between 1 and $($Items.Count)." -ForegroundColor Yellow
            }
        }
    }
}

<#
.SYNOPSIS
    Renders the wizard's answers as the equivalent Invoke-AzureScout command so
    the operator can copy it into a script and skip the wizard next time.
#>

function Format-AZSCWizardCommand {
    param([hashtable]$Answers)

    $parts = [System.Collections.Generic.List[string]]::new()
    $parts.Add('Invoke-AzureScout')
    foreach ($key in ($Answers.Keys | Sort-Object)) {
        $value = $Answers[$key]
        if ($value -is [switch] -or $value -is [bool]) {
            if ($value) { $parts.Add("-$key") }
        }
        elseif ($value -is [hashtable]) {
            # AB#6930 -- -ReportIdentity. Too free-form to inline as command-line syntax (values
            # commonly contain spaces/punctuation); name it and point at the wizard instead of
            # emitting something that would not actually parse if pasted back in.
            if ($value.Count -gt 0) { $parts.Add("-$key <see wizard prompts -- re-run the wizard to set this>") }
        }
        elseif ($value -is [array]) {
            $parts.Add("-$key $((@($value) | ForEach-Object { if ($_ -match '[\s]') { "'$_'" } else { $_ } }) -join ',')")
        }
        elseif ($value -match '\s') { $parts.Add("-$key '$value'") }
        else { $parts.Add("-$key $value") }
    }
    return ($parts -join ' ')
}