Private/Export-BridgeStatusJson.ps1

<#
.SYNOPSIS
Υπολογίζει το ενεργό βάθος σειριοποίησης JSON από τις παραμέτρους και τις ρυθμίσεις.

.DESCRIPTION
Χρησιμοποιεί το ρητό βάθος JSON όταν δίνεται, αλλιώς διαβάζει την προεπιλογή από τη διαμόρφωση.

.PARAMETER JsonDepth
Ρητό βάθος σειριοποίησης JSON, όταν δίνεται.

.PARAMETER Configuration
Η διαμόρφωση που παρέχει το προεπιλεγμένο βάθος JSON.
#>

function Get-BridgeExportJsonDepth {
    param (
        [Parameter()][int]$JsonDepth,
        [Parameter(Mandatory)][ValidateNotNull()][PSCustomObject]$Configuration
    )
    $configJsonDepthProp = $Configuration.Defaults.PSObject.Properties['JsonDepth']
    $configJsonDepth = if ($null -ne $configJsonDepthProp) { $configJsonDepthProp.Value } else { 0 }
    return (@($JsonDepth, $configJsonDepth, 10) | Where-Object -FilterScript { $_ -gt 0 } | Select-Object -First 1)
}

<#
.SYNOPSIS
Εγγράφει περιεχόμενο JSON ατομικά μέσω προσωρινού αρχείου.

.DESCRIPTION
Γράφει το JSON σε προσωρινό αρχείο δίπλα στον προορισμό πριν το δημοσιεύσει με μετακίνηση. Καθαρίζει το προσωρινό αρχείο μετά την προσπάθεια.

.PARAMETER Path
Η διαδρομή του τελικού αρχείου JSON.

.PARAMETER JsonContent
Το σειριοποιημένο περιεχόμενο που θα γραφτεί στο αρχείο.
#>

function Write-BridgeAtomicJson {
    param (
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Path,
        [Parameter()][AllowNull()][object]$JsonContent
    )
    $destination = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
    $tmpPath = "$destination.$([guid]::NewGuid().ToString('N')).tmp"
    try {
        Set-Content -LiteralPath $tmpPath -Value $JsonContent -Encoding UTF8 -Force -ErrorAction Stop
        Move-Item -LiteralPath $tmpPath -Destination $destination -Force -ErrorAction Stop
    }
    finally {
        if (Test-Path -LiteralPath $tmpPath) {
            Remove-Item -LiteralPath $tmpPath -Force -ErrorAction SilentlyContinue
        }
    }
}

<#
.SYNOPSIS
Writes an export log message without aborting snapshot persistence or structured error returns.

.DESCRIPTION
Calls Write-BridgeLog and converts log-write exceptions into warnings so callers receive the export outcome.

.PARAMETER Stage
The logging stage name.

.PARAMETER Message
The log message to write.

.PARAMETER Level
The logging level to use.

.PARAMETER Configuration
The BridgeWatcher configuration object.
#>

function Write-BridgeExportLogSafe {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Stage,
        [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Message,
        [Parameter()][ValidateSet('Verbose', 'Debug', 'Warning')][string]$Level = 'Verbose',
        [Parameter(Mandatory)][ValidateNotNull()][PSCustomObject]$Configuration
    )
    $appendFailure = $null
    try {
        Write-BridgeLog -Stage $Stage -Message $Message -Level $Level -Configuration $Configuration -ErrorAction Stop
    } catch {
        $appendFailure = $_
    }
    if ($null -ne $appendFailure) {
        Write-Warning -Message "Export log write failed: $($appendFailure.Exception.Message)" -WarningAction Continue
    }
}

<#
.SYNOPSIS
Εξάγει την κατάσταση γέφυρας σε αρχείο JSON.

.DESCRIPTION
Η Export-BridgeStatusJson αποθηκεύει δεδομένα κατάστασης γέφυρας σε μορφή JSON
σε καθορισμένη διαδρομή.

