#!/usr/bin/env bash
set -euo pipefail
repo="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$repo"
command="${1:-help}"
if [[ "$command" == inspect ]]; then command=inspect_bench; fi
if [[ $# -gt 0 ]]; then shift; fi
if [[ "$command" == install ]]; then exec bash "$repo/scripts/install.sh" "$@"; fi
python_path="${ARENA_PYTHON:-$repo/vendor/IsaacLab/.venv/bin/python}"
case "$command" in
  doctor) exec python3 "$repo/scripts/doctor.py" "$@" ;;
  run|play|eval|teleop|replay|train_ppo|train_bc|qualify|qualify_rendering|qualify_variation|qualify_tasks|qualify_convergence|inspect_bench|scripted_diagnostic|probe_reset_render|contact_study|benchmark_runtime)
    if [[ ! -x "$python_path" ]]; then
      echo 'Runtime missing. On the RTX host: ./arena install --accept-eula' >&2
      exit 1
    fi
    export OMNI_KIT_ACCEPT_EULA=YES
    exec "$python_path" "$repo/scripts/$command.py" "$@" ;;
  freeze_benchmark|prepare_runtime_image|qualify_offline_image|make_suite|validate_calibration|release_check|qualify_container|check_policy|package_policy|summarize_ports|summarize_runtime|compare_diagnostics|merge_task_qualifications|merge_convergence_qualifications|asset_bundle|archive_results)
    cpu_python="${ARENA_TEST_PYTHON:-$python_path}"
    if [[ ! -x "$cpu_python" ]]; then cpu_python="$repo/.venv/bin/python"; fi
    exec "$cpu_python" "$repo/scripts/$command.py" "$@" ;;
  test)
    test_python="${ARENA_TEST_PYTHON:-$repo/.venv/bin/python}"
    exec "$test_python" -m pytest "$repo/tests" -m 'not gpu' "$@" ;;
  assets) exec "$python_path" -m cabling.usd_assets "$@" ;;
  help|-h|--help)
    echo 'Usage: ./arena <command> [options]'
    echo 'Build: doctor install assets asset_bundle prepare_runtime_image'
    echo 'Develop: run play teleop replay train_ppo train_bc inspect test'
    echo 'Submit: check_policy package_policy eval'
    echo 'Qualify: qualify qualify_rendering qualify_variation qualify_tasks qualify_convergence qualify_container qualify_offline_image'
    echo 'Organize: make_suite summarize_ports compare_diagnostics merge_task_qualifications merge_convergence_qualifications validate_calibration release_check freeze_benchmark'
    echo 'Preserve: archive_results pack|verify'
    echo 'Diagnostics: scripted_diagnostic contact_study benchmark_runtime summarize_runtime'
    ;;
  *) echo "Unknown command: $command. Run ./arena --help for available commands." >&2; exit 2 ;;
esac
