#Requires -Version 7.4

# Plugin context tracking for accurate log source detection in ephemeral modules

$script:PluginContextStack = [System.Collections.Stack]::new()

function Push-PluginContext {
    <#
    .SYNOPSIS
    Pushes a plugin path onto the plugin context stack.

    .DESCRIPTION
    Records the plugin path and entry timestamp on a module-scoped stack so that
    Write-vSEALLog and other logging functions can determine which plugin is currently
    executing. This is necessary because plugins run in ephemeral ThreadJob modules
    where the call stack does not reliably reflect the originating plugin.

    .PARAMETER PluginPath
    The filesystem path of the plugin being executed.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$PluginPath
    )

    $script:PluginContextStack.Push(@{
        Path      = $PluginPath
        EnteredAt = Get-Date
    })
}

function Pop-PluginContext {
    <#
    .SYNOPSIS
    Removes the most recent plugin context from the stack.

    .DESCRIPTION
    Pops the top entry from the module-scoped plugin context stack, indicating that the
    corresponding plugin has finished executing. If the stack is empty, the call is a
    no-op. Should be called in a finally block after each plugin execution to ensure
    the stack stays balanced.
    #>
    [CmdletBinding()]
    param()

    if ($script:PluginContextStack.Count -gt 0) {
        $null = $script:PluginContextStack.Pop()
    }
}

function Get-CurrentPluginContext {
    <#
    .SYNOPSIS
    Returns the currently active plugin context from the stack.

    .DESCRIPTION
    Peeks at the top of the module-scoped plugin context stack and returns the hashtable
    containing the Path and EnteredAt timestamp of the currently executing plugin. Returns
    null if no plugin context is active (i.e., the stack is empty).
    #>
    [CmdletBinding()]
    param()

    if ($script:PluginContextStack.Count -gt 0) {
        return $script:PluginContextStack.Peek()
    }
    return $null
}
