#!/usr/bin/env bash
# Runs the real precheck/install entry point with isolated HOME and fake tools;
# never contacts GitHub or builds Rust. Run with bash on Linux or Git Bash.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
UNDER_TEST="${1:-$HERE/traceable-reqs.sh}"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/tools"
cat >"$work/tools/git" <<'SH'
#!/usr/bin/env bash
printf 'git\n' >>"$CALLS"
exit 128
SH
cat >"$work/tools/cargo" <<'SH'
#!/usr/bin/env bash
printf 'cargo\n' >>"$CALLS"
exit 99
SH
chmod +x "$work/tools/"*

# [unit->REQ-CI-CHECKER-PIN-PRECHECK]
run_case() {
  local label="$1" reported="$2" version_rc="$3" token="$4" mode="$5" want_rc="$6"
  local root="$work/$label" out rc=0
  mkdir -p "$root/home/.local/bin" "$root/checkout" "$root/tmp"
  if [ "$reported" != missing ]; then
    printf '#!/usr/bin/env bash\nprintf "%%s\\n" "%s"\nexit %s\n' \
      "$reported" "$version_rc" >"$root/home/.local/bin/traceable-reqs"
    chmod +x "$root/home/.local/bin/traceable-reqs"
  fi
  out="$(cd "$root/checkout" && HOME="$root/home" RUNNER_TEMP="$root/tmp" \
    PATH="$work/tools:$PATH" CALLS="$root/calls" GH_TOKEN="$token" \
    bash "$UNDER_TEST" "$mode" 2>&1)" || rc=$?
  if [ "$rc" != "$want_rc" ]; then
    printf 'FAIL %s: exit=%s expected=%s\n%s\n' "$label" "$rc" "$want_rc" "$out"
    exit 1
  fi
  # The incident must name BOTH the pin and the observed box version before
  # authentication/build, not just report an unrelated downstream exit 128.
  case "$out" in *"pin=0.4.1"*) ;; *) printf 'FAIL missing pin: %s\n' "$out"; exit 1;; esac
  case "$out" in *"box="*) ;; *) printf 'FAIL missing box: %s\n' "$out"; exit 1;; esac
  if [ "$label" = stale-no-token ]; then
    case "$out" in *"0.2.0"*"TRACEABLE_REQS_TOKEN"*) ;; *) printf 'FAIL mismatch/auth diagnostic: %s\n' "$out"; exit 1;; esac
  fi
  if [ "$label" = clone-refusal ]; then
    [ "$(cat "$root/calls")" = git ]
  else
    [ ! -e "$root/calls" ] # no clone/build, including matching installs
  fi
  if [ "$mode" = install ] && [ "$rc" = 0 ]; then
    [ "$("$root/checkout/traceable-reqs" --version)" = 'traceable-reqs 0.4.1' ]
  else
    [ ! -e "$root/checkout/traceable-reqs" ]
  fi
  case "$out" in *TOKEN_CANARY*) echo 'FAIL credential disclosed'; exit 1;; esac
  printf 'PASS %s exit=%s\n' "$label" "$rc"
}

run_case stale-no-token 'traceable-reqs 0.2.0' 0 '' precheck 1
run_case matching-no-token 'traceable-reqs 0.4.1' 0 '' precheck 0
run_case matching-install 'traceable-reqs 0.4.1' 0 '' install 0
run_case missing-no-token missing 0 '' install 1
run_case failed-version 'traceable-reqs 0.4.1' 7 '' precheck 1
run_case regex-lookalike 'traceable-reqs 0x4x1' 0 '' precheck 1
run_case repair-admitted 'traceable-reqs 0.2.0' 0 TOKEN_CANARY precheck 0
run_case clone-refusal 'traceable-reqs 0.2.0' 0 TOKEN_CANARY install 128
