$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

function Resolve-BinPath {
    if ($env:BIN -and (Test-Path $env:BIN)) {
        return (Resolve-Path $env:BIN).Path
    }

    $selfDir = Split-Path -Parent $PSCommandPath
    $releaseBin = Join-Path $selfDir "agw-standalone-api.exe"
    if (Test-Path $releaseBin) {
        return $releaseBin
    }

    $workspaceBin = Join-Path $selfDir "..\\target\\release\\agw-standalone-api.exe"
    if (Test-Path $workspaceBin) {
        return (Resolve-Path $workspaceBin).Path
    }

    throw "未找到 agw-standalone-api.exe，可设置 BIN=C:\\path\\agw-standalone-api.exe 后重试。"
}

$binPath = Resolve-BinPath

if (-not $env:AGW_ETH_PRIVKEY) {
    throw "缺少 AGW_ETH_PRIVKEY（必须为 0x + 64 hex）。"
}
if ($env:AGW_ETH_PRIVKEY -notmatch '^0x[0-9a-fA-F]{64}$') {
    throw "AGW_ETH_PRIVKEY 格式非法，应为 0x + 64 hex。"
}
if (-not $env:AGW_MEMORY_OWNER_KEY) {
    throw "缺少 AGW_MEMORY_OWNER_KEY（Rpc/Smoldot 必填）。"
}

$env:AGW_CHAIN_BACKEND = "smoldot"
if (-not $env:AGW_BIND) {
    $env:AGW_BIND = "127.0.0.1:8790"
}

Write-Host "启动主网网关："
Write-Host "  BIN=$binPath"
Write-Host "  AGW_BIND=$($env:AGW_BIND)"
Write-Host "  AGW_CHAIN_BACKEND=$($env:AGW_CHAIN_BACKEND)"
Write-Host "  AGW_MEMORY_OWNER_KEY=$($env:AGW_MEMORY_OWNER_KEY)"
if ($env:AGW_AGENT_ID) {
    Write-Host "  AGW_AGENT_ID=$($env:AGW_AGENT_ID) (显式绑定)"
} else {
    Write-Host "  AGW_AGENT_ID=<unset> (由链上解析/可 unbound 启动)"
}

& $binPath
