Private/Read-RaidinessIntakeAnswer.ps1

<#
    Reading answers back, from any of the shapes they arrive in.

    Three, because three are genuinely useful: the JSON questionnaire
    Get-RaidinessIntake writes, the CSV a consultant fills in with the customer,
    and a plain {key: answer} object -- which is what the Node CLI's --intake
    already takes, so the two front doors accept the same file.
#>

function Read-RaidinessIntakeAnswer {
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        # A questionnaire file, an intake envelope, or a run folder holding one.
        [Parameter(Mandatory = $true)]
        [string] $Path
    )

    $ErrorActionPreference = 'Stop'

    $file = $Path
    if (Test-Path -Path $Path -PathType Container) {
        $candidates = @(
            (Join-Path $Path 'data' 'raidiness-intake.json')
            (Join-Path $Path 'raidiness-intake.json')
            (Join-Path $Path 'intake.json')
        )
        $file = $candidates | Where-Object { Test-Path -Path $_ } | Select-Object -First 1
        if (-not $file) { throw "No intake file found in $Path." }
    }
    if (-not (Test-Path -Path $file)) { throw "No intake file at $file." }

    $answers = @{}

    if ([System.IO.Path]::GetExtension($file) -eq '.csv') {
        foreach ($row in Import-Csv -Path $file) {
            if (-not $row.PSObject.Properties['Key']) { throw "$file has no Key column; it is not a Raidiness questionnaire." }
            $value = $row.PSObject.Properties['Answer'] ? $row.Answer : $null
            if ($null -ne $value -and "$value".Trim() -ne '') { $answers[$row.Key] = "$value".Trim() }
        }
        return $answers
    }

    $parsed = Get-Content -Path $file -Raw | ConvertFrom-Json

    # The questionnaire and the envelope both keep answers under `answers`; a
    # bare {key: answer} object is the whole document.
    $source = $parsed.PSObject.Properties['answers'] ? $parsed.answers : $parsed
    foreach ($property in $source.PSObject.Properties) {
        if ($property.Name -in 'raidinessIntake', 'questions') { continue }
        $value = $property.Value
        if ($null -eq $value) { continue }
        if ($value -is [string] -and $value.Trim() -eq '') { continue }
        $answers[$property.Name] = $value
    }

    $answers
}