#Requires -Version 7.4

function Get-vSEALBaseline {
    <#
    .SYNOPSIS
        Retrieves a specific baseline by ID.

    .DESCRIPTION
        Retrieves a baseline from storage by its timestamp ID (YYYYMMDD_HHMMSS format).
        Validates baseline integrity before returning. Returns $null with warning if
        the baseline is not found or fails integrity validation.

    .PARAMETER Id
        The baseline ID in YYYYMMDD_HHMMSS format (e.g., '20260125_120000').

    .PARAMETER Config
        Optional hashtable containing vSEAL configuration. If the configuration
        contains a baseline.path setting, that path will be used for lookup.

    .EXAMPLE
        Get-vSEALBaseline -Id '20260125_120000'

        Retrieves the baseline with the specified ID from the default location.

    .EXAMPLE
        $config = @{ baseline = @{ path = 'D:\Baselines' } }
        Get-vSEALBaseline -Id '20260125_120000' -Config $config

        Retrieves a baseline from a custom storage location.

    .OUTPUTS
        [hashtable]

    .NOTES
        The baseline hashtable contains: Id, Created, Status, Phase, Config, Machine,
        OSBuild, OS (object with name/edition/version/buildNumber/releaseId/architecture
        /isWorkstation/isServer), Platform (object with hypervisor/isVMware/isHyperV
        /isNutanixAHV/isXenServer/isAzure/azureMetadata), Plugins, and Summary.
        Returns $null if baseline not found or integrity check fails.
    #>
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Id,

        [Parameter()]
        [hashtable]$Config
    )

    # Resolve storage location
    $basePath = Resolve-vSEALBaselinePath -Config $Config

    # Build baseline folder path
    $baselineDir = Join-Path $basePath $Id

    Write-vSEALLog "Looking for baseline: $baselineDir" -Level VERBOSE

    # Check if baseline exists
    if (-not (Test-Path -Path $baselineDir -PathType Container)) {
        Write-Warning "Baseline not found: $Id"
        return $null
    }

    # Validate integrity
    $integrity = Test-vSEALBaselineIntegrity -BaselinePath $baselineDir
    if (-not $integrity.Valid) {
        Write-Warning "Baseline integrity check failed: $($integrity.Reason)"
        return $null
    }

    # Read manifest
    $manifestPath = Join-Path $baselineDir '_manifest.json'
    try {
        $manifestContent = Get-Content -Path $manifestPath -Raw -Encoding utf8 -ErrorAction Stop
        $manifest = $manifestContent | ConvertFrom-Json -AsHashtable -ErrorAction Stop
    }
    catch {
        Write-Warning "Failed to read manifest: $($_.Exception.Message)"
        return $null
    }

    # Read plugin files and build plugins hashtable
    $plugins = @{}
    $pluginFiles = Get-ChildItem -Path $baselineDir -Filter '*.json' -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -ne '_manifest.json' }

    foreach ($file in $pluginFiles) {
        try {
            $pluginContent = Get-Content -Path $file.FullName -Raw -Encoding utf8 -ErrorAction Stop
            $pluginData = $pluginContent | ConvertFrom-Json -AsHashtable -ErrorAction Stop

            if ($null -ne $pluginData -and $null -ne $pluginData.plugin) {
                $plugins[$pluginData.plugin] = $pluginData.entries
            }
        }
        catch {
            Write-vSEALLog "Warning: Could not read plugin file $($file.Name): $($_.Exception.Message)" -Level WARNING
            # Continue loading other plugins
        }
    }

    # Build result structure
    $result = @{
        Id       = $manifest.id
        Created  = $manifest.created
        Status   = $manifest.status
        Phase    = $manifest.phase
        Config   = $manifest.configPath
        Machine  = $manifest.machineName
        OSBuild  = $manifest.osBuild
        OS       = if ($manifest.ContainsKey('os') -and $null -ne $manifest.os) {
            [PSCustomObject]$manifest.os
        } else {
            # Backward compatibility for old manifests
            [PSCustomObject]@{
                name          = $null
                edition       = $null
                version       = $null
                buildNumber   = $manifest.osBuild
                releaseId     = $null
                architecture  = $null
                isWorkstation = $null
                isServer      = $null
            }
        }
        Platform = if ($manifest.ContainsKey('platform') -and $null -ne $manifest.platform) {
            [PSCustomObject]$manifest.platform
        } else {
            $null
        }
        Plugins  = $plugins
        Summary  = $manifest.plugins
    }

    Write-vSEALLog "Baseline retrieved: $Id with $($plugins.Count) plugins" -Level VERBOSE

    return $result
}
