#!/usr/bin/env python3
"""Cross-platform dispatcher for the libgnss++ command suite."""

from __future__ import annotations

import difflib
import glob
import json
import os
import sys


ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
APPS_DIR = os.path.dirname(os.path.abspath(__file__))
EXE_SUFFIX = ".exe" if os.name == "nt" else ""
BUILD_CONFIGS = ("Release", "RelWithDebInfo", "Debug", "MinSizeRel")

PYTHON_COMMANDS_DIR = os.path.join(APPS_DIR, "commands")


def _discover_python_command_sources() -> tuple[dict[str, str], tuple[str, ...]]:
    source_paths = sorted(glob.glob(os.path.join(PYTHON_COMMANDS_DIR, "*", "*.py")))
    sources: dict[str, str] = {}
    install_sources: dict[str, tuple[str, str]] = {}
    source_dirs: list[str] = []
    for source_path in source_paths:
        category_dir = os.path.dirname(source_path)
        if os.path.basename(category_dir) == "support":
            continue
        if category_dir not in source_dirs:
            source_dirs.append(category_dir)

        filename = os.path.basename(source_path)
        install_key = filename.casefold()
        previous_source = install_sources.get(install_key)
        if previous_source is not None:
            previous_filename, previous_path = previous_source
            raise RuntimeError(
                "duplicate Python command basenames would collide case-insensitively "
                f"when installed flat: {previous_filename!r} ({previous_path}) and "
                f"{filename!r} ({source_path})"
            )
        install_sources[install_key] = (filename, source_path)
        sources[filename] = source_path
    return sources, tuple(source_dirs)


PYTHON_COMMAND_DISCOVERY_ERROR: str | None = None
try:
    PYTHON_COMMAND_SOURCES, PYTHON_COMMAND_SOURCE_DIRS = (
        _discover_python_command_sources()
    )
except RuntimeError as exc:
    PYTHON_COMMAND_SOURCES = {}
    PYTHON_COMMAND_SOURCE_DIRS = ()
    PYTHON_COMMAND_DISCOVERY_ERROR = str(exc)


def python_target(filename: str) -> str:
    """Resolve a grouped source command or its flat installed counterpart."""
    source_target = PYTHON_COMMAND_SOURCES.get(filename)
    if source_target is not None:
        return source_target
    return os.path.join(APPS_DIR, filename)

