#Requires -Version 7.4

function Import-vSEALConfiguration {
    <#
    .SYNOPSIS
    Loads and parses a TOML configuration file for vSEAL.

    .DESCRIPTION
    Validates that the specified file exists and has a .toml extension, resolves it to an
    absolute path, and checks whether the path falls within standard configuration
    directories (module root, user profile, or ProgramData). If the path is outside these
    directories, a warning is logged but loading proceeds. The file is read and parsed via
    ConvertFrom-Toml (PSToml). Specific exception types are caught and re-thrown with
    descriptive messages for file-not-found, I/O, access-denied, and TOML parse errors.

    .PARAMETER Path
    The path to the TOML configuration file. Must point to an existing file with a .toml extension.
    #>
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory)]
        [string]$Path
    )

    # Validate path exists before attempting resolution
    if (-not (Test-Path -Path $Path -PathType Leaf)) {
        throw "Configuration file not found: $Path"
    }

    # Resolve to absolute path and validate against directory traversal
    $resolvedPath = (Resolve-Path -Path $Path -ErrorAction Stop).Path

    # Ensure the resolved path is a .toml file (expected configuration format)
    if (-not $resolvedPath.EndsWith('.toml', [System.StringComparison]::OrdinalIgnoreCase)) {
        throw "Configuration file must be a TOML file (.toml extension): $resolvedPath"
    }

    # Optional: Validate path is within module or expected config directories
    # This provides defense-in-depth against path traversal attacks
    $moduleRoot = Split-Path -Path $PSScriptRoot -Parent
    $allowedPaths = @(
        $moduleRoot,
        (Join-Path -Path $env:USERPROFILE -ChildPath '.vseal'),
        (Join-Path -Path $env:ProgramData -ChildPath 'vSEAL')
    ) | Where-Object { $_ }

    $isAllowedPath = $false
    foreach ($allowedBase in $allowedPaths) {
        if ($allowedBase -and (Test-Path -Path $allowedBase -PathType Container)) {
            $resolvedAllowedBase = (Resolve-Path -Path $allowedBase -ErrorAction SilentlyContinue).Path
            if ($resolvedAllowedBase -and $resolvedPath.StartsWith($resolvedAllowedBase, [System.StringComparison]::OrdinalIgnoreCase)) {
                $isAllowedPath = $true
                break
            }
        }
    }

    if (-not $isAllowedPath) {
        Write-vSEALLog "Configuration path '$resolvedPath' is outside standard config directories. Proceeding with caution." -Level 'WARNING'
    }

    try {
        $content = Get-Content -Path $resolvedPath -Raw -ErrorAction Stop
        $config = ConvertFrom-Toml -InputObject $content
        return $config
    }
    catch [System.IO.FileNotFoundException] {
        throw "Configuration file not found: $resolvedPath"
    }
    catch [System.IO.IOException] {
        throw "I/O error reading configuration file '$resolvedPath': $($_.Exception.Message)"
    }
    catch [System.UnauthorizedAccessException] {
        throw "Access denied reading configuration file '$resolvedPath': $($_.Exception.Message)"
    }
    catch [System.Management.Automation.RuntimeException] {
        # PSToml parsing errors typically surface as RuntimeException
        throw "TOML parsing error in '$resolvedPath': $($_.Exception.Message)"
    }
    catch {
        # Fallback for any other unexpected exceptions
        $exceptionType = $_.Exception.GetType().FullName
        throw "Failed to load configuration from '$resolvedPath' ($exceptionType): $($_.Exception.Message)"
    }
}
