# rebuild_with_fixes.ps1 - 重新构建并修复错误

Write-Host "=== 重新构建 WASM 模块 ===" -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"

# 创建目录
New-Item -Path "public/wasm" -ItemType Directory -Force | Out-Null

Write-Host "[ ] 编译 WASM 模块（包含完整的运行时方法）..." -ForegroundColor Cyan

# 完整的编译命令
$compileCmd = @'
emcc src/math_utils.cpp src/smart_json_wrapper.cpp src/main.cpp -I./include -I./third_party -I./third_party/kdl_parser/include -I./third_party/orocos_kdl/install_wasm/include -I./third_party/eigen3 -std=c++17 -s WASM=1 -s EXPORTED_FUNCTIONS='["_smart_process_json","_smart_get_function_list","_smart_get_function_info","_smart_test_match","_smart_get_version","_smart_free_string","_main"]' -s EXPORTED_RUNTIME_METHODS='["ccall","cwrap","UTF8ToString","stringToUTF8","lengthBytesUTF8","allocateUTF8","allocate","ALLOC_NORMAL","getValue","setValue"]' -s MODULARIZE=1 -s EXPORT_NAME="createSmartMathModule" -s ALLOW_MEMORY_GROWTH=1 -s ASSERTIONS=1 -O3 -o public/wasm/smart_math.js
'@

Write-Host "执行命令: $compileCmd" -ForegroundColor Gray
Invoke-Expression $compileCmd

if ($LASTEXITCODE -eq 0) {
    Write-Host "[✓] 编译成功!" -ForegroundColor Green
    
    if (Test-Path "public/wasm/smart_math.js") {
        $jsSize = (Get-Item "public/wasm/smart_math.js").Length / 1KB
        $wasmSize = (Get-Item "public/wasm/smart_math.wasm").Length / 1KB
        
        Write-Host ""
        Write-Host "📦 生成文件:" -ForegroundColor White
        Write-Host "├─ smart_math.js   ($($jsSize.ToString('F1')) KB)" -ForegroundColor Gray
        Write-Host "└─ smart_math.wasm ($($wasmSize.ToString('F1')) KB)" -ForegroundColor Gray
        Write-Host ""
        
        Write-Host "🔧 导出的运行时方法:" -ForegroundColor Cyan
        Write-Host "├─ ccall" -ForegroundColor Gray
        Write-Host "├─ cwrap" -ForegroundColor Gray
        Write-Host "├─ UTF8ToString" -ForegroundColor Gray
        Write-Host "├─ stringToUTF8" -ForegroundColor Gray
        Write-Host "├─ lengthBytesUTF8" -ForegroundColor Gray
        Write-Host "├─ allocateUTF8" -ForegroundColor Gray
        Write-Host "├─ allocate" -ForegroundColor Gray
        Write-Host "└─ ALLOC_NORMAL" -ForegroundColor Gray
        Write-Host ""
        
        # 测试模块是否正常工作
        Write-Host "[ ] 创建测试文件..." -ForegroundColor Cyan
        
        $testHtml = @"
<!DOCTYPE html>
<html>
<head>
    <title>WASM 测试</title>
    <script src="wasm/smart_math.js"></script>
</head>
<body>
    <h1>WASM 模块测试</h1>
    <div id="output">加载中...</div>
    
    <script>
        async function testModule() {
            try {
                const Module = await createSmartMathModule();
                console.log('Module loaded:', Module);
                
                // 测试 allocateUTF8 是否存在
                if (typeof Module.allocateUTF8 === 'function') {
                    console.log('✓ allocateUTF8 is available');
                    
                    // 测试版本函数
                    const versionPtr = Module._smart_get_version();
                    const versionStr = Module.UTF8ToString(versionPtr);
                    console.log('Version:', versionStr);
                    Module._smart_free_string(versionPtr);
                    
                    document.getElementById('output').innerHTML = 
                        '<h3 style="color: green;">✅ WASM 模块加载成功！</h3>' +
                        '<pre>' + versionStr + '</pre>';
                } else {
                    console.log('✗ allocateUTF8 is NOT available');
                    document.getElementById('output').innerHTML = 
                        '<h3 style="color: red;">❌ allocateUTF8 不可用</h3>';
                }
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('output').innerHTML = 
                    '<h3 style="color: red;">❌ 加载失败: ' + error.message + '</h3>';
            }
        }
        
        testModule();
    </script>
</body>
</html>
"@
        
        Set-Content -Path "public/test_wasm.html" -Value $testHtml -Encoding UTF8
        Write-Host "[✓] 测试文件已创建: public/test_wasm.html" -ForegroundColor Green
        Write-Host ""
        Write-Host "🌐 启动测试服务器:" -ForegroundColor Cyan
        Write-Host "    cd public" -ForegroundColor Gray
        Write-Host "    python -m http.server 8080" -ForegroundColor Gray
        Write-Host "    然后在浏览器中打开: http://localhost:8080/test_wasm.html" -ForegroundColor Gray
        
    } else {
        Write-Host "[✗] 未找到生成文件" -ForegroundColor Red
    }
} else {
    Write-Host "[✗] 编译失败，退出码: $LASTEXITCODE" -ForegroundColor Red
}