COMMANDS = {
    "pva-demo": {
        "kind": "python", "target": python_target("gnss_pva_demo.py"),
        "summary": "Run the tracked synthetic PVA scoring witness without hardware or a source build.",
    },
    "pva-evaluate": {
        "kind": "python", "target": python_target("gnss_pva_evaluate.py"),
        "summary": "Replay received GNSS/IMU events and score position, velocity, attitude and motion scenes offline.",
    },
    "pva-replay": {
        "kind": "binary", "target": "gnss_pva_replay",
        "summary": "Replay raw PPC through the causal online API without opening reference truth.",
    },
    "commands": {
        "kind": "builtin",
        "summary": "List registered dispatcher commands as text or JSON for users, docs, and tooling.",
    },
    "help": {
        "kind": "builtin",
        "summary": "Show top-level help or dispatch to a command's own --help output.",
    },
    "doctor": {
        "kind": "python",
        "target": python_target("gnss_doctor.py"),
        "summary": "Check local setup, built tools, datasets, docs, Docker, and ROS2 readiness.",
    },
    "demo": {
        "kind": "python",
        "target": python_target("gnss_demo.py"),
        "summary": "Run the tracked offline PPP demo and emit a .pos, KML, and JSON summary.",
    },
    "next": {
        "kind": "python",
        "target": python_target("gnss_next.py"),
        "summary": "Inspect local progress and recommend one concrete next command.",
    },
    "robotics-smoke": {
        "kind": "python",
        "target": python_target("gnss_robotics_smoke.py"),
        "summary": "Run a short PPC RTK replay with robotics-friendly realtime gates.",
    },
    "urban-bridge-score": {
        "kind": "python",
        "target": python_target("gnss_urban_bridge_score.py"),
        "summary": "Score RTK-degraded spans, fused IMU bridge drift, and reacquisition jumps against PPC truth.",
    },
    "urban-continuity-bundle": {
        "kind": "python",
        "target": python_target("gnss_urban_continuity_bundle.py"),
        "summary": "Build one auditable RTK/IMU continuity bundle with POS, KML, PNG, score, and manifest artifacts.",
    },
    "japan-static-survey": {
        "kind": "python",
        "target": python_target("gnss_japan_static_survey.py"),
        "summary": "Fetch and evaluate the frozen IGS Tsukuba relative-static and PPP survey example.",
    },
    "structural-displacement-signoff": {
        "kind": "python",
        "target": python_target("gnss_structural_displacement_signoff.py"),
        "summary": "Score multi-day static coordinates, continuity, noise floor, drift, and an injected displacement witness.",
    },
    "structural-displacement-workflow": {
        "kind": "python",
        "target": python_target("gnss_structural_displacement_workflow.py"),
        "summary": "Run the frozen R7 multi-day development or one-shot sealed holdout workflow.",
    },
    "integrity-geofence-signoff": {
        "kind": "python",
        "target": python_target("gnss_integrity_geofence_signoff.py"),
        "summary": "Truth-score empirical protection envelopes and fail-safe inside/outside/unknown geofence decisions.",
    },
    "integrity-geofence-workflow": {
        "kind": "python",
        "target": python_target("gnss_integrity_geofence_workflow.py"),
        "summary": "Build a qualified urban solution and run the frozen R8 empirical-envelope geofence decision workflow.",
    },
    "timing-holdover-signoff": {
        "kind": "python",
        "target": python_target("gnss_timing_holdover_signoff.py"),
        "summary": "Compare SPP receiver-clock telemetry with IGS final station clocks and assess simulated holdover.",
    },
    "timing-holdover-workflow": {
        "kind": "python",
        "target": python_target("gnss_timing_holdover_workflow.py"),
        "summary": "Acquire BRUX RINEX/IGS clocks, emit receiver-clock telemetry, and assess lock plus simulated holdover.",
    },
    "trajectory-bundle": {
        "kind": "python", "target": python_target("gnss_trajectory_bundle.py"),
        "summary": "Package and truth-score a versioned trajectory for SLAM, maps, or visualization.",
    },
    "trajectory-bundle-validate": {
        "kind": "python", "target": python_target("gnss_trajectory_bundle_validate.py"),
        "summary": "Validate trajectory hashes, frames, and consumer gates without rerunning a solver.",
    },
    "clas-application-decision": {
        "kind": "python", "target": python_target("gnss_clas_application_decision.py"),
        "summary": "Acquire, decode, truth-score, and gate one public PPC/QZSS CLAS application run.",
    },
    "ros2-doctor": {
        "kind": "python",
        "target": python_target("gnss_ros2_doctor.py"),
        "summary": "Check ROS2 receiver readiness, serial permissions, launch, record, and topic debug commands.",
    },
    "ros2-bag-doctor": {
        "kind": "python",
        "target": python_target("gnss_ros2_bag_doctor.py"),
        "summary": "Inspect ROS2 GNSS bag topics, rates, gaps, and raw-binary replayability.",
    },
    "field-report": {
        "kind": "python",
        "target": python_target("gnss_field_report.py"),
        "summary": "Aggregate setup, ROS2, bag, and robotics smoke diagnostics into Markdown/JSON reports.",
    },
    "spp": {
        "kind": "binary",
        "target": "gnss_spp",
        "summary": "Batch SPP post-processing from rover/nav RINEX files.",
    },
    "fgo": {
        "kind": "binary",
        "target": "gnss_fgo",
        "summary": "Batch factor-graph post-processing from rover/nav RINEX files.",
    },
    "fuse": {
        "kind": "binary",
        "target": "gnss_fuse",
        "summary": "GNSS/IMU fusion with SPP/RTK and validated tight-coupling presets.",
    },
    "online": {
        "kind": "binary",
        "target": "gnss_online",
        "summary": "Process received RTCM and IMU events sequentially, with explicit input age and reset metadata.",
    },
    "vel-d": {
        "kind": "binary",
        "target": "gnss_vel_d",
        "summary": "Taroz-style batch velocity and clock-drift estimation from Doppler.",
    },
    "pos-pd": {
        "kind": "binary",
        "target": "gnss_pos_pd",
        "summary": "Taroz-style batch position and clock estimation from pseudorange plus Doppler between epochs.",
    },
    "pos-pdc": {
        "kind": "binary",
        "target": "gnss_pos_pdc",
        "summary": "Taroz-style batch position and clock estimation from pseudorange, Doppler, and TDCP.",
    },
    "pos-vel-pd": {
        "kind": "binary",
        "target": "gnss_pos_vel_pd",
        "summary": "Taroz-style batch position, velocity, clock, and drift estimation from pseudorange plus Doppler.",
    },
    "pos-vel-pdc": {
        "kind": "binary",
        "target": "gnss_pos_vel_pdc",
        "summary": "Taroz-style batch position, velocity, clock, and drift estimation from pseudorange, Doppler, and TDCP.",
    },
    "compare-modes": {
        "kind": "python",
        "target": python_target("gnss_mode_compare.py"),
        "summary": "Run SPP/FGO/RTK on shared RINEX inputs and emit a mode-comparison JSON summary.",
    },
    "uncertainty-eval": {
        "kind": "python",
        "target": python_target("gnss_uncertainty_eval.py"),
        "summary": "Check reported per-epoch sigma (gnss solve --pos-uncertainty) against truth: normalized errors, exceedances, K*sigma Stanford bins (not a certified protection level).",
    },
    "taroz-pc-dogfood": {
        "kind": "python",
        "target": python_target("gnss_taroz_pc_dogfood.py"),
        "summary": "Regenerate taroz PC FGO outputs and verify intermediate/final parity.",
    },
    "taroz-p-dogfood": {
        "kind": "python",
        "target": python_target("gnss_taroz_p_dogfood.py"),
        "summary": "Regenerate taroz P FGO smoke outputs and verify raw-pseudorange configuration.",
    },
    "taroz-pd-dogfood": {
        "kind": "python",
        "target": python_target("gnss_taroz_pd_dogfood.py"),
        "summary": "Regenerate taroz position/velocity PD outputs and verify internal parity.",
    },
    "taroz-pos-vel-amb-pdc-dogfood": {
        "kind": "python",
        "target": python_target("gnss_taroz_pos_vel_amb_pdc_dogfood.py"),
        "summary": "Regenerate taroz position/velocity ambiguity PDC FGO outputs and verify parity.",
    },
    "taroz-observable-dogfood": {
        "kind": "python",
        "target": python_target("gnss_taroz_observable_dogfood.py"),
        "summary": "Regenerate taroz D/position PD/PDC/position-velocity PDC outputs and verify parity.",
    },
    "taroz-oracle-suite": {
        "kind": "python",
        "target": python_target("gnss_taroz_oracle_suite.py"),
        "summary": "Run all taroz MATLAB-oracle dogfood harnesses from one suite entrypoint.",
    },
    "ppc-taroz-amb-pdc-smoke": {
        "kind": "python",
        "target": python_target("gnss_ppc_taroz_amb_pdc_smoke.py"),
        "summary": "Run taroz ambiguity PDC FGO checks on PPC-Dataset runs.",
    },
    "ppc-spp-jump-sweep": {
        "kind": "python",
        "target": python_target("gnss_ppc_spp_jump_sweep.py"),
        "summary": "Sweep post-hoc SPP position-jump gates against a PPC reference trajectory.",
    },
    "ppc-spp-compare": {
        "kind": "python",
        "target": python_target("gnss_ppc_spp_compare.py"),
        "summary": "Compare multiple SPP .pos files against a PPC reference and render CSV/PNG artifacts.",
    },
    "ppc-spp-policy-report": {
        "kind": "python",
        "target": python_target("gnss_ppc_spp_policy_report.py"),
        "summary": "Summarize PPC SPP jump-gate policy sweep JSONs across runs.",
    },
    "ppc-spp-policy-suite": {
        "kind": "python",
        "target": python_target("gnss_ppc_spp_policy_suite.py"),
        "summary": "Run PPC SPP jump-gate sweeps, policy reports, and comparisons as one suite.",
    },
    "solve": {
        "kind": "binary",
        "target": "gnss_solve",
        "summary": "Batch RTK post-processing from rover/base/nav RINEX files.",
    },
    "ppp": {
        "kind": "binary",
        "target": "gnss_ppp",
        "summary": "Batch PPP post-processing from rover RINEX plus precise SP3/CLK products.",
    },
    "visibility": {
        "kind": "binary",
        "target": "gnss_visibility",
        "summary": "Analyze satellite visibility from rover/nav RINEX into azimuth/elevation/SNR CSV and summary JSON.",
    },
    "visibility-plot": {
        "kind": "python",
        "target": python_target("gnss_visibility_plot.py"),
        "summary": "Render a visibility CSV into a polar/elevation PNG quick-look.",
    },
    "nav-products": {
        "kind": "binary",
        "target": "gnss_nav_products",
        "summary": "Generate simple SP3/CLK precise-product files from observed epochs plus broadcast nav.",
    },
    "fetch-products": {
        "kind": "python",
        "target": python_target("gnss_fetch_products.py"),
        "summary": "Fetch and cache SP3/CLK/IONEX/DCB-style product files from local paths or URLs.",
    },
    "artifact-manifest": {
        "kind": "python",
        "target": python_target("gnss_artifact_manifest.py"),
        "summary": "Scan generated summaries and build a web/CI-friendly artifact manifest JSON.",
    },
    "rinex-info": {
        "kind": "binary",
        "target": "gnss_rinex_info",
        "summary": "Inspect RINEX headers and optionally count epochs or ephemerides.",
    },
    "stream": {
        "kind": "binary",
        "target": "gnss_stream",
        "summary": "Read and relay RTCM from file, NTRIP, or serial sources with optional decode summaries and relay sinks.",
    },
    "has-info": {
        "kind": "binary",
        "target": "gnss_has_info",
        "summary": "Decode Galileo HAS E6-B pages (UBX/SBF/cssrlib text) and dump MT1 messages and held corrections.",
    },
    "ubx-info": {
        "kind": "binary",
        "target": "gnss_ubx_info",
        "summary": "Inspect UBX NAV/RAWX/SFRBX files or serial streams and optionally export RAWX epochs to RINEX.",
    },
    "ionex-info": {
        "kind": "python",
        "target": python_target("gnss_ionex_info.py"),
        "summary": "Inspect IONEX headers, map counts, grid metadata, and auxiliary DCB blocks.",
    },
    "dcb-info": {
        "kind": "python",
        "target": python_target("gnss_dcb_info.py"),
        "summary": "Inspect Bias-SINEX or IONEX auxiliary DCB products and summarize systems/bias types.",
    },
    "nmea-info": {
        "kind": "python",
        "target": python_target("gnss_nmea_info.py"),
        "summary": "Inspect NMEA GGA/RMC logs or serial streams and print decoded position summaries.",
    },
    "novatel-info": {
        "kind": "python",
        "target": python_target("gnss_novatel_info.py"),
        "summary": "Inspect NovAtel ASCII BESTPOS/BESTVEL logs or serial streams.",
    },
    "sbp-info": {
        "kind": "python",
        "target": python_target("gnss_sbp_info.py"),
        "summary": "Inspect Swift Binary Protocol GPS_TIME/POS_LLH/VEL_NED logs or serial streams.",
    },
    "sbf-info": {
        "kind": "python",
        "target": python_target("gnss_sbf_info.py"),
        "summary": "Inspect Septentrio SBF PVTGeodetic/LBandTrackerStatus/P2PPStatus logs or serial streams.",
    },
    "trimble-info": {
        "kind": "python",
        "target": python_target("gnss_trimble_info.py"),
        "summary": "Inspect Trimble GSOF GENOUT Type 1/2/8 packets from file or serial input.",
    },
    "skytraq-info": {
        "kind": "python",
        "target": python_target("gnss_skytraq_info.py"),
        "summary": "Inspect SkyTraq binary epoch/raw/rawx/ack logs or serial streams.",
    },
    "binex-info": {
        "kind": "python",
        "target": python_target("gnss_binex_info.py"),
        "summary": "Inspect BINEX big-endian regular-CRC metadata/navigation/prototyping records from file or serial input.",
    },
    "qzss-l6-info": {
        "kind": "python",
        "target": python_target("gnss_qzss_l6_info.py"),
        "summary": "Inspect direct QZSS L6 250-byte frames and optionally export subframes, subtype 10 service-info packets, Compact SSR message inventory, or sampled corrections from subtype 1/2/3/4/5/6/7/8/9/11/12.",
    },
    "convert": {
        "kind": "binary",
        "target": "gnss_convert",
        "summary": "Convert RTCM or UBX input into RINEX 3.04 observation/navigation files and export UBX SFRBX frame metadata.",
    },
    "replay": {
        "kind": "binary",
        "target": "gnss_replay",
        "summary": "Replay rover/base observations from RINEX, UBX, or RTCM through the RTK solver.",
    },
    "live": {
        "kind": "binary",
        "target": "gnss_live",
        "summary": "Continuously solve RTCM or UBX rover input against RTCM base corrections into a live RTK solution file.",
    },
    "realtime-stress": {
        "kind": "python",
        "target": python_target("gnss_realtime_stress.py"),
        "summary": "Replay a recorded RINEX run as paced RTCM3 over TCP/NTRIP with fault injection and measure gnss live survival, latency, recovery, accuracy, RSS and batch parity.",
    },
    "rtcm-encode": {
        "kind": "binary",
        "target": "gnss_rtcm_encode",
        "summary": "Encode recorded RINEX observations (+ nav) into an RTCM3 stream with a per-epoch index for replay.",
    },
    "live-signoff": {
        "kind": "python",
        "target": python_target("gnss_live_signoff.py"),
        "summary": "Run gnss live with realtime/error-handling thresholds and emit summary JSON.",
    },
    "moving-base-signoff": {
        "kind": "python",
        "target": python_target("gnss_moving_base_signoff.py"),
        "summary": "Run a real moving-base replay/live dataset against reference baseline/heading CSV and emit summary JSON.",
    },
    "scorpion-moving-base-signoff": {
        "kind": "python",
        "target": python_target("gnss_scorpion_moving_base_signoff.py"),
        "summary": "Prepare and validate the public SCORPION moving-base ROS2 bag through replay plus receiver side-by-side output.",
    },
    "moving-base-prepare": {
        "kind": "python",
        "target": python_target("gnss_moving_base_prepare.py"),
        "summary": "Extract rover/base UBX files plus reference and optional receiver CSVs from a ROS2 moving-base bag.",
    },
    "moving-base-plot": {
        "kind": "python",
        "target": python_target("gnss_moving_base_plot.py"),
        "summary": "Render moving-base sign-off solution/reference pairs into a baseline and heading PNG quick-look.",
    },
    "rcv": {
        "kind": "python",
        "target": python_target("gnss_rcv.py"),
        "summary": "Run the live solver from an rtkrcv-style config file and emit status snapshots.",
    },
    "station": {
        "kind": "python",
        "target": python_target("gnss_station.py"),
        "summary": "Validate and manage a long-running RTK station with run artifacts and health status.",
    },
    "web": {
        "kind": "python",
        "target": python_target("gnss_web.py"),
        "summary": "Serve a local web UI for benchmark snapshots, live sign-offs, 2D trajectories, and receiver status.",
    },
    "stats": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "tools", "rtk_stats.py"),
        "summary": "Show text statistics for a .pos solution file.",
    },
    "compare": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "tools", "compare_rtklib.py"),
        "summary": "Compare libgnss++ output against RTKLIB output.",
    },
    "plot": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "tools", "plot_rtk.py"),
        "summary": "Generate ENU/time-series plots for one or two .pos files.",
    },
    "trackplot": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "tools", "plot_trajectory.py"),
        "summary": "Generate a 2D trajectory comparison plot with status colors.",
    },
    "rtklib2pos": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "scripts", "convert_rtklib_pos.py"),
        "summary": "Convert raw RTKLIB .pos output into libgnss++ .pos format.",
    },
    "pos2kml": {
        "kind": "python",
        "target": os.path.join(APPS_DIR, "compat", "gnss_pos2kml"),
        "summary": "Convert libgnss++ or RTKLIB .pos output into KML.",
    },
    "driving-compare": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "scripts", "generate_driving_comparison.py"),
        "summary": "Generate the UrbanNav/Odaiba comparison figure from solution files.",
    },
    "scorecard": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "scripts", "generate_odaiba_scorecard.py"),
        "summary": "Generate the Odaiba benchmark scorecard image.",
    },
    "social-card": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "scripts", "generate_odaiba_social_card.py"),
        "summary": "Generate a Twitter-ready Odaiba social card image.",
    },
    "architecture-card": {
        "kind": "python",
        "target": os.path.join(ROOT_DIR, "scripts", "generate_architecture_diagram.py"),
        "summary": "Generate a docs-friendly architecture diagram image.",
    },
    "reproduce": {
        "kind": "python",
        "target": python_target("gnss_reproduce.py"),
        "summary": "Reproduce README result numbers from tracked lane manifests and check them against expectations.",
    },
    "odaiba-benchmark": {
        "kind": "python",
        "target": python_target("gnss_odaiba_benchmark.py"),
        "summary": "Run the full libgnss++ vs RTKLIB Odaiba benchmark pipeline.",
    },
    "odaiba-scan": {
        "kind": "python",
        "target": python_target("gnss_odaiba_scan.py"),
        "summary": "Scan Odaiba in epoch windows and report reference-based metrics.",
    },
    "short-baseline-signoff": {
        "kind": "python",
        "target": python_target("gnss_short_baseline_signoff.py"),
        "summary": "Run a mixed-GNSS short-baseline static sign-off and emit summary JSON.",
    },
    "rtk-kinematic-signoff": {
        "kind": "python",
        "target": python_target("gnss_rtk_kinematic_signoff.py"),
        "summary": "Run the bundled mixed-GNSS RTK kinematic sign-off and emit summary JSON.",
    },
    "ppp-static-signoff": {
        "kind": "python",
        "target": python_target("gnss_ppp_static_signoff.py"),
        "summary": "Run the bundled static PPP sign-off and emit summary JSON.",
    },
    "ppp-kinematic-signoff": {
        "kind": "python",
        "target": python_target("gnss_ppp_kinematic_signoff.py"),
        "summary": "Run the bundled kinematic PPP sign-off against an RTK reference and emit summary JSON.",
    },
    "ppp-iers-solid-tide-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_solid_tide_bench.py"),
        "summary": "Run the same PPP setup with and without --use-iers-solid-tide and summarize the per-epoch displacement (Phase C-1 truth-bench harness).",
    },
    "ppp-iers-pole-tide-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_pole_tide_bench.py"),
        "summary": "Run the same PPP setup with and without --use-iers-pole-tide and summarize the per-epoch displacement (Phase D-1 truth-bench harness; requires --eop-c04).",
    },
    "ppp-iers-atm-tidal-loading-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_atm_tidal_loading_bench.py"),
        "summary": "Run the same PPP setup with and without --use-iers-atm-tidal-loading and summarize the per-epoch displacement (Phase D-3 truth-bench harness; requires --atm-tidal-loading).",
    },
    "ppp-iers-atm-tidal-loading-multisite-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_atm_tidal_loading_multisite_bench.py"),
        "summary": "Run the Phase D-3 atmospheric-tidal-loading bench across an arbitrary list of IGS stations and emit an aggregate per-site distribution summary.",
    },
    "vmf-atl": {
        "kind": "python",
        "target": python_target("gnss_vmf_atl.py"),
        "summary": "Fetch or read VMF site-wise GNSS tidal APL coefficients and write libgnss++ ATL coefficient files.",
    },
    "ppp-iers-pole-tide-multisite-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_pole_tide_multisite_bench.py"),
        "summary": "Run the Phase D-1 pole-tide bench across an arbitrary list of IGS stations and emit an aggregate per-site distribution summary (gates the use_iers_pole_tide flip-default).",
    },
    "ppp-iers-sub-daily-eop-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_sub_daily_eop_bench.py"),
        "summary": "Run the same PPP setup with and without --use-iers-sub-daily-eop (pole-tide ON in both runs) and summarize the per-epoch displacement (Phase D-2 truth-bench harness; requires --eop-c04).",
    },
    "ppp-iers-sub-daily-eop-multisite-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_sub_daily_eop_multisite_bench.py"),
        "summary": "Run the Phase D-2 sub-daily-EOP bench across an arbitrary list of IGS stations and emit an aggregate per-site distribution summary.",
    },
    "ppp-iers-truth-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_truth_bench.py"),
        "summary": "Run an end-to-end PPP truth bench with all IERS defaults ON, comparing the converged static position to the RINEX header's APPROX POSITION XYZ; --ab also runs all-IERS-OFF to report the on/off residual delta.",
    },
    "ppp-iers-truth-multisite-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_truth_multisite_bench.py"),
        "summary": "Run the IERS end-to-end truth bench across an arbitrary list of IGS stations and emit an aggregate per-site residual distribution.",
    },
    "ppp-iers-ocean-loading-bench": {
        "kind": "python",
        "target": python_target("gnss_ppp_iers_ocean_loading_bench.py"),
        "summary": "Run the same PPP setup with and without --use-iers-ocean-loading and summarize the per-epoch displacement (Phase A-2b HARDISP truth-bench harness).",
    },
    "ppp-products-signoff": {
        "kind": "python",
        "target": python_target("gnss_ppp_products_signoff.py"),
        "summary": "Run static, kinematic, or PPC PPP sign-off with fetched SP3/CLK/IONEX/DCB products and emit summary JSON.",
    },
    "observation-analysis": {
        "kind": "python",
        "target": python_target("gnss_observation_analysis.py"),
        "summary": "Export satellite code residuals, SNR and carrier-continuity diagnostics through the public Python API.",
    },
    "ppc-native-replay": {
        "kind": "python",
        "target": python_target("gnss_ppc_native_replay.py"),
        "summary": "Build and regenerate PPC RTK/IMU baselines from raw inputs with complete run provenance.",
    },
    "ppc-demo": {
        "kind": "python",
        "target": python_target("gnss_ppc_demo.py"),
        "summary": "Run an external PPC-Dataset Tokyo/Nagoya run through RTK or PPP and compare against reference.csv.",
    },
    "ppc-rtk-signoff": {
        "kind": "python",
        "target": python_target("gnss_ppc_rtk_signoff.py"),
        "summary": "Run the PPC-Dataset RTK sign-off profile for Tokyo/Nagoya, with optional RTKLIB side-by-side gates.",
    },
    "ppc-coverage-matrix": {
        "kind": "python",
        "target": python_target("gnss_ppc_coverage_matrix.py"),
        "summary": "Run all six PPC Tokyo/Nagoya RTK coverage-profile replays and emit JSON/Markdown summaries.",
    },
    "public-rtk-benchmarks": {
        "kind": "python",
        "target": python_target("gnss_public_rtk_benchmarks.py"),
        "summary": "List public moving-RTK benchmark profiles, adapter status, and caveats.",
    },
    "smartloc-adapter": {
        "kind": "python",
        "target": python_target("gnss_smartloc_adapter.py"),
        "summary": "Export smartLoc NAV-POSLLH.csv into reference and receiver CSV comparison artifacts.",
    },
    "smartloc-signoff": {
        "kind": "python",
        "target": python_target("gnss_smartloc_signoff.py"),
        "summary": "Run smartLoc adapter export plus receiver-fix comparison gates.",
    },
    "smartphone-gnss-adapter": {
        "kind": "python",
        "target": python_target("gnss_smartphone_gnss_adapter.py"),
        "summary": "Validate and normalize Google Smartphone Decimeter Challenge raw GNSS and truth CSVs.",
    },
    "smartphone-mimir-adapter": {
        "kind": "python",
        "target": python_target("gnss_smartphone_mimir_adapter.py"),
        "summary": "Fail-closed adapter for Mimir (Nantes dataset) Raw.csv/PSR.csv: RINEX observations plus GPST barometer CSV.",
    },
    "smartphone-baro-eval": {
        "kind": "python",
        "target": python_target("gnss_smartphone_baro_eval.py"),
        "summary": "Score a smartphone SPP POS against the weak Awinda reference (H/V RMSE, P95, availability, jumps).",
    },
    "smartphone-baro-nantes": {
        "kind": "python",
        "target": python_target("gnss_smartphone_baro_nantes_runner.py"),
        "summary": "Run barometer OFF vs ON standalone SPP on Nantes/Mimir runs and score against the Awinda reference.",
    },
    "smartphone-gnss-signoff": {
        "kind": "python",
        "target": python_target("gnss_smartphone_gnss_signoff.py"),
        "summary": "Truth-score a smartphone libgnss++ POS and enforce R5 availability, error, and gap gates.",
    },
    "smartphone-quality-report": {
        "kind": "python",
        "target": python_target("gnss_smartphone_quality_report.py"),
        "summary": "Correlate smartphone GNSS quality telemetry with existing sign-off errors by fixed bucket and route segment.",
    },
    "smartphone-raw-quality-control": {
        "kind": "python",
        "target": python_target("gnss_smartphone_raw_quality_control.py"),
        "summary": "Audit truth-free smartphone raw GNSS observables and run the frozen robust SPP fallback candidate.",
    },
    "smartphone-native-gnss-pdc": {
        "kind": "python",
        "target": python_target("gnss_smartphone_native_gnss_pdc.py"),
        "summary": "Run the native raw-Android GNSS/PDC executable with an atomic raw/nav/binary provenance manifest.",
    },
    "smartphone-kaggle-submit": {
        "kind": "python",
        "target": python_target("gnss_smartphone_kaggle_submit.py"),
        "summary": "Generate a truth-free GSDC 2023 phone submission CSV and provenance manifest.",
    },
    "smartphone-kaggle-evaluate": {
        "kind": "python",
        "target": python_target("gnss_smartphone_kaggle_evaluate.py"),
        "summary": "Audit GSDC 2023 submissions with WGS84/Vincenty and spherical/Haversine P50/P95 variants.",
    },
    "smartphone-trajectory-smoother": {
        "kind": "python",
        "target": python_target("gnss_smartphone_trajectory_smoother.py"),
        "summary": "Development-only truth-free constant-velocity Kalman/RTS smoothing with device-key interpolation.",
    },
    "smartphone-trajectory-smoother-eval": {
        "kind": "python",
        "target": python_target("gnss_smartphone_trajectory_smoother_eval.py"),
        "summary": "Select and validate frozen truth-free smartphone trajectory smoother parameters on development only.",
    },
    "smartphone-tdcp-trajectory": {
        "kind": "python",
        "target": python_target("gnss_smartphone_tdcp_trajectory.py"),
        "summary": "Run truth-free TDCP/ADR displacement-constrained smartphone trajectory postprocess.",
    },
    "smartphone-doppler-position": {
        "kind": "python",
        "target": python_target("gnss_smartphone_doppler_position.py"),
        "summary": "Run a truth-free bounded pseudorange-rate Doppler position update around handset WLS.",
    },
    "smartphone-gnss-workflow": {
        "kind": "python",
        "target": python_target("gnss_smartphone_gnss_workflow.py"),
        "summary": "Run the frozen R5 archive-to-POS/KML/PNG/sign-off workflow and emit a hash manifest.",
    },
    "smartphone-generalization": {
        "kind": "python",
        "target": python_target("gnss_smartphone_generalization.py"),
        "summary": "Inventory train-only GSDC routes and compare fixed Galileo/Hatch and causal IMU trajectory lanes without opening holdout data.",
    },
    "smartphone-reacquisition-eval": {
        "kind": "python",
        "target": python_target("gnss_smartphone_reacquisition_eval.py"),
        "summary": "Evaluate bounded truth-free smartphone smoother reacquisition on frozen train/validation routes without opening holdout data.",
    },
    "smartphone-reacquisition-conservative-eval": {
        "kind": "python",
        "target": python_target("gnss_smartphone_reacquisition_conservative_eval.py"),
        "summary": "Evaluate conservative truth-free smartphone reacquisition bounds on a frozen new validation route and byte-identical main regression.",
    },
    "smartphone-wls-position": {
        "kind": "python",
        "target": python_target("gnss_smartphone_wls.py"),
        "summary": "Extract and validate Android handset WLS ECEF positions into WGS84/POS artifacts with a truth-free atomic manifest.",
    },
    "smartphone-wls-multi-phone-ensemble-eval": {
        "kind": "python",
        "target": python_target("gnss_smartphone_wls_multi_phone_ensemble_eval.py"),
        "summary": "Evaluate a fixed truth-free multi-phone handset-WLS ensemble on train routes and one new validation route while keeping the next holdout sealed.",
    },
    "smartphone-wls-test-batch": {
        "kind": "python",
        "target": python_target("gnss_smartphone_wls_test_batch.py"),
        "summary": "Generate a truth-free full GSDC test submission with sealed v1.4 WLS/ensemble authorization and sample-key order.",
    },
    "performance-report": {
        "kind": "python",
        "target": python_target("gnss_performance_report.py"),
        "summary": "Summarize native per-epoch SPP/RTK timing CSVs by GPST interval.",
    },
    "uav-mars-acquire": {
        "kind": "python",
        "target": python_target("gnss_uav_mars_acquire.py"),
        "summary": "Acquire and fail-closed validate a frozen MARS-LVIG UAV ROS1 bag for the R6 workflow.",
    },
    "uav-mars-adapter": {
        "kind": "python",
        "target": python_target("gnss_uav_mars_adapter.py"),
        "summary": "Extract MARS-LVIG raw GNSS, IMU, attitude, and independent RTK truth under the frozen R6 frame contract.",
    },
    "uav-mars-signoff": {
        "kind": "python",
        "target": python_target("gnss_uav_mars_signoff.py"),
        "summary": "Truth-score an R6 UAV flight and publish separate navigation, mapping, and visualization decisions.",
    },
    "uav-mars-workflow": {
        "kind": "python",
        "target": python_target("gnss_uav_mars_workflow.py"),
        "summary": "Run the frozen R6 UAV container-to-POS/KML/PNG/sign-off workflow and emit a hash manifest.",
    },
    "clas-ppp": {
        "kind": "python",
        "target": python_target("gnss_clas_ppp.py"),
        "summary": "Run PPP with a named CLAS/MADOCA correction profile over RTCM, compact sampled transport, or raw QZSS L6 subtype 1/2/3/4/5/6/7/8/9/11/12 input.",
    },
    "ros2-solution-node": {
        "kind": "binary",
        "target": "gnss_solution_node",
        "summary": "Publish a .pos solution file as ROS2 NavSatFix, PoseStamped, Path, status, and satellite-count topics.",
    },
}


