#Requires -Version 7.4

function Resolve-vSEALStatusPath {
    <#
    .SYNOPSIS
        Resolves the status file path based on phase and configuration.

    .DESCRIPTION
        Determines the correct path for status.json based on execution phase:
        - Seal phase: Always returns C:\ProgramData\vSEAL\status.json
        - Engage phase: Returns persistent_disk\vSEAL\status.json if configured and exists,
          otherwise falls back to C:\ProgramData\vSEAL\status.json

        Throws an error if Engage phase has persistent_disk configured but the path doesn't exist.

    .PARAMETER Phase
        The execution phase: 'Seal' or 'Engage'.

    .PARAMETER Configuration
        The vSEAL configuration hashtable or OrderedDictionary containing storage settings.

    .EXAMPLE
        $config = @{ storage = @{ persistent_disk = 'D:' } }
        Resolve-vSEALStatusPath -Phase Engage -Configuration $config

        Returns 'D:\vSEAL\status.json' if D: exists.

    .EXAMPLE
        Resolve-vSEALStatusPath -Phase Seal -Configuration @{}

        Returns 'C:\ProgramData\vSEAL\status.json' regardless of configuration.

    .OUTPUTS
        [string] - The resolved path to status.json
    #>
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('Seal', 'Engage', 'Rollback')]
        [string]$Phase,

        [Parameter(Mandatory)]
        $Configuration  # hashtable or OrderedDictionary
    )

    # Default status path (C:\ProgramData\vSEAL\status.json)
    $defaultPath = Join-Path $env:ProgramData 'vSEAL\status.json'

    # Seal phase: always use C: path
    if ($Phase -eq 'Seal') {
        Write-vSEALLog "Seal phase: using default status path $defaultPath" -Level DEBUG
        return $defaultPath
    }

    # Engage phase: check for persistent_disk configuration
    # Note: Use bracket notation for null-safe hashtable access (?.  doesn't work on hashtables)
    $storage = $Configuration['storage']
    $persistentDisk = if ($storage) { $storage['persistent_disk'] } else { $null }

    if ([string]::IsNullOrWhiteSpace($persistentDisk)) {
        # No persistent_disk configured - use default C: path
        Write-vSEALLog "Engage phase: no persistent_disk configured, using default status path $defaultPath" -Level DEBUG
        return $defaultPath
    }

    # persistent_disk is configured - verify it exists
    if (-not (Test-Path -Path $persistentDisk -PathType Container)) {
        throw "Configured storage.persistent_disk '$persistentDisk' does not exist"
    }

    # persistent_disk exists - use it
    $persistentPath = Join-Path $persistentDisk 'vSEAL\status.json'
    Write-vSEALLog "Engage phase: using persistent_disk status path $persistentPath" -Level DEBUG
    return $persistentPath
}
