#!/usr/bin/env bash
set -uo pipefail

TESTS="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$TESTS/../../.." && pwd)"
REGISTRY="$HOME/.claude/buildbox-hosts.json"
# Records are write-once (runner links tmp -> target and never overwrites), so the
# fallback must be per-invocation: a shared /tmp dir makes every SECOND bare run —
# including the land gate after any local `pnpm run test` — fail EEXIST on records
# left by the first.
RECORDS_DIR="${CI_GATE_RESULTS_DIR:-$(mktemp -d "${TMPDIR:-/tmp}/overdeck-ci-results.XXXXXX")}/buildbox-records"
SUITE_RUNNER="$ROOT/tools/ci/buildbox-suite-runner.mjs"

classify() {
  case "$1" in
    deadman-lab-proof.sh) printf 'lab-only' ;;
    node-runtime.smoke.sh) printf 'remote' ;;
    *) printf 'local' ;;
  esac
}

suites=()
while IFS= read -r path; do
  [ "$(basename "$path")" = run-all.sh ] || suites+=("$path")
done < <(find "$TESTS" -maxdepth 1 -type f -name '*.sh' -print | sort)

if [ "${1:-}" = --list ]; then
  for path in "${suites[@]}"; do
    name=$(basename "$path")
    printf '%s\t%s\n' "$name" "$(classify "$name")"
  done
  exit 0
fi
if [ "$#" -ne 0 ]; then
  echo "usage: $0 [--list]" >&2
  exit 64
fi

pass=0
fail=0
not_run=0
failed=()
cd "$ROOT"

for path in "${suites[@]}"; do
  name=$(basename "$path")
  kind=$(classify "$name")
  case "$kind" in
    lab-only)
      printf 'NOT RUN %-30s dangerlab-only: reboots and intentionally breaks a disposable guest\n' "$name"
      not_run=$((not_run + 1))
      continue
      ;;
    remote)
      host="${BUILDBOX_TEST_HOST:-}"
      if [ -z "$host" ] && [ -r "$REGISTRY" ]; then
        host=$(jq -r '[.hosts[] | select(.state == "reachable" and (.roles | index("builder")))] | first | .name // empty' "$REGISTRY" 2>/dev/null)
      fi
      if [ -z "$host" ] || ! jq -e --arg host "$host" \
          '.hosts[] | select(.name == $host and .state == "reachable")' "$REGISTRY" >/dev/null 2>&1; then
        printf 'NOT RUN %-30s no registry host marked reachable\n' "$name"
        not_run=$((not_run + 1))
        continue
      fi
      out=$(bash "$path" "$host" 2>&1); rc=$?
      ;;
    *)
      node "$SUITE_RUNNER" workspace "$ROOT" "${path#$ROOT/}" "$RECORDS_DIR"; rc=$?
      out=""
      ;;
  esac
  if [ "$rc" -eq 0 ]; then
    printf 'PASS    %s\n' "$name"
    pass=$((pass + 1))
  else
    printf 'FAIL    %s (exit %s)\n%s\n' "$name" "$rc" "$out"
    fail=$((fail + 1))
    failed+=("$name")
  fi
done

printf '\nbuildbox suites: total=%d run=%d passed=%d failed=%d not_run=%d\n' \
  "${#suites[@]}" "$((pass + fail))" "$pass" "$fail" "$not_run"
if [ "$fail" -ne 0 ]; then
  printf 'failed: %s\n' "${failed[*]}"
  exit 1
fi