def command_kinds() -> list[str]:
    return sorted({metadata["kind"] for metadata in COMMANDS.values()})


def command_matches_query(record: dict[str, str], query: str) -> bool:
    query_words = query.lower().replace("_", "-").split()
    haystack = " ".join(
        [
            record["name"],
            record["kind"],
            record["summary"],
        ]
    ).lower()
    return all(word in haystack for word in query_words)


def command_records(
    kind_filter: str | None = None,
    query: str | None = None,
    limit: int | None = None,
) -> list[dict[str, str]]:
    records: list[dict[str, str]] = []
    for name, metadata in sorted(COMMANDS.items()):
        kind = metadata["kind"]
        if kind_filter is not None and kind != kind_filter:
            continue
        record = {
            "name": name,
            "kind": kind,
            "summary": metadata["summary"],
        }
        if query is not None and not command_matches_query(record, query):
            continue
        records.append(record)
        if limit is not None and len(records) >= limit:
            break
    return records


def format_command_records(
    records: list[dict[str, str]],
    *,
    query: str | None = None,
) -> str:
    width = max((len(record["name"]) for record in records), default=7)
    lines = [f"Commands matching `{query}`:" if query is not None else "Commands:"]
    if not records:
        lines.append("  (none)")
        lines.extend(["", "Run `gnss commands` to list all registered commands."])
        return "\n".join(lines)
    for record in records:
        lines.append(f"  {record['name']:<{width}}  {record['summary']}")
    lines.extend(["", "Run `gnss help <command>` for command-specific options."])
    return "\n".join(lines)


