#Requires -Version 7.4

function Test-vSEALBaselineIntegrity {
    <#
    .SYNOPSIS
        Validates the integrity of a baseline folder.

    .DESCRIPTION
        Checks that a baseline folder exists, contains a valid _manifest.json file,
        and that all plugin JSON files are parseable. Returns a result object with
        Valid (boolean) and Reason (string or null) properties.

    .PARAMETER BaselinePath
        The full path to the baseline folder to validate.

    .EXAMPLE
        Test-vSEALBaselineIntegrity -BaselinePath 'C:\ProgramData\vSEAL\baselines\20260125_120000'

        Returns: @{ Valid = $true; Reason = $null } if valid
        Returns: @{ Valid = $false; Reason = 'Missing manifest' } if invalid

    .OUTPUTS
        [hashtable] Object with Valid (bool) and Reason (string or null) properties.
    #>
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory)]
        [string]$BaselinePath
    )

    # Check 1: Folder exists
    if (-not (Test-Path -Path $BaselinePath -PathType Container)) {
        return @{
            Valid  = $false
            Reason = 'Folder not found'
        }
    }

    # Check 2: _manifest.json exists
    $manifestPath = Join-Path $BaselinePath '_manifest.json'
    if (-not (Test-Path -Path $manifestPath -PathType Leaf)) {
        return @{
            Valid  = $false
            Reason = 'Missing manifest'
        }
    }

    # Check 3: Manifest is valid JSON with content
    try {
        $content = Get-Content -Path $manifestPath -Raw -Encoding utf8
        if ([string]::IsNullOrWhiteSpace($content)) {
            return @{
                Valid  = $false
                Reason = 'Corrupt manifest: empty file'
            }
        }
        $manifest = $content | ConvertFrom-Json -AsHashtable
        if ($null -eq $manifest) {
            return @{
                Valid  = $false
                Reason = 'Corrupt manifest: invalid content'
            }
        }
    }
    catch {
        return @{
            Valid  = $false
            Reason = "Corrupt manifest: $($_.Exception.Message)"
        }
    }

    # Check 4: Manifest required fields validation
    $requiredScalar = @('id', 'created', 'status', 'phase')
    $missingFields = [System.Collections.Generic.List[string]]::new()

    foreach ($field in $requiredScalar) {
        if (-not $manifest.ContainsKey($field) -or $null -eq $manifest[$field]) {
            $missingFields.Add($field)
        }
    }

    if (-not $manifest.ContainsKey('plugins') -or $null -eq $manifest['plugins']) {
        $missingFields.Add('plugins')
    }
    elseif ($manifest['plugins'] -isnot [hashtable]) {
        $missingFields.Add('plugins (must be hashtable)')
    }

    if ($missingFields.Count -gt 0) {
        return @{
            Valid  = $false
            Reason = "Invalid manifest: missing required fields: $($missingFields -join ', ')"
        }
    }

    # Check 5: Each plugin JSON file is parseable
    $pluginFiles = Get-ChildItem -Path $BaselinePath -Filter '*.json' -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -ne '_manifest.json' }

    foreach ($file in $pluginFiles) {
        try {
            $fileContent = Get-Content -Path $file.FullName -Raw -Encoding utf8
            $null = $fileContent | ConvertFrom-Json
        }
        catch {
            return @{
                Valid  = $false
                Reason = "Corrupt plugin file: $($file.Name)"
            }
        }
    }

    # All checks passed
    return @{
        Valid  = $true
        Reason = $null
    }
}
