param(
    [string]$DllPath = "open_wrapper/lib/open.dll",
    [string]$OutputLibPath = "",
    [ValidateSet("x64", "x86")]
    [string]$Machine = "x64"
)

$errorActionPreference = "Stop"

function Resolve-Tool($name) {
    $cmd = Get-Command $name -ErrorAction SilentlyContinue
    if (-not $cmd) {
        throw "Could not find '$name' on PATH. Run this script from the Visual Studio Developer Command Prompt or add $name.exe to PATH."
    }
    return $cmd.Path
}

$dumpbin = Resolve-Tool "dumpbin.exe"
$libExe = Resolve-Tool "lib.exe"

if (-not (Test-Path $DllPath)) {
    throw "DLL not found: $DllPath"
}

$dllFullPath = (Get-Item $DllPath).FullName
$workDir = Split-Path $dllFullPath -Parent

if ([string]::IsNullOrWhiteSpace($OutputLibPath)) {
    $dllBase = [System.IO.Path]::GetFileNameWithoutExtension($dllFullPath)
    $OutputLibPath = [System.IO.Path]::Combine($workDir, "$dllBase.lib")
}

$libName = [System.IO.Path]::GetFileNameWithoutExtension($OutputLibPath)
$exportsFile = Join-Path $workDir "$libName.exports"
$defFile = Join-Path $workDir "$libName.def"

Write-Host "Generating exports list from $dllFullPath ..."
& $dumpbin /nologo /exports $dllFullPath | Set-Content -Encoding UTF8 $exportsFile

$lines = Get-Content $exportsFile | Where-Object { $_ -match '^\s+\d+\s+[0-9A-F]+\s+[0-9A-F]+\s+\S+' }
$symbols = $lines | ForEach-Object {
    ($_.Trim() -split '\s+')[3]
}

if (-not $symbols) {
    throw "Failed to parse exports from $dllFullPath. Inspect $exportsFile for details."
}

$defContent = @("LIBRARY $libName", "EXPORTS") + $symbols
$defContent | Set-Content -Encoding ASCII $defFile

Write-Host "Creating import library $OutputLibPath ..."
& $libExe /nologo /def:$defFile /machine:$Machine /out:$OutputLibPath

Write-Host "Done."