def usage() -> str:
    lines = [
        "Usage: gnss <command> [args...]",
        "",
        format_command_records(command_records()),
    ]
    lines.extend(
        [
            "",
            "Examples:",
            "  python3 apps/gnss.py commands",
            "  python3 apps/gnss.py commands --json",
            "  python3 apps/gnss.py help doctor",
            "  python3 apps/gnss.py doctor",
            "  python3 apps/gnss.py demo",
            "  python3 apps/gnss.py robotics-smoke --profile realtime",
            "  python3 apps/gnss.py ros2-doctor --device /dev/ttyUSB0",
            "  python3 apps/gnss.py solve --data-dir data/driving --out output/rtk_solution.pos",
            "  python3 apps/gnss.py spp --obs data/rover_static.obs --nav data/navigation_static.nav --out output/spp_solution.pos",
            "  python3 apps/gnss.py fgo --preset real-data-fixed --obs data/rover_static.obs --nav data/navigation_static.nav --out output/fgo_solution.pos --summary-json output/fgo_summary.json",
            "  python3 apps/gnss.py vel-d --obs data/rover_1Hz.obs --nav data/base.nav --seed-pos data/rover_1Hz_spp.pos --out-csv output/velocity.csv",
            "  python3 apps/gnss.py pos-pd --obs data/rover_1Hz.obs --nav data/base.nav --seed-pos data/rover_1Hz_spp.pos --out-csv output/pos_pd_state.csv",
            "  python3 apps/gnss.py pos-pdc --obs data/rover_1Hz.obs --nav data/base.nav --seed-pos data/rover_1Hz_spp.pos --out-csv output/pos_pdc_state.csv",
            "  python3 apps/gnss.py pos-vel-pd --obs data/rover_1Hz.obs --nav data/base.nav --seed-pos data/rover_1Hz_spp.pos --out-csv output/pd_state.csv",
            "  python3 apps/gnss.py pos-vel-pdc --obs data/rover_1Hz.obs --nav data/base.nav --seed-pos data/rover_1Hz_spp.pos --out-csv output/pdc_state.csv",
            "  python3 apps/gnss.py compare-modes --fgo-preset real-data --obs data/rover_kinematic.obs --base data/base_kinematic.obs --nav data/navigation_kinematic.nav --reference-csv data/reference.csv --max-epochs 120",
            "  python3 apps/gnss.py taroz-p-dogfood --out-dir output/dogfood/taroz_p_dogfood_current",
            "  python3 apps/gnss.py taroz-pd-dogfood --out-dir output/dogfood/taroz_pd_dogfood_current",
            "  python3 apps/gnss.py taroz-pc-dogfood --out-dir output/dogfood/taroz_pc_dogfood_current",
            "  python3 apps/gnss.py taroz-observable-dogfood --mode pos-pdc --out-dir output/dogfood/taroz_pos_pdc_dogfood_current",
            "  python3 apps/gnss.py taroz-pos-vel-amb-pdc-dogfood --out-dir output/dogfood/taroz_pos_vel_amb_pdc_dogfood_current",
            "  python3 apps/gnss.py taroz-oracle-suite --native-bin-dir build/apps --out-root output/dogfood/taroz_oracle_suite_current",
            "  python3 apps/gnss.py ppc-taroz-amb-pdc-smoke --dataset-root /datasets/PPC-Dataset --max-epochs 200 --generate-spp-seed",
            "  python3 apps/gnss.py compare-modes --modes spp,fgo,rtk --spp-pos output/spp.pos --fgo-pos output/fgo.pos --rtk-pos output/rtk.pos",
            "  python3 apps/gnss.py compare-modes --modes fgo,rtk --fgo-pos output/fgo.pos --rtk-pos output/rtk.pos --require-pair-p95-3d-max fgo:rtk=2.0",
            "  python3 apps/gnss.py visibility --obs data/rover_static.obs --nav data/navigation_static.nav --csv output/visibility.csv --summary-json output/visibility.json --max-epochs 60",
            "  python3 apps/gnss.py visibility-plot output/visibility.csv output/visibility.png",
            "  python3 apps/gnss.py solve --rover data/rover_kinematic.obs --base data/base_kinematic.obs --nav data/navigation_kinematic.nav --iono est --max-epochs 5",
            "  python3 apps/gnss.py ppp --static --obs data/rover_static.obs --nav data/navigation_static.nav --sp3 precise.sp3 --clk precise.clk --antex igs20.atx --receiver-antenna-type \"TRM59800.80     NONE\" --blq station.blq --out output/ppp_solution.pos",
            "  python3 apps/gnss.py ppp --kinematic --enable-ar --convergence-min-epochs 4 --ar-ratio-threshold 2.0 --obs rover.obs --sp3 precise.sp3 --clk precise.clk --out output/ppp_ar.pos",
            "  python3 apps/gnss.py nav-products --obs data/rover_static.obs --nav data/navigation_static.nav --sp3-out output/static_products.sp3 --clk-out output/static_products.clk --max-epochs 60",
            "  python3 apps/gnss.py fetch-products --date 2024-01-02 --product sp3=https://example.net/{yyyy}{doy}.sp3.gz --product clk=file:///data/{yyyy}{doy}.clk.gz --summary-json output/products.json",
            "  python3 apps/gnss.py artifact-manifest --root . --output output/artifact_manifest.json",
            "  python3 apps/gnss.py stream --input ntrip://user:pass@caster:2101/MOUNT --limit 10",
            "  python3 apps/gnss.py stream --input tcp://127.0.0.1:9000 --limit 10",
            "  python3 apps/gnss.py stream --input correction.rtcm3 --output serial:///dev/ttyUSB1?baud=115200 --limit 10",
            "  python3 apps/gnss.py stream --input correction.rtcm3 --output tcp://127.0.0.1:9000 --limit 10",
            "  python3 apps/gnss.py web --port 8085 --rcv-status output/receiver.status.json",
            "  python3 apps/gnss.py ubx-info --input logs/session.ubx --decode-observations",
            "  python3 apps/gnss.py ubx-info --input serial:///dev/ttyACM0?baud=115200 --limit 10",
            "  python3 apps/gnss.py ionex-info --input products/codg0020.24i --summary-json output/ionex.json",
            "  python3 apps/gnss.py dcb-info --input products/CAS0MGXRAP_20240020000_01D_01D_DCB.BSX --summary-json output/dcb.json",
            "  python3 apps/gnss.py nmea-info --input serial:///dev/ttyUSB0?baud=9600 --limit 10",
            "  python3 apps/gnss.py novatel-info --input logs/novatel.log --decode-bestpos --decode-bestvel",
            "  python3 apps/gnss.py novatel-info --input serial:///dev/ttyUSB0?baud=115200 --limit 10",
            "  python3 apps/gnss.py sbp-info --input logs/session.sbp --decode-time --decode-pos --decode-vel",
            "  python3 apps/gnss.py sbp-info --input serial:///dev/ttyUSB0?baud=115200 --limit 10",
            "  python3 apps/gnss.py sbf-info --input logs/session.sbf --decode-pvt --decode-lband --decode-p2pp",
            "  python3 apps/gnss.py sbf-info --input serial:///dev/ttyUSB0?baud=115200 --limit 10",
            "  python3 apps/gnss.py trimble-info --input logs/session.gsof --decode-time --decode-llh --decode-vel",
            "  python3 apps/gnss.py trimble-info --input serial:///dev/ttyUSB0?baud=115200 --limit 10",
            "  python3 apps/gnss.py skytraq-info --input logs/session.stq --decode-epoch --decode-raw --decode-ack",
            "  python3 apps/gnss.py skytraq-info --input serial:///dev/ttyUSB0?baud=115200 --limit 10",
            "  python3 apps/gnss.py binex-info --input logs/session.bnx --decode-metadata --decode-nav --decode-proto",
            "  python3 apps/gnss.py binex-info --input serial:///dev/ttyUSB0?baud=115200 --limit 10",
            "  python3 apps/gnss.py qzss-l6-info --input logs/qzss_l6.bin --show-preview --extract-data-parts output/qzss_l6_frames.csv --extract-subframes output/qzss_l6_subframes.csv --extract-compact-messages output/qzss_l6_messages.csv",
            "  python3 apps/gnss.py qzss-l6-info --input serial:///dev/ttyUSB0?baud=115200 --limit 10",
            "  python3 apps/gnss.py convert --format ubx --input logs/session.ubx --obs-out output/session.obs",
            "  python3 apps/gnss.py convert --format ubx --input logs/session.ubx --nav-out output/session.nav",
            "    # exports GPS/QZSS/Galileo/GLONASS/BeiDou broadcast nav from RXM-SFRBX when available",
            "  python3 apps/gnss.py convert --format ubx --input logs/session.ubx --nav-rinex-out output/session_sfrbx.nav",
            "    # library SFRBX decoder (checked, with the GPS Klobuchar GPSA/GPSB header lines); needs RAWX in the log for GPS/QZSS/GLONASS",
            "  python3 apps/gnss.py convert --format ubx --input logs/session.ubx --sfrbx-out output/session_sfrbx.csv",
            "  python3 apps/gnss.py social-card --lib-pos output/rtk_solution.pos --rtklib-pos output/driving_rtklib_rtk.pos --reference-csv data/driving/Tokyo_Data/Odaiba/reference.csv --output docs/driving_odaiba_social_card.png",
            "  python3 apps/gnss.py architecture-card --output docs/libgnsspp_architecture.png",
            "  python3 apps/gnss.py convert --format rtcm --input tcp://127.0.0.1:9000 --obs-out output/correction.obs",
            "  python3 apps/gnss.py convert --format ubx --input serial:///dev/ttyACM0?baud=115200 --obs-out output/stream.obs --limit 10",
            "  python3 apps/gnss.py replay --rover-rinex data/rover_kinematic.obs --base-rinex data/base_kinematic.obs --nav-rinex data/navigation_kinematic.nav --out output/replay.pos",
            "  python3 apps/gnss.py live --rover-rtcm rover.rtcm3 --base-rtcm base.rtcm3 --nav-rinex nav.rnx",
            "  python3 apps/gnss.py live-signoff --rover-rtcm rover.rtcm3 --base-rtcm base.rtcm3 --out output/live.pos --summary-json output/live_summary.json --require-written-solutions-min 3 --require-realtime-factor-min 1.0",
            "  python3 apps/gnss.py rcv start --config configs/examples/live.example.conf --status-out output/receiver_status.json",
            "  python3 apps/gnss.py rcv status --status-out output/receiver_status.json --wait-seconds 5",
            "  python3 apps/gnss.py rcv status --status-out output/receiver_status.json --tail-log-lines 20",
            "  python3 apps/gnss.py rcv reload --status-out output/receiver_status.json --wait-seconds 1",
            "  python3 apps/gnss.py station check --config configs/examples/station.example.toml",
            "  python3 apps/gnss.py station start --config configs/examples/station.example.toml",
            "  python3 apps/gnss.py station status --config configs/examples/station.example.toml --wait-seconds 5",
            "  python3 apps/gnss.py stats output/rtk_solution.pos",
            "  python3 apps/gnss.py compare output/rtk_solution.pos output/driving_rtklib_rtk.pos",
            "  python3 apps/gnss.py odaiba-benchmark --rtklib-bin /path/to/rnx2rtkp",
            "  python3 apps/gnss.py odaiba-benchmark --rtklib-bin /path/to/rnx2rtkp --malib-bin /path/to/malib/rnx2rtkp",
            "  python3 apps/gnss.py odaiba-benchmark --rtklib-bin /path/to/rnx2rtkp --require-all-epochs-min 11000 --require-common-epoch-pairs-min 8000 --require-lib-all-p95-h-max 8.0 --require-lib-common-median-h-max 0.8 --require-lib-common-p95-h-max 6.5",
            "  python3 apps/gnss.py odaiba-scan --glonass-ar autocal --window-size 1000",
            "  python3 apps/gnss.py short-baseline-signoff --max-epochs 120 --require-fix-rate-min 95 --require-mean-error-max 0.15 --require-max-error-max 0.6 --require-mean-sats-min 14",
            "  python3 apps/gnss.py rtk-kinematic-signoff --max-epochs 120 --require-valid-epochs-min 120 --require-fix-rate-min 95 --require-mean-error-max 3.0 --require-max-error-max 3.0 --require-mean-sats-min 25",
            "  python3 apps/gnss.py ppp-static-signoff --max-epochs 120 --require-valid-epochs-min 120 --require-mean-error-max 1.5 --require-max-error-max 1.5 --require-mean-sats-min 6.0 --require-ppp-solution-rate-min 100",
            "  python3 apps/gnss.py ppp-static-signoff --enable-ar --generate-products --ar-ratio-threshold 1.5 --require-mean-error-max 5.0 --require-max-error-max 6.0 --require-ppp-fixed-epochs-min 1 --require-ppp-solution-rate-min 100",
            "  python3 apps/gnss.py ppp-kinematic-signoff --max-epochs 120 --require-common-epoch-pairs-min 120 --require-reference-fix-rate-min 95 --require-converged --require-convergence-time-max 300 --require-mean-error-max 7.0 --require-p95-error-max 7.0 --require-max-error-max 7.0 --require-mean-sats-min 18 --require-ppp-solution-rate-min 100",
            "  python3 apps/gnss.py ppc-demo --dataset-root /datasets/PPC-Dataset --city tokyo --run run1 --solver rtk --require-realtime-factor-min 1.0 --summary-json output/ppc_tokyo_run1_rtk_summary.json",
            "  python3 apps/gnss.py ppc-rtk-signoff --dataset-root /datasets/PPC-Dataset --city tokyo --rtklib-bin /path/to/rnx2rtkp",
            "  python3 apps/gnss.py ppc-coverage-matrix --dataset-root /datasets/PPC-Dataset --rtklib-root output/benchmark --markdown-output output/ppc_coverage_matrix.md",
            "  python3 apps/gnss.py public-rtk-benchmarks --format markdown",
            "  python3 apps/gnss.py smartloc-adapter --input-url https://www.tu-chemnitz.de/projekt/smartLoc/gnss_dataset/berlin/scenario1/berlin1_potsdamer_platz.zip --reference-csv output/smartloc_reference.csv --receiver-csv output/smartloc_ublox.csv --raw-csv output/smartloc_rawx.csv --obs-rinex output/smartloc_rover.obs",
            "  python3 apps/gnss.py smartloc-signoff --input-url https://www.tu-chemnitz.de/projekt/smartLoc/gnss_dataset/berlin/scenario1/berlin1_potsdamer_platz.zip --output-dir output/smartloc --require-matched-epochs-min 100",
            "  python3 apps/gnss.py clas-ppp --profile madoca --obs data/rover_static.obs --nav data/navigation_static.nav --ssr-rtcm ntrip://caster/MOUNT --out output/madoca_ppp.pos --summary-json output/madoca_ppp_summary.json",
            "  python3 apps/gnss.py clas-ppp --profile clas --obs data/rover_static.obs --nav data/navigation_static.nav --compact-ssr corrections.compact.csv --out output/clas_ppp.pos --summary-json output/clas_ppp_summary.json",
            "  python3 apps/gnss.py clas-ppp --profile clas --obs data/rover_static.obs --nav data/navigation_static.nav --qzss-l6 logs/qzss_l6.bin --qzss-gps-week 2200 --out output/clas_l6.pos --summary-json output/clas_l6_summary.json",
            "  python3 apps/gnss.py ros2-solution-node --ros-args -p solution_file:=output/rtk_solution.pos -p max_messages:=1",
            "",
            "On Windows, use: py apps\\gnss.py <command> ...",
        ]
    )
    return "\n".join(lines)


