param(
    [int]$PairIndex = 0,
    [string]$ResultRoot = ""
)

$ErrorActionPreference = "Stop"
$Repo = Split-Path -Parent $PSScriptRoot
if ([string]::IsNullOrWhiteSpace($ResultRoot)) { $ResultRoot = Join-Path $Repo "results\01_previous_two_batches" }
$Code = Join-Path $Repo "code\scan_extrinsic_sensitivity.py"
$X = Join-Path $ResultRoot "final_extrinsic_recommended.json"
$Ground = Join-Path $ResultRoot "common\ground_planes_batch2.csv"
$Out = Join-Path $ResultRoot "diagnostics"

foreach ($Backend in @("open3d_gicp", "small_gicp")) {
    $Label = if ($Backend -eq "open3d_gicp") { "open3d_refined" } else { "small_gicp_refined" }
    & python $Code --pairs (Join-Path $ResultRoot "$Backend\B_batch2_refined.npz") --extrinsic $X `
        --ground-planes $Ground --pair-index $PairIndex --output (Join-Path $Out "${Label}_pair${PairIndex}_left_rpy_scan.json")
    if ($LASTEXITCODE -ne 0) { throw "$Backend sensitivity scan failed" }
}
& python $Code --pairs (Join-Path $ResultRoot "consensus\B_batch2_consensus.npz") --extrinsic $X `
    --ground-planes $Ground --pair-index $PairIndex --output (Join-Path $Out "consensus_pair${PairIndex}_left_rpy_scan.json")
if ($LASTEXITCODE -ne 0) { throw "Consensus sensitivity scan failed" }
