param(
  [string]$InstallRoot = (Join-Path $env:LOCALAPPDATA 'PLAI Canonical QBFT Node')
)

$ErrorActionPreference = 'Stop'
$configPath = Join-Path $InstallRoot 'node-config.json'
if (-not (Test-Path -LiteralPath $configPath)) { throw "Node config is missing: $configPath" }
$config = Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
if (-not $config.finalized -or $config.mode -ne 'preserve-canonical-genesis') {
  throw 'Only a finalized canonical-genesis migration package may start.'
}

$genesis = Join-Path $InstallRoot 'genesis.json'
$staticNodes = Join-Path $InstallRoot 'static-nodes.json'
$runtimeRoot = Join-Path $InstallRoot 'runtime'
$java = Join-Path (Join-Path (Join-Path $runtimeRoot 'jdk') 'bin') 'java.exe'
$besuRoot = Join-Path $runtimeRoot 'besu'
$libRoot = Join-Path $besuRoot 'lib'
$classpath = Join-Path $libRoot '*'
foreach ($required in @($genesis, $staticNodes, $java, $libRoot)) {
  if (-not (Test-Path -LiteralPath $required)) { throw "Required node file is missing: $required" }
}
if ((Get-FileHash -LiteralPath $genesis -Algorithm SHA256).Hash.ToLowerInvariant() -ne $config.genesisSha256) {
  throw 'Genesis hash does not match the canonical migration plan.'
}

$dataPath = Join-Path $InstallRoot 'data'
New-Item -ItemType Directory -Force -Path $dataPath | Out-Null
$besuArgs = @(
  '--enable-native-access=ALL-UNNAMED',
  '-Xms128m',
  '-Xmx512m',
  '-cp', $classpath,
  'org.hyperledger.besu.Besu',
  "--data-path=$dataPath",
  "--genesis-file=$genesis",
  '--profile=ENTERPRISE',
  '--sync-mode=FULL',
  '--data-storage-format=BONSAI',
  "--p2p-host=$($config.advertisedHost)",
  '--p2p-interface=0.0.0.0',
  "--p2p-port=$($config.p2pPort)",
  '--discovery-enabled=false',
  '--nat-method=NONE',
  "--static-nodes-file=$staticNodes",
  '--min-gas-price=0',
  '--logging=INFO'
)

if ($config.role -eq 'validator') {
  $activationPath = Join-Path $InstallRoot 'activation-approved.json'
  $privateKeyPath = Join-Path (Join-Path $InstallRoot 'secrets') 'validator.key'
  if (-not (Test-Path -LiteralPath $activationPath)) {
    throw 'Validator activation is locked. Stop the matching local validator, then run approve-node-activation.ps1.'
  }
  $activation = Get-Content -LiteralPath $activationPath -Raw | ConvertFrom-Json
  if ($activation.nodeName -ne $config.nodeName -or $activation.validatorAddress -ne $config.validatorAddress) {
    throw 'Validator activation approval does not match this node identity.'
  }
  if (-not (Test-Path -LiteralPath $privateKeyPath)) { throw 'Validator private key is missing.' }
  $besuArgs += "--node-private-key-file=$privateKeyPath"
} elseif ($config.role -ne 'presync') {
  throw "Unsupported canonical migration role: $($config.role)"
}

$env:JAVA_HOME = Join-Path $runtimeRoot 'jdk'
Set-Location $besuRoot
& $java @besuArgs
exit $LASTEXITCODE
