#!/usr/bin/env bash
set -euo pipefail
command -v git >/dev/null
command -v node >/dev/null
DEMO_ROOT=$(mktemp -d "${TMPDIR:-/tmp}/saignals-bisect.XXXXXX")
mkdir "$DEMO_ROOT/repo"
cd "$DEMO_ROOT/repo"
git init -q -b chore/bisect-demo
git config user.name 'sAIgnals demo'
git config user.email 'demo@example.invalid'
git config commit.gpgsign false
mkdir src
cat > src/shipping.mjs <<'JS'
export function shippingCents(subtotalCents) {
  return subtotalCents >= 5000 ? 0 : 500;
}
JS
git add src/shipping.mjs
git commit -qm 'feat: add shipping calculation'
git tag demo-good
for step in 1 2 3 4 5 6 7; do
  printf 'Demo revision %s\n' "$step" > notes.txt
  if [ "$step" = 4 ]; then
    cat > src/shipping.mjs <<'JS'
export function shippingCents(subtotalCents) {
  return subtotalCents > 5000 ? 0 : 500;
}
JS
  fi
  git add notes.txt src/shipping.mjs
  git commit -qm "chore: demo revision $step"
  if [ "$step" = 4 ]; then git tag demo-introduced; fi
done
git tag demo-bad
cat > "$DEMO_ROOT/check-shipping.mjs" <<'JS'
import { existsSync } from 'node:fs';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
const source = resolve('src/shipping.mjs');
if (!existsSync(source)) process.exit(125);
try {
  const { shippingCents } = await import(pathToFileURL(source).href);
  const actual = shippingCents(5000);
  console.log(`shippingCents(5000) = ${actual}`);
  process.exit(actual === 0 ? 0 : 1);
} catch (error) {
  console.error(error);
  process.exit(128);
}
JS
git worktree add --quiet --detach "$DEMO_ROOT/investigation" demo-bad
cd "$DEMO_ROOT/investigation"
git checkout -q demo-good
node "$DEMO_ROOT/check-shipping.mjs"
git checkout -q demo-bad
if node "$DEMO_ROOT/check-shipping.mjs"; then
  echo 'Expected the bad endpoint to fail' >&2
  exit 1
else
  status=$?
  test "$status" -eq 1
fi
git bisect start demo-bad demo-good --
git bisect run node "$DEMO_ROOT/check-shipping.mjs"
found=$(git rev-parse refs/bisect/bad)
expected=$(git rev-parse demo-introduced)
test "$found" = "$expected"
git bisect log > "$DEMO_ROOT/bisect.log"
git show --format=short "$found" -- src/shipping.mjs
git bisect reset
printf 'Verified expected first bad commit: %s\nArtifacts retained in: %s\n' "$found" "$DEMO_ROOT"
