#!/bin/bash

set -euo pipefail

run_step() {
  local name="$1"
  shift
  printf '\n==> %s\n' "$name"
  "$@"
}

if command -v soldr >/dev/null 2>&1; then
  CARGO=(soldr cargo)
else
  echo "warning: soldr not on PATH; falling back to bare cargo (no caching). Install soldr to get the caching path." >&2
  CARGO=(cargo)
  # soldr#2493: the test steps below need cargo-nextest, which soldr fetches
  # automatically but a bare cargo does not. Say so plainly rather than
  # letting cargo report `no such subcommand: nextest`.
  if ! cargo nextest --version >/dev/null 2>&1; then
    echo "error: cargo-nextest is required to run the test suite (it owns per-test timeouts since soldr#2493)." >&2
    echo "       Install soldr, or run: cargo install cargo-nextest --locked" >&2
    exit 1
  fi
fi

run_step "Build workspace" "${CARGO[@]}" build --workspace
# soldr#2493: nextest, not `cargo test`. Per-test timeouts now come from
# `.config/nextest.toml` (`slow-timeout` / `terminate-after`) instead of the
# removed `timed_test!` watchdog, so a `cargo test` run here would be
# unbounded -- a hung test would sit until the caller gives up.
run_step "Run library tests" "${CARGO[@]}" nextest run --workspace --lib
run_step "Run CLI smoke tests" "${CARGO[@]}" nextest run -p soldr-cli --tests
run_step "Run fetch integration test" "${CARGO[@]}" nextest run -p soldr-cli --test fetch_crgx
run_step "Run install-zccache integration test" "${CARGO[@]}" nextest run -p soldr-cli --test lib_install_zccache
run_step "Install Python dev tools" ./install
run_step "Run Python wrapper tests" uv run --no-sync pytest -n auto tests -v --durations=0

printf '\nPipeline complete.\n'
