# 测试 TSN 格式支持

Write-Host "=== TSN 格式支持测试 ===" -ForegroundColor Cyan
Write-Host ""

# 1. 创建测试 TSN 文件
Write-Host "1. 创建测试 TSN 文件..." -ForegroundColor Yellow

# 使用 PowerShell 手动构建 TSN 二进制
$tsnHeader = [byte[]](0x54, 0x53, 0x4E, 0x00)  # "TSN\0"
$tsnVersion = [byte[]](0x01, 0x00, 0x00, 0x00)  # 版本 1

# 节区描述
$codeOffset = [BitConverter]::GetBytes([uint32]24)  # 代码从 24 字节开始
$codeSize = [BitConverter]::GetBytes([uint32]6)     # 6 字节代码
$dataOffset = [BitConverter]::GetBytes([uint32]30)  # 数据从 30 开始
$dataSize = [BitConverter]::GetBytes([uint32]0)     # 0 字节数据
$rdataOffset = [BitConverter]::GetBytes([uint32]30)
$rdataSize = [BitConverter]::GetBytes([uint32]0)

# 符号表
$numSymbols = [BitConverter]::GetBytes([uint32]1)  # 1 个符号
$section = [byte](0x00)  # SECTION_TEXT
$symOffset = [BitConverter]::GetBytes([uint32]0)  # 偏移 0
$symName = [System.Text.Encoding]::UTF8.GetBytes("main" + "`0")  # "main\0"
while ($symName.Length % 8 -ne 0) { $symName += [byte]0 }  # 8 字节对齐

# 重定位表
$numRelocs = [BitConverter]::GetBytes([uint32]0)  # 0 个重定位

# 代码（mov eax, 42; ret）
$code = [byte[]](0xB8, 0x2A, 0x00, 0x00, 0x00, 0xC3)

# 组装 TSN 文件
$tsnData = @()
$tsnData += $tsnHeader
$tsnData += $tsnVersion
$tsnData += $codeOffset
$tsnData += $codeSize
$tsnData += $dataOffset
$tsnData += $dataSize
$tsnData += $rdataOffset
$tsnData += $rdataSize
$tsnData += $numSymbols
$tsnData += $section
$tsnData += $symOffset
$tsnData += $symName
$tsnData += $numRelocs
$tsnData += $code

[System.IO.File]::WriteAllBytes("$PSScriptRoot\test_module.tsn", $tsnData)
Write-Host "  ✅ 已创建 test_module.tsn ($($tsnData.Length) bytes)" -ForegroundColor Green
Write-Host ""

# 2. 测试链接器加载
Write-Host "2. 测试链接器加载 TSN..." -ForegroundColor Yellow
Write-Host "  运行: native-linker test_module.tsn -o test_tsn.exe" -ForegroundColor Gray

$nativeLinker = "$PSScriptRoot\target\release\native-linker.exe"
if (Test-Path $nativeLinker) {
    & $nativeLinker "test_module.tsn" -o "test_tsn.exe" 2>&1 | Select-String "TSN|加载|error" | ForEach-Object { Write-Host "  $_" }
} else {
    Write-Host "  ❌ native-linker.exe 不存在" -ForegroundColor Red
}

Write-Host ""
Write-Host "=== 测试完成 ===" -ForegroundColor Cyan
