param(
    [Parameter(Mandatory = $true)][string]$DataRoot,
    [Parameter(Mandatory = $true)][string]$OutputRoot,
    [string]$LidarObject = "frontlidar",
    [string]$Timezone = "+08:00",
    [string[]]$StationNames = @(),
    [int]$Stride = 1,
    [double]$RtkMaxDtMs = 150.0
)

$ErrorActionPreference = "Stop"
$Repo = Split-Path -Parent $PSScriptRoot
$Exporter = Join-Path $Repo "tools\frontlidar_dlog_export.py"
if (-not (Test-Path -LiteralPath $DataRoot)) { throw "DataRoot does not exist: $DataRoot" }
if ($Stride -lt 1) { throw "Stride must be at least 1" }
if ($StationNames.Count -gt 0) {
    $Stations = @($StationNames | ForEach-Object { Get-Item -LiteralPath (Join-Path $DataRoot $_) })
} else {
    $Stations = @(Get-ChildItem -LiteralPath $DataRoot -Directory | Where-Object {
        (Test-Path -LiteralPath (Join-Path $_.FullName "dobject")) -and
        (Test-Path -LiteralPath (Join-Path $_.FullName "dobject_recording"))
    } | Sort-Object Name)
}
if ($Stations.Count -eq 0) { throw "No station directory containing dobject and dobject_recording was found" }
New-Item -ItemType Directory -Force -Path $OutputRoot | Out-Null
foreach ($Station in $Stations) {
    $Out = Join-Path $OutputRoot $Station.Name
    Write-Host "[legacy station $($Station.Name)]"
    & python $Exporter --dlog $Station.FullName --out $Out --object $LidarObject --format npz `
        --timezone $Timezone --stride $Stride --compress --rtk-sidecars --write-reports --resume `
        --rtk-max-dt-ms $RtkMaxDtMs
    if ($LASTEXITCODE -ne 0) { throw "Export failed for station $($Station.Name)" }
}
Write-Host "Exported stations: $($Stations.Count)"