def suggest_commands(command_name: str, *, limit: int = 3) -> list[str]:
    suggestions: list[str] = []
    normalized = command_name.replace("_", "-")
    if normalized in COMMANDS:
        suggestions.append(normalized)

    for match in difflib.get_close_matches(
        normalized,
        sorted(COMMANDS),
        n=limit,
        cutoff=0.55,
    ):
        if match not in suggestions:
            suggestions.append(match)
        if len(suggestions) >= limit:
            break
    return suggestions


def unknown_command_message(command_name: str) -> str:
    lines = [f"Error: unknown command `{command_name}`."]
    suggestions = suggest_commands(command_name)
    if suggestions:
        lines.append("")
        if len(suggestions) == 1:
            lines.append(f"Did you mean `{suggestions[0]}`?")
        else:
            lines.append("Did you mean one of these?")
            for name in suggestions:
                lines.append(f"  {name:<22} {COMMANDS[name]['summary']}")
    lines.extend(["", usage()])
    return "\n".join(lines)


def help_usage() -> str:
    return "\n".join(
        [
            "Usage: gnss help [command]",
            "",
            "Show top-level help, or show the named command's own --help output.",
            "",
            "Examples:",
            "  python3 apps/gnss.py help",
            "  python3 apps/gnss.py help doctor",
            "  python3 apps/gnss.py help clas-ppp",
        ]
    )


