src/collect/Get-ScoutGovernanceReadSummary.ps1

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

# Issue #104. Did EVERY read of one governance dataset answer? A read that answered with no rows is an
# answer ("this subscription has no budget"); a read that threw, was denied or was throttled is not, and
# a dataset built from 39 of 42 subscriptions must not be scored as if it were the whole estate -- a rule
# that passes on "no policy exemption was found" would pass on 39/42nds of the data.
#
# Returns the flag and the sentence that goes next to it in collect.json. COUNTS ONLY: how many scopes
# were asked, how many did not answer, and the HTTP status classes -- never a subscription name or id.
# Shared by the raw pass (Get-ScoutGovernanceDataset) and the typed path (Import-Governance) so both
# write the same flag for the same facts.
function Get-ScoutGovernanceReadSummary {
    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        [Parameter(Mandatory)] [string] $Label,
        [Parameter(Mandatory)] [string] $Unit,
        [int] $Asked,
        [int] $Failed,
        [string[]] $StatusCode = @(),
        [string] $NothingAskedReason
    )
    $answered = [Math]::Max(0, $Asked - $Failed)
    $available = ($Asked -gt 0) -and ($Failed -eq 0)
    $reason = $null
    if (-not $available) {
        if ($Asked -eq 0) {
            $reason = if ($NothingAskedReason) { $NothingAskedReason } else { "$Label was not read: there was nothing to ask." }
        }
        else {
            $codes = @($StatusCode | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique | Sort-Object)
            $codeText = if ($codes.Count -gt 0) { " (HTTP $($codes -join ', '))" } else { '' }
            $reason = "$Label was read for $answered of $Asked $Unit; $Failed did not answer$codeText. Checks that need the whole set read Not assessed."
        }
    }
    [pscustomobject]@{
        Label = $Label; Asked = $Asked; Answered = $answered; Failed = $Failed
        Available = $available; Reason = $reason
    }
}