.PARAMETER Data
Το αντικείμενο ή η λίστα αντικειμένων που θα εξαχθεί.

.PARAMETER Path
Η πλήρης διαδρομή του αρχείου εξόδου.

.PARAMETER JsonDepth
Το βάθος σειριοποίησης (serialization) του JSON.

.PARAMETER Configuration
Το αντικείμενο διαμόρφωσης που περιέχει τις ρυθμίσεις.

.OUTPUTS
[PSCustomObject] - Αντικείμενο αποτελέσματος.
#>

function Export-BridgeStatusJson {
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([PSCustomObject])]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [object]$Data,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Path,

        [Parameter()]
        [int]$JsonDepth,

        [Parameter(Mandatory)][ValidateNotNull()][PSCustomObject]$Configuration
    )

    begin {
        $items = [System.Collections.Generic.List[object]]::new()
        $resolvedDepth = Get-BridgeExportJsonDepth -JsonDepth $JsonDepth -Configuration $Configuration

        $successMessage = $Configuration.ExportMessages.Success
        $failedMessage = $Configuration.ExportMessages.Failed
        $directoryNotExistsMessage = $Configuration.ExportMessages.DirectoryNotExists
        $analysisStage = $Configuration.LoggingConfig.InfoStage
        $errorStage = $Configuration.LoggingConfig.ErrorStage
    }

    process {
        $isEmptyCollection = ($Data -is [System.Collections.IEnumerable]) -and ($Data -isnot [string]) -and ($Data.Count -eq 0)
        if ($null -ne $Data -and -not $isEmptyCollection) {
            $items.Add($Data)
        }
    }

    end {
        try {
            $dataToExport = if ($items.Count -eq 1) { $items[0] } else { $items.ToArray() }

            if ($PSCmdlet.ShouldProcess($Path, "Create JSON export")) {
                $parentDir = Split-Path -Parent -Path $Path
                if (-not [string]::IsNullOrWhiteSpace($parentDir)) {
                try {
                    $null = New-Item -ItemType Directory -Force -Path $parentDir -ErrorAction Stop
                } catch {
                    $errorMessage = "$directoryNotExistsMessage ($parentDir): $($_.Exception.Message)"
                    $writeBridgeLogSplat = @{
                        Stage   = $errorStage
                        Message = $errorMessage
                        Level   = 'Warning'
                    }
                    Write-BridgeExportLogSafe @writeBridgeLogSplat -Configuration $Configuration

                    return [PSCustomObject]@{
                        Success      = $false
                        Data         = $null
                        ErrorMessage = $errorMessage
                        ErrorCode    = 'DIRECTORY_NOT_EXISTS'
                        Timestamp    = (Get-Date -Format o)
                    }
                }
                }

                $json = ConvertTo-Json -InputObject $dataToExport -Depth $resolvedDepth -Compress
                Write-BridgeAtomicJson -Path $Path -JsonContent $json

                $writeBridgeLogSplat = @{
                    Stage   = $analysisStage
                    Message = "$successMessage`: $Path"
                }
                Write-BridgeExportLogSafe @writeBridgeLogSplat -Configuration $Configuration
            }

            return [PSCustomObject]@{
                Success      = $true
                Data         = @{ ExportedPath = $Path; RecordCount = $items.Count }
                ErrorMessage = ''
                ErrorCode    = ''
                Timestamp    = (Get-Date -Format o)
            }
        }
        catch {
            $errorMessage = "$failedMessage`: $($_.Exception.Message)"
            $writeBridgeLogSplat = @{
                Stage   = $errorStage
                Message = $errorMessage
                Level   = 'Warning'
            }
            Write-BridgeExportLogSafe @writeBridgeLogSplat -Configuration $Configuration

            return [PSCustomObject]@{
                Success      = $false
                Data         = $null
                ErrorMessage = $errorMessage
                ErrorCode    = 'JSON_EXPORT_FAILURE'
                Timestamp    = (Get-Date -Format o)
            }
        }
    }
}