def commands_usage() -> str:
    return "\n".join(
        [
            "Usage: gnss commands [--json] [--kind KIND] [--query TEXT] [--limit N]",
            "",
            "List registered dispatcher commands without invoking solver binaries.",
            "",
            "Options:",
            "  --json       Emit a machine-readable command registry.",
            f"  --kind KIND  Filter by command kind: {', '.join(command_kinds())}.",
            "  --query TEXT Search command names, kinds, and summaries.",
            "  --limit N    Return at most N commands after filtering.",
            "",
            "Examples:",
            "  python3 apps/gnss.py commands",
            "  python3 apps/gnss.py commands --json",
            "  python3 apps/gnss.py commands --kind python",
            "  python3 apps/gnss.py commands --query ppp --limit 10",
        ]
    )


def run_help(args: list[str]) -> int:
    if not args:
        print(usage())
        return 0
    if args == ["-h"] or args == ["--help"]:
        print(help_usage())
        return 0
    if len(args) > 1:
        print(
            f"Error: gnss help accepts at most one command, got {len(args)}.",
            "",
            help_usage(),
            sep="\n",
            file=sys.stderr,
        )
        return 2
    return dispatch_command(args[0], ["--help"])


def run_commands(args: list[str]) -> int:
    emit_json = False
    kind_filter: str | None = None
    query: str | None = None
    limit: int | None = None
    index = 0
    valid_kinds = set(command_kinds())

    while index < len(args):
        arg = args[index]
        if arg in ("-h", "--help"):
            print(commands_usage())
            return 0
        if arg == "--json":
            emit_json = True
            index += 1
            continue
        if arg == "--query":
            if index + 1 >= len(args):
                print(
                    "Error: --query requires a non-empty search string.",
                    "",
                    commands_usage(),
                    sep="\n",
                    file=sys.stderr,
                )
                return 2
            query = args[index + 1].strip()
            if not query:
                print(
                    "Error: --query requires a non-empty search string.",
                    "",
                    commands_usage(),
                    sep="\n",
                    file=sys.stderr,
                )
                return 2
            index += 2
            continue
        if arg.startswith("--query="):
            query = arg.split("=", 1)[1].strip()
            if not query:
                print(
                    "Error: --query requires a non-empty search string.",
                    "",
                    commands_usage(),
                    sep="\n",
                    file=sys.stderr,
                )
                return 2
            index += 1
            continue
        if arg == "--limit":
            if index + 1 >= len(args):
                print(
                    "Error: --limit requires a positive integer.",
                    "",
                    commands_usage(),
                    sep="\n",
                    file=sys.stderr,
                )
                return 2
            raw_limit = args[index + 1]
            index += 2
        elif arg.startswith("--limit="):
            raw_limit = arg.split("=", 1)[1]
            index += 1
        else:
            raw_limit = None

        if raw_limit is not None:
            try:
                limit = int(raw_limit)
            except ValueError:
                print(
                    f"Error: invalid --limit value `{raw_limit}`; expected a positive integer.",
                    "",
                    commands_usage(),
                    sep="\n",
                    file=sys.stderr,
                )
                return 2
            if limit < 1:
                print(
                    f"Error: invalid --limit value `{raw_limit}`; expected a positive integer.",
                    "",
                    commands_usage(),
                    sep="\n",
                    file=sys.stderr,
                )
                return 2
            continue
        if arg == "--kind":
            if index + 1 >= len(args):
                print(
                    "Error: --kind requires one of: "
                    + ", ".join(sorted(valid_kinds))
                    + ".",
                    "",
                    commands_usage(),
                    sep="\n",
                    file=sys.stderr,
                )
                return 2
            kind_filter = args[index + 1]
            index += 2
        elif arg.startswith("--kind="):
            kind_filter = arg.split("=", 1)[1]
            index += 1
        else:
            print(
                f"Error: unknown option for gnss commands: `{arg}`.",
                "",
                commands_usage(),
                sep="\n",
                file=sys.stderr,
            )
            return 2

        if kind_filter is not None and kind_filter not in valid_kinds:
            print(
                f"Error: unknown command kind `{kind_filter}`. "
                f"Expected one of: {', '.join(sorted(valid_kinds))}.",
                "",
                commands_usage(),
                sep="\n",
                file=sys.stderr,
            )
            return 2

    records = command_records(kind_filter, query, limit)
    if emit_json:
        filters = {"kind": kind_filter}
        if query is not None:
            filters["query"] = query
        if limit is not None:
            filters["limit"] = limit
        payload = {
            "schema_version": 1,
            "filters": filters,
            "count": len(records),
            "commands": records,
        }
        print(json.dumps(payload, indent=2, sort_keys=True))
    else:
        print(format_command_records(records, query=query))
    return 0


