param(
  [Parameter(Mandatory = $true)]
  [string]$BridgeConfigPath
)

$ErrorActionPreference = 'Stop'
$admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $admin) { throw 'Administrator rights are required to install bridge firewall rules.' }
if (-not (Test-Path -LiteralPath $BridgeConfigPath)) { throw "Bridge config is missing: $BridgeConfigPath" }
$bridge = Get-Content -LiteralPath $BridgeConfigPath -Raw | ConvertFrom-Json
if ($bridge.state -ne 'READY_FOR_BRIDGE' -or $bridge.mode -ne 'preserve-canonical-genesis') {
  throw 'Bridge config is not finalized for canonical-genesis migration.'
}
$remoteHosts = @($bridge.allowedRemoteHosts | Select-Object -Unique)
if ($remoteHosts.Count -ne 4) { throw 'Exactly four validator target hosts must be allowlisted.' }

foreach ($node in $bridge.nodes) {
  $ruleName = "PLAI QBFT bridge $($node.name) P2P"
  Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue | Remove-NetFirewallRule
  New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Action Allow -Protocol TCP -LocalPort $node.p2pPort -RemoteAddress $remoteHosts -Profile Domain,Private | Out-Null
}
Write-Host 'Restricted bridge firewall rules installed. No QBFT process was restarted.' -ForegroundColor Green
