#!/usr/bin/env bash
# Run with bash. Requires Git 2.41+, jq and Alibaba's ocr v1.13.8 on PATH.
# Recreates the two-file billing example and checks both file-selection previews.
set -euo pipefail

temporary_parent=$(cd -- "${TMPDIR:-/tmp}" && pwd -P)
fixture=$(mktemp -d "$temporary_parent/wavect-ocr.XXXXXXXX")
trap 'rm -rf -- "$fixture"' EXIT
mkdir -p "$fixture/home" "$fixture/repo/billing"
# Keep personal review rules, Git hooks and provider credentials out of the run.
clean=(env -i "PATH=$PATH" "HOME=$fixture/home" GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null)
version=$("${clean[@]}" ocr version)
if [[ $version != 'open-code-review v1.13.8 '* ]]; then
  printf 'This fixture expects ocr v1.13.8. Installed version:\n%s\n' "$version" >&2
  exit 1
fi
command -v jq >/dev/null || { echo 'Install jq to validate the preview JSON.' >&2; exit 1; }
cd "$fixture/repo"
fixture_git() { "${clean[@]}" git -c user.name='Wavect fixture' -c user.email='fixture@example.invalid' "$@"; }
fixture_git init --quiet -b main

cat > billing/retry.go <<'GO'
package billing

func RetryKey(invoice string, attempt int) string {
	return invoice
}
GO
write_test() {
  cat > billing/retry_test.go <<GO
package billing

import "testing"

func TestRetryKey(t *testing.T) {
	if RetryKey("inv-42", 1) $1 RetryKey("inv-42", 2) {
		t.Fatal("$2")
	}
}
GO
}
write_test '!=' 'retries must reuse the invoice key'
fixture_git add billing
fixture_git commit --quiet -m 'Use the invoice ID across retries'
fixture_git switch --quiet -c retry-policy
cat > billing/retry.go <<'GO'
package billing

import "strconv"

func RetryKey(invoice string, attempt int) string {
	return invoice + "-" + strconv.Itoa(attempt)
}
GO
write_test '==' 'attempt keys must differ'
fixture_git add billing
fixture_git commit --quiet -m 'Generate a new key for each billing attempt'
fixture_git diff --name-only main...HEAD

check_preview() {
  local expected_test_selection=$1
  "${clean[@]}" ocr review --from main --to HEAD --preview --format json > "$fixture/preview.json"
  cat "$fixture/preview.json"
  jq -e --argjson include_test "$expected_test_selection" '
    (.files | map({key: .path, value: .}) | from_entries) as $files
    | .total_files == 2
      and .reviewable_count == (if $include_test then 2 else 1 end)
      and .excluded_count == (if $include_test then 0 else 1 end)
      and $files["billing/retry.go"].will_review == true
      and $files["billing/retry_test.go"].will_review == $include_test
      and ($include_test or $files["billing/retry_test.go"].exclude_reason == "default_path")
  ' "$fixture/preview.json" >/dev/null
}

printf '\nDefault rules\n'
check_preview false
mkdir .opencodereview
printf '%s\n' '{"include":["billing/retry_test.go"]}' > .opencodereview/rule.json
printf '\nSame diff with an explicit include for the test\n'
check_preview true
printf '\nBoth selection checks passed.\n'
