src/report/renderers/inventory/Export-AZSCAsciiDocReport.ps1

<#
.Synopsis
Export inventory data as a structured AsciiDoc report
 
.DESCRIPTION
Reads all cache files produced by the processing phase and assembles them into
a single AsciiDoc document. Each category becomes a level-1 section and each
module's data is rendered as an AsciiDoc table. Includes AsciiDoc admonition
blocks ([TIP], [NOTE], [WARNING]) for recommendations. Suitable for Antora,
Confluence, and any AsciiDoc-capable documentation system.
 
.Link
https://github.com/thisismydemo/azure-scout/Modules/Private/Reporting/Export-AZSCAsciiDocReport.ps1
 
.COMPONENT
This PowerShell Module is part of Azure Scout (AZSC)
 
.NOTES
Version: 1.0.0
First Release Date: February 24, 2026
Authors: AzureScout Contributors
#>


function Export-AZSCAsciiDocReport {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$ReportCache,

        [Parameter(Mandatory)]
        [string]$File,

        [Parameter()]
        [string]$TenantID,

        [Parameter()]
        [object]$Subscriptions,

        [Parameter()]
        [ValidateSet('All', 'ArmOnly', 'EntraOnly')]
        [string]$Scope = 'All',

        [Parameter()]
        [string]$DefinitionRoot = (Join-Path (Join-Path ((Get-Item $PSScriptRoot).Parent.Parent.Parent.Parent.FullName) 'manifests') 'collectors')
    )

    $AdocFile = [System.IO.Path]::ChangeExtension($File, '.adoc')
    Write-Debug ((Get-Date -Format 'yyyy-MM-dd_HH_mm_ss') + " - AsciiDoc output file: $AdocFile")

    $subCount = if ($Subscriptions) { @($Subscriptions).Count } else { 0 }
    $genDate  = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'

    $lines = [System.Collections.Generic.List[string]]::new()

    # ── Document header ──────────────────────────────────────────────────
    $lines.Add('= Azure Scout Report')
    $lines.Add('AzureScout')
    $lines.Add(":toc: left")
    $lines.Add(":toc-title: Contents")
    $lines.Add(":toclevels: 3")
    $lines.Add(":icons: font")
    $lines.Add(":source-highlighter: highlight.js")
    $lines.Add(":docdate: $genDate")
    $lines.Add('')
    $lines.Add('[NOTE]')
    $lines.Add('====')
    $lines.Add("This report was auto-generated by *AzureScout* on `$genDate`.")
    $lines.Add('')
    $lines.Add("[horizontal]")
    $lines.Add("Tenant ID:: $TenantID")
    $lines.Add("Subscriptions:: $subCount")
    $lines.Add("Scope:: $Scope")
    $lines.Add('====')
    $lines.Add('')

    # Definitions are the report contract; cache keys are definition names.
    $SectionIndex = @(Get-ScoutReportSectionIndex -DefinitionRoot $DefinitionRoot)
    $CacheFiles = @(Get-ChildItem -Path $ReportCache -Recurse -Filter '*.json' -ErrorAction SilentlyContinue | Sort-Object FullName)
    $CacheByName = @{}
    foreach ($CacheFile in $CacheFiles) {
        if (-not $CacheByName.ContainsKey($CacheFile.Name)) { $CacheByName[$CacheFile.Name] = $CacheFile }
    }
    $ParsedCache = @{}

    $totalResources = 0
    $sectionLines   = [System.Collections.Generic.List[string]]::new()

    $CurrentCategory = $null
    foreach ($Section in $SectionIndex) {
        if ($Scope -eq 'ArmOnly' -and $Section.Category -eq 'Identity') { continue }
        if ($Scope -eq 'EntraOnly' -and $Section.Category -ne 'Identity') { continue }
        if (-not $CacheByName.ContainsKey($Section.CacheFileName)) { continue }
        if (-not $ParsedCache.ContainsKey($Section.CacheFileName)) {
            $RawJson = [System.IO.File]::ReadAllText($CacheByName[$Section.CacheFileName].FullName)
            if ([string]::IsNullOrWhiteSpace($RawJson)) { continue }
            $ParsedCache[$Section.CacheFileName] = $RawJson | ConvertFrom-Json
        }

        $CacheData = $ParsedCache[$Section.CacheFileName]
        $CacheProperty = $CacheData.PSObject.Properties[$Section.CacheKey]
        $ModResources = if ($CacheProperty) { $CacheProperty.Value } else { $null }
        if (-not $ModResources -or @($ModResources).Count -eq 0) { continue }

        $rows = @($ModResources)
        $totalResources += $rows.Count
        if ($CurrentCategory -ne $Section.Category) {
            $CurrentCategory = $Section.Category
            $sectionLines.Add("== $CurrentCategory")
            $sectionLines.Add('')
        }

        $sectionLines.Add("=== $($Section.Name)")
        $sectionLines.Add('')
        $sectionLines.Add('[TIP]')
        $sectionLines.Add('====')
        $sectionLines.Add("$($rows.Count) resource(s) found in this module.")
        $sectionLines.Add('====')
        $sectionLines.Add('')

        # Build AsciiDoc table
        $props = $rows[0].PSObject.Properties.Name | Where-Object { $_ -notmatch 'Tag (Name|Value)|Resource U' }
        if (@($props).Count -gt 0) {
            $colSpec = ($props | ForEach-Object { '1' }) -join ','
            $sectionLines.Add("[%header,cols=""$colSpec""]")
            $sectionLines.Add('|===')
            $sectionLines.Add(($props | ForEach-Object { "| $_" }) -join ' ')
            foreach ($row in $rows) {
                $cells = $props | ForEach-Object {
                    $v = $row.$_
                    if ($null -eq $v) { '' }
                    else { [string]$v -replace '\|', '{vbar}' -replace '\r?\n', ' +' }
                }
                $sectionLines.Add(($cells | ForEach-Object { "| $_" }) -join ' ')
            }
            $sectionLines.Add('|===')
        }
        $sectionLines.Add('')
    }

    $lines.Add("_Total resources inventoried: *$totalResources*_")
    $lines.Add('')
    foreach ($l in $sectionLines) { $lines.Add($l) }

    # ── Footer ────────────────────────────────────────────────────────────
    $lines.Add("'''")
    $lines.Add('')
    $lines.Add("[NOTE]")
    $lines.Add('====')
    $lines.Add("Generated by link:https://github.com/thisismydemo/azure-scout[AzureScout] at $genDate")
    $lines.Add('====')

    try {
        $lines | Out-File -FilePath $AdocFile -Encoding UTF8 -Force
        Write-Host "AsciiDoc report saved to: " -ForegroundColor Green -NoNewline
        Write-Host $AdocFile -ForegroundColor Cyan
    }
    catch {
        Write-Warning "Failed to write AsciiDoc report to '$AdocFile': $_"
    }

    return $AdocFile
}