param([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\rigorous_calibration.py"
$Filter = Join-Path $Repo "code\cross_backend_filter.py"
$Finalize = Join-Path $Repo "code\finalize_consensus.py"

function Run-Python {
    param([string[]]$Arguments)
    & python @Arguments
    if ($LASTEXITCODE -ne 0) { throw "Python failed with exit code $LASTEXITCODE" }
}

Run-Python @($Filter, "--open3d-pairs", (Join-Path $ResultRoot "open3d_gicp\B_batch2_refined.npz"),
    "--small-pairs", (Join-Path $ResultRoot "small_gicp\B_batch2_refined.npz"),
    "--output", (Join-Path $ResultRoot "consensus\B_batch2_consensus.npz"))
Run-Python @($Filter, "--open3d-pairs", (Join-Path $ResultRoot "open3d_gicp\B_batch1_auxiliary_refined.npz"),
    "--small-pairs", (Join-Path $ResultRoot "small_gicp\B_batch1_auxiliary_refined.npz"),
    "--output", (Join-Path $ResultRoot "consensus\B_batch1_consensus.npz"), "--min-pairs", "15")
Run-Python @($Code, "calibrate", "--pairs", (Join-Path $ResultRoot "consensus\B_batch2_consensus.npz"),
    "--ground-planes", (Join-Path $ResultRoot "common\ground_planes_batch2.csv"),
    "--output", (Join-Path $ResultRoot "consensus\extrinsic_batch2_consensus.json"))
Run-Python @($Code, "validate", "--pairs", (Join-Path $ResultRoot "consensus\B_batch1_consensus.npz"),
    "--extrinsic", (Join-Path $ResultRoot "consensus\extrinsic_batch2_consensus.json"),
    "--output", (Join-Path $ResultRoot "consensus\batch1_auxiliary_check.json"))
Run-Python @($Finalize,
    "--consensus-extrinsic", (Join-Path $ResultRoot "consensus\extrinsic_batch2_consensus.json"),
    "--consensus-check", (Join-Path $ResultRoot "consensus\batch1_auxiliary_check.json"),
    "--open3d-extrinsic", (Join-Path $ResultRoot "open3d_gicp\extrinsic_batch2_refined.json"),
    "--small-extrinsic", (Join-Path $ResultRoot "small_gicp\extrinsic_batch2_refined.json"),
    "--output", (Join-Path $ResultRoot "final_extrinsic_recommended.json"),
    "--summary", (Join-Path $ResultRoot "final_summary.json"))
