#!/usr/bin/env bash

set -euo pipefail

repo_root="$(cd "$(dirname "$0")/.." && pwd)"
test_root="$(mktemp -d "${TMPDIR:-/tmp}/nucleic-cache-guard.XXXXXX")"
trap 'rm -rf "$test_root"' EXIT

mkdir -p "$test_root/bin" "$test_root/project" "$test_root/scratch/out"
cat > "$test_root/bin/swift" <<'SCRIPT'
#!/usr/bin/env bash
printf 'Swift version %s\n' "${FAKE_SWIFT_VERSION:?}"
SCRIPT
cat > "$test_root/bin/swiftc" <<'SCRIPT'
#!/usr/bin/env bash
exit 0
SCRIPT
cat > "$test_root/bin/xcodebuild" <<'SCRIPT'
#!/usr/bin/env bash
printf 'Xcode %s\n' "${FAKE_XCODE_VERSION:?}"
SCRIPT
cat > "$test_root/bin/xcrun" <<'SCRIPT'
#!/usr/bin/env bash
case "$*" in
  *--show-sdk-path*) printf '/SDKs/MacOSX%s.sdk\n' "${FAKE_SDK_VERSION:?}" ;;
  *--find\ clang*) printf '/toolchains/%s/clang\n' "${FAKE_XCODE_VERSION:?}" ;;
  *) exit 1 ;;
esac
SCRIPT
chmod +x "$test_root/bin/"*

export PATH="$test_root/bin:$PATH"
export NUCLEIC_SCRATCH_PATH="$test_root/scratch"
export FAKE_SWIFT_VERSION=6.4-a
export FAKE_XCODE_VERSION=27A
export FAKE_SDK_VERSION=27.0

printf '// package graph a\n' > "$test_root/project/Package.swift"
touch "$test_root/scratch/out/preserved"
bash "$repo_root/scripts/lib/guard-swift-cache.sh" "$test_root/project"
test -f "$test_root/scratch/out/preserved" # first run adopts existing products

bash "$repo_root/scripts/lib/guard-swift-cache.sh" "$test_root/project"
test -f "$test_root/scratch/out/preserved" # unchanged identity preserves products

export FAKE_SWIFT_VERSION=6.4-b
bash "$repo_root/scripts/lib/guard-swift-cache.sh" "$test_root/project"
test ! -d "$test_root/scratch/out"          # changed identity drops products only
test -f "$test_root/scratch/.nucleic-swift-toolchain"

mkdir -p "$test_root/scratch/out"
touch "$test_root/scratch/out/xcode-change"
export FAKE_XCODE_VERSION=27B
bash "$repo_root/scripts/lib/guard-swift-cache.sh" "$test_root/project"
test ! -d "$test_root/scratch/out"

mkdir -p "$test_root/scratch/out"
touch "$test_root/scratch/out/package-change"
printf '// package graph b\n' > "$test_root/project/Package.swift"
bash "$repo_root/scripts/lib/guard-swift-cache.sh" "$test_root/project"
test ! -d "$test_root/scratch/out"

mkdir -p "$test_root/scratch/out"
touch "$test_root/scratch/out/forced-reset"
bash "$repo_root/scripts/lib/guard-swift-cache.sh" "$test_root/project" --reset-products
test ! -d "$test_root/scratch/out"

echo "swift cache guard tests passed"