def run_builtin(command_name: str, args: list[str]) -> int:
    if command_name == "help":
        return run_help(args)
    if command_name == "commands":
        return run_commands(args)
    print(f"Error: unsupported builtin command `{command_name}`.", file=sys.stderr)
    return 1


def find_binary(target_name: str) -> str | None:
    filename = target_name + EXE_SUFFIX
    build_roots = [
        path for path in sorted(glob.glob(os.path.join(ROOT_DIR, "build*")))
        if os.path.isdir(path)
    ]
    default_build = os.path.join(ROOT_DIR, "build")
    if default_build not in build_roots:
        build_roots.insert(0, default_build)
    # GNSSPP_BUILD_DIR points at an out-of-tree build and takes precedence.
    override_build = os.environ.get("GNSSPP_BUILD_DIR")
    if override_build:
        build_roots.insert(0, os.path.abspath(override_build))

    candidates = [
        os.path.join(APPS_DIR, filename),
    ]
    for build_root in build_roots:
        candidates.append(os.path.join(build_root, "apps", filename))
        for config in BUILD_CONFIGS:
            candidates.append(os.path.join(build_root, "apps", config, filename))
            candidates.append(os.path.join(build_root, config, "apps", filename))
            candidates.append(os.path.join(build_root, config, filename))

    for candidate in candidates:
        if os.path.isfile(candidate):
            return candidate

    recursive_hits: list[str] = []
    for build_root in build_roots:
        recursive_hits.extend(
            path for path in glob.glob(os.path.join(build_root, "**", filename), recursive=True)
            if os.path.isfile(path)
        )
    recursive_hits.sort()
    return recursive_hits[0] if recursive_hits else None


