
# test_compile.ps1 - 测试编译
Write-Host "=== 测试编译 ===" -ForegroundColor Cyan

# 设置环境
$emsdkCandidates = @()

if ($env:EMSDK) {
    $emsdkCandidates += $env:EMSDK
}

$emsdkCandidates += "E:\emsdk"
$emsdkCandidates += (Join-Path (Split-Path $PSScriptRoot -Parent) "..\emsdk")
$emsdkCandidates += (Join-Path (Split-Path $PSScriptRoot -Parent) "emsdk")

$emccCommand = Get-Command emcc -ErrorAction SilentlyContinue
if ($emccCommand -and $emccCommand.Source) {
    $emccSourceDir = Split-Path $emccCommand.Source -Parent
    if (Test-Path (Join-Path $emccSourceDir "emcc.ps1")) {
        $emsdkCandidates += (Split-Path (Split-Path $emccSourceDir -Parent) -Parent)
    }
}

$EmsdkPath = $null
foreach ($candidate in $emsdkCandidates | Select-Object -Unique) {
    if (-not [string]::IsNullOrWhiteSpace($candidate)) {
        try {
            if (Test-Path $candidate) {
                $resolvedCandidate = [System.IO.Path]::GetFullPath($candidate)
                if (Test-Path (Join-Path $resolvedCandidate "upstream\emscripten\emcc.ps1")) {
                    $EmsdkPath = $resolvedCandidate
                    break
                }
            }
        } catch {
            continue
        }
    }
}

if (-not $EmsdkPath) {
    Write-Host "[错误] 未找到 Emscripten" -ForegroundColor Red
    exit 1
}

$env:PATH = "$EmsdkPath\upstream\emscripten;$env:PATH"

# 公共包含目录
$includeArgs = @(
    '-I./include',
    '-I./third_party',
    '-I./third_party/kdl_parser/include',
    '-I./third_party/orocos_kdl/install_wasm/include',
    '-I./third_party/eigen3'
)

# 测试 1: 编译 math_utils.cpp
Write-Host "[ ] 测试编译 math_utils.cpp..." -ForegroundColor Cyan
emcc src/math_utils.cpp @includeArgs -s WASM=1 -c -o test_math.o 2>&1
if ($LASTEXITCODE -eq 0) {
    Write-Host "[✓] math_utils.cpp 编译成功" -ForegroundColor Green
} else {
    Write-Host "[✗] math_utils.cpp 编译失败" -ForegroundColor Red
}

# 测试 2: 编译 smart_json_wrapper.cpp
Write-Host "[ ] 测试编译 smart_json_wrapper.cpp..." -ForegroundColor Cyan
emcc src/smart_json_wrapper.cpp @includeArgs -s WASM=1 -c -o test_wrapper.o 2>&1
if ($LASTEXITCODE -eq 0) {
    Write-Host "[✓] smart_json_wrapper.cpp 编译成功" -ForegroundColor Green
} else {
    Write-Host "[✗] smart_json_wrapper.cpp 编译失败" -ForegroundColor Red
}

# 测试 3: 编译 main.cpp
Write-Host "[ ] 测试编译 main.cpp..." -ForegroundColor Cyan
emcc src/main.cpp @includeArgs -s WASM=1 -c -o test_main.o 2>&1
if ($LASTEXITCODE -eq 0) {
    Write-Host "[✓] main.cpp 编译成功" -ForegroundColor Green
} else {
    Write-Host "[✗] main.cpp 编译失败" -ForegroundColor Red
}

# 清理
Remove-Item test_*.o -ErrorAction SilentlyContinue
