#Requires -Version 7.4
#Requires -PSEdition Core

<#
.SYNOPSIS
    vSEAL - Automated golden image sealing for VDI environments.

.DESCRIPTION
    PowerShell 7 module for automated golden image sealing targeting
    Windows Server 2022+ and Windows 11. Runs elevated (Admin) or as SYSTEM.
#>

# Get the module root path
$script:ModuleRoot = $PSScriptRoot

# Dot-source native P/Invoke types first (required by other components)
. $PSScriptRoot/Private/NativeTypes.ps1

# Dot-source prerequisite orchestrator first (needed for module load validation)
$prerequisiteOrchestratorPath = Join-Path -Path $script:ModuleRoot -ChildPath 'Private/Invoke-vSEALPrerequisiteChecks.ps1'
if (Test-Path -Path $prerequisiteOrchestratorPath -PathType Leaf) {
    . $prerequisiteOrchestratorPath
}

# Dot-source PluginContext early (Write-vSEALLog depends on Get-CurrentPluginContext)
$pluginContextPath = Join-Path -Path $script:ModuleRoot -ChildPath 'Private/PluginContext.ps1'
if (Test-Path -Path $pluginContextPath -PathType Leaf) {
    . $pluginContextPath
}

# Dot-source all private functions
$privateFunctionsPath = Join-Path -Path $script:ModuleRoot -ChildPath 'Private'
if (Test-Path -Path $privateFunctionsPath -PathType Container) {
    $privateFiles = Get-ChildItem -Path $privateFunctionsPath -Filter '*.ps1' -File -ErrorAction SilentlyContinue
    foreach ($file in $privateFiles) {
        try {
            . $file.FullName
        }
        catch {
            Write-Error -Message "Failed to import private function '$($file.FullName)': $_"
        }
    }
}

# Dot-source all public functions
$publicFunctionsPath = Join-Path -Path $script:ModuleRoot -ChildPath 'Public'
if (Test-Path -Path $publicFunctionsPath -PathType Container) {
    $publicFiles = Get-ChildItem -Path $publicFunctionsPath -Filter '*.ps1' -File -ErrorAction SilentlyContinue
    foreach ($file in $publicFiles) {
        try {
            . $file.FullName
        }
        catch {
            Write-Error -Message "Failed to import public function '$($file.FullName)': $_"
        }
    }
}

# Run prerequisite checks at module load time
# This validates the environment before the module becomes usable
try {
    Invoke-vSEALPrerequisiteChecks -ErrorAction Stop
}
catch {
    # Re-throw with module context for clearer error message
    throw "vSEAL prerequisites not met:`n$($_.Exception.Message)"
}