def run_python(target: str, command_name: str, args: list[str]) -> int:
    env = os.environ.copy()
    env["GNSS_CLI_NAME"] = f"gnss {command_name}"
    source_import_dirs = [*PYTHON_COMMAND_SOURCE_DIRS, PYTHON_COMMANDS_DIR]
    existing_pythonpath = env.get("PYTHONPATH")
    if existing_pythonpath:
        source_import_dirs.append(existing_pythonpath)
    env["PYTHONPATH"] = os.pathsep.join(source_import_dirs)
    if os.name == "nt":
        # os.exec* on Windows has spawn semantics (the parent console
        # regains control while the child still runs, and the reported
        # exit status is unreliable). Use a regular subprocess instead.
        import subprocess

        return subprocess.run(
            [sys.executable, target, *args], env=env, check=False
        ).returncode
    try:
        os.execvpe(sys.executable, [sys.executable, target, *args], env)
    except OSError as exc:
        print(f"Error: failed to exec {target}: {exc}", file=sys.stderr)
        return 1


def run_binary(target_name: str, args: list[str]) -> int:
    binary = find_binary(target_name)
    if binary is None:
        print(
            f"Error: built binary not found for {target_name}. "
            f"Run `cmake --build build --target {target_name}` first.",
            file=sys.stderr,
        )
        return 1
    if os.name == "nt":
        import subprocess

        return subprocess.run([binary, *args], check=False).returncode
    try:
        os.execv(binary, [binary, *args])
    except OSError as exc:
        print(f"Error: failed to exec {binary}: {exc}", file=sys.stderr)
        return 1


def dispatch_command(command_name: str, args: list[str]) -> int:
    command = COMMANDS.get(command_name)
    if command is None:
        print(unknown_command_message(command_name), file=sys.stderr)
        return 1

    if command["kind"] == "builtin":
        return run_builtin(command_name, args)
    if command["kind"] == "python":
        return run_python(command["target"], command_name, args)
    return run_binary(command["target"], args)


def main() -> int:
    if PYTHON_COMMAND_DISCOVERY_ERROR is not None:
        print(f"Error: {PYTHON_COMMAND_DISCOVERY_ERROR}", file=sys.stderr)
        return 1

    if len(sys.argv) < 2:
        print(usage())
        return 1

    if sys.argv[1] in ("-h", "--help"):
        print(usage())
        return 0

    return dispatch_command(sys.argv[1], sys.argv[2:])


if __name__ == "__main__":
    raise SystemExit(main())
