UkgPro.Reports.psm1

$ErrorActionPreference = 'Stop'

$moduleRoot = $PSScriptRoot
$libRoot = Join-Path -Path $moduleRoot -ChildPath 'lib/netstandard2.0'
$binaryModule = Join-Path -Path $libRoot -ChildPath 'UkgPro.Reports.Binary.dll'

if (-not (Test-Path -LiteralPath $binaryModule)) {
    throw "The UkgPro.Reports binary was not found at '$binaryModule'. Run tools/build.ps1 before importing the module from source."
}

$resolveDependency = {
    param($sender, $args)

    if ([string]::IsNullOrWhiteSpace($args.Name)) {
        return $null
    }

    $assemblyName = [System.Reflection.AssemblyName]::new($args.Name).Name
    if ([string]::IsNullOrWhiteSpace($assemblyName)) {
        return $null
    }

    $candidate = Join-Path -Path $libRoot -ChildPath "$assemblyName.dll"
    if (Test-Path -LiteralPath $candidate) {
        return [System.Reflection.Assembly]::LoadFrom($candidate)
    }

    return $null
}

if ($PSVersionTable.PSEdition -eq 'Desktop') {
    [System.AppDomain]::CurrentDomain.add_AssemblyResolve($resolveDependency)
} else {
    $loadContextType = [type]::GetType('System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader')
    if ($loadContextType) {
        $defaultContext = $loadContextType::Default
        $handler = {
            param($context, $assemblyName)

            $candidate = Join-Path -Path $libRoot -ChildPath "$($assemblyName.Name).dll"
            if (Test-Path -LiteralPath $candidate) {
                return $context.LoadFromAssemblyPath($candidate)
            }

            return $null
        }.GetNewClosure()

        $defaultContext.add_Resolving($handler)
    }
}

Import-Module -Name $binaryModule -ErrorAction Stop