param(
    [Parameter(Mandatory = $true)][string]$CombinedRoot,
    [string]$OutputRoot = "",
    [string]$WorkRoot = "",
    [double]$RtkReferenceHeightAboveGroundM = 0.8535,
    [int]$ExpectedStations = 34,
    [int]$MinPairs = 20,
    [int]$Bootstrap = 200
)

$ErrorActionPreference = "Stop"
$Repo = Split-Path -Parent $PSScriptRoot
if ([string]::IsNullOrWhiteSpace($OutputRoot)) { $OutputRoot = Join-Path $Repo "outputs\rtk_lidar_calibration" }
if ([string]::IsNullOrWhiteSpace($WorkRoot)) { $WorkRoot = Join-Path $Repo "work\prepared_rtk_direct" }
$Prepared = $WorkRoot

& (Join-Path $Repo "run\prepare_multisensor_dataset.ps1") `
    -CombinedRoot $CombinedRoot -Output $Prepared -HeadingOffsetDeg 0 `
    -AntennaLever @(0.0,0.0,0.0) -PoseName "rtk_gga_raw_heading" -MinStations 30 -ExpectedStations $ExpectedStations -Overwrite
if ($LASTEXITCODE -ne 0) { throw "RTK-direct dataset preparation failed" }

& (Join-Path $Repo "run\run_single_dataset.ps1") `
    -Prepared $Prepared -OutputRoot $OutputRoot `
    -ReferencePoseFile "reference_poses_rtk_gga_raw_heading.csv" `
    -ReferenceHeight $RtkReferenceHeightAboveGroundM -MinPairs $MinPairs -Bootstrap $Bootstrap
if ($LASTEXITCODE -ne 0) { throw "RTK-direct calibration failed" }

$Finalize = @(
    (Join-Path $Repo "code\finalize_direct_rtk_lidar.py"),
    "--result-root", $OutputRoot,
    "--reference-height", "$RtkReferenceHeightAboveGroundM"
)
& python @Finalize
if ($LASTEXITCODE -ne 0) { throw "Final result packaging failed" }

Write-Host "Final T_RTK_lidar: $(Join-Path $OutputRoot 'final_T_RTK_lidar.json')"
