#!/usr/bin/env bash
# Behavioral test for the Final-Step-B allowlist helper. It stubs no networked
# tools and calls only the harness helper entrypoint.
set -uo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
ORCH="$HERE/../harness_orchestrator.sh"
PASS=0
FAIL=0

ok() {
  echo "  OK: $1"
  PASS=$((PASS + 1))
}

no() {
  echo "  FAIL: $1"
  FAIL=$((FAIL + 1))
}

expect_allowlist() {
  local name="$1"
  local expected="$2"
  local spec="$3"
  shift 3

  bash "$ORCH" __autoland_allowlist_check "$spec" "$@" >/dev/null 2>&1
  local rc=$?
  if [ "$expected" = "true" ] && [ "$rc" -eq 0 ]; then
    ok "$name"
  elif [ "$expected" = "false" ] && [ "$rc" -ne 0 ]; then
    ok "$name"
  else
    no "$name (exit $rc)"
  fi
}

test -f "$ORCH" || { echo "FATAL: harness not found at $ORCH"; exit 1; }

SBX="$(mktemp -d)"
trap 'rm -rf "$SBX"' EXIT

NO_ALLOWED="$SBX/no-allowed.md"
MATCHES="$SBX/matches.md"
OUTSIDE="$SBX/outside.md"
DUPLICATE="$SBX/duplicate.md"

cat > "$NO_ALLOWED" <<'SPEC'
# BUILD_SPEC

# ALLOWED='^commented/out$'
SPEC

cat > "$MATCHES" <<'SPEC'
# BUILD_SPEC

ALLOWED='^(recoil/pipeline/tools/harness_orchestrator\.sh|recoil/pipeline/tools/tests/test_autoland_allowlist\.sh)$'
SPEC

cat > "$OUTSIDE" <<'SPEC'
# BUILD_SPEC

ALLOWED='^(recoil/pipeline/tools/harness_orchestrator\.sh)$'
SPEC

cat > "$DUPLICATE" <<'SPEC'
# BUILD_SPEC

ALLOWED='^old/value$'
  ALLOWED='^(recoil/pipeline/tools/harness_orchestrator\.sh)$'
SPEC

expect_allowlist "no ALLOWED line is not eligible" false "$NO_ALLOWED" \
  "recoil/pipeline/tools/harness_orchestrator.sh"

expect_allowlist "all changed paths within allowlist are eligible" true "$MATCHES" \
  "recoil/pipeline/tools/harness_orchestrator.sh" \
  "recoil/pipeline/tools/tests/test_autoland_allowlist.sh"

expect_allowlist "one path outside allowlist is not eligible" false "$OUTSIDE" \
  "recoil/pipeline/tools/harness_orchestrator.sh" \
  "README.md"

expect_allowlist "multiple ALLOWED lines fail closed" false "$DUPLICATE" \
  "recoil/pipeline/tools/harness_orchestrator.sh"

if [ "$FAIL" -gt 0 ]; then
  echo "FAIL: $FAIL failed, $PASS passed"
  exit 1
fi

echo "PASS: $PASS passed"
