#!/usr/bin/env bash
# Issue #40248: a commit with a typed message staged the whole worktree twice. First into a
# throwaway index (prepareCommitContext: copy the index, expand it, `add -A`, unmerged check,
# name-status) only to learn whether anything would be committed, then again into the real index.
# Claim: fixed on main by #40282 (69228fe179). A typed commit now skips the throwaway index when
# the index matches HEAD, stages the real index once, and maps "nothing staged" to
# skipped_no_changes.
# Shows: with the issue's setup (3 tracked files, a line appended to each, nothing pre-staged),
# a typed-message runStackedAction commit runs `add -A` twice and builds the throwaway index before
# #40282, and runs `add -A` once with no throwaway index on main. Both commits contain all 3 files.
# Needs deps installed (`vp i`). Run from the root of a clean t3code checkout.
set -euo pipefail

ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

if [ -n "$(git status --porcelain)" ]; then
  echo "refusing to run on a dirty tree"
  exit 2
fi
ORIG=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
TEST=apps/server/src/git/GitManager.test.ts
LOG=$(mktemp)
CMDS=$(mktemp)
cleanup() {
  git checkout -q -- "$TEST" 2>/dev/null || true
  rm -f "$LOG" "$CMDS"
  git checkout -q -f "$ORIG"
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
FIX=69228fe179815a9446531eb9cf73d8deaa26db4c
BEFORE=$(git rev-parse "$FIX^")
echo "main=$MAIN fix=$FIX before=$BEFORE"

subject=$(git log -1 --format=%s "$FIX")
if git merge-base --is-ancestor "$FIX" "$MAIN" &&
  [ "$subject" = "fix(server): typed-message commits stage the worktree once (#40282)" ]; then
  pass "#40282 ($(git rev-parse --short "$FIX")) is on main: $subject"
else
  fail "#40282 is not on main, or $FIX is a different commit ($subject)"
fi

# Same harness as the fix's own "stages the worktree once for a typed commit message", using only
# helpers both commits have. gitCommands records every git process the manager starts.
append_test() {
  cat >> "$TEST" <<'EOF'

it.layer(layerGitManagerTest)("prove-issue-40248", (it) => {
  it.effect("prove-issue-40248", () =>
    Effect.gen(function* () {
      const repoDir = yield* makeTempDir("t3code-prove-40248-");
      yield* initRepo(repoDir);
      const files = ["AGENTS.md", "README.md", "package.json"];
      NodeFS.writeFileSync(NodePath.join(repoDir, "AGENTS.md"), "# agents\n");
      NodeFS.writeFileSync(NodePath.join(repoDir, "package.json"), "{}\n");
      yield* runGit(repoDir, ["add", "AGENTS.md", "package.json"]);
      yield* runGit(repoDir, ["commit", "-m", "Track files"]);
      // The issue's setup: a line appended to 3 tracked files, nothing staged.
      for (const file of files) {
        NodeFS.appendFileSync(NodePath.join(repoDir, file), "\ncommit 0\n");
      }
      const gitCommands: string[] = [];
      const { manager } = yield* makeManager({ gitCommands });

      const result = yield* runStackedAction(manager, {
        cwd: repoDir,
        action: "commit",
        commitMessage: "perf commit 0",
      });
      const during = [...gitCommands];
      if (process.env.PROOF_OUT) NodeFS.writeFileSync(process.env.PROOF_OUT, `${during.join("\n")}\n`);

      expect(result.commit).toMatchObject({ status: "created", subject: "perf commit 0" });
      const committed = (yield* runGit(repoDir, ["show", "--pretty=", "--name-only", "HEAD"]))
        .stdout.trim()
        .split("\n");
      expect(committed.toSorted()).toEqual(files);
      expect((yield* runGit(repoDir, ["status", "--porcelain"])).stdout.trim()).toBe("");

      const addAll = during.filter((args) => args.endsWith("add -A")).length;
      const scratchIndex = during.filter((args) =>
        args.endsWith("update-index --no-split-index"),
      ).length;
      if (process.env.PROOF_EXPECT === "bug") {
        expect(addAll).toBe(2);
        expect(scratchIndex).toBe(1);
      } else {
        expect(addAll).toBe(1);
        expect(scratchIndex).toBe(0);
      }
    }),
  );
});
EOF
}

run_at() {
  local sha=$1 expect=$2
  git checkout -q --detach "$sha"
  append_test
  local rc=0
  : > "$CMDS"
  PROOF_EXPECT="$expect" PROOF_OUT="$CMDS" vp test run "$TEST" -t prove-issue-40248 > "$LOG" 2>&1 || rc=$?
  git checkout -q -- "$TEST"
  if [ "$rc" -eq 0 ] && ! grep -Eq 'Tests +1 passed' "$LOG"; then rc=3; fi
  if [ "$rc" -ne 0 ]; then sed 's#'"$HOME"'#~#g' "$LOG" | tail -25; fi
  return "$rc"
}

show_commands() {
  echo "      git processes the manager started during the commit: $(wc -l < "$CMDS" | tr -d ' ')"
  sed -E -e 's#(/private)?/var/folders/[^ ]+/T/#$TMPDIR/#g' -e 's#'"$HOME"'#~#g' -e 's/^/        git /' "$CMDS"
}

if run_at "$BEFORE" bug; then
  pass "before #40282 ($(git rev-parse --short "$BEFORE")): the typed commit is created with all 3 files, after 2 \`add -A\` runs and 1 throwaway-index expansion (\`update-index --no-split-index\`)"
  show_commands
else
  fail "before #40282: the typed commit did not stage twice"
fi
if run_at "$MAIN" fixed; then
  pass "main ($(git rev-parse --short "$MAIN")): the same typed commit is created with all 3 files, after 1 \`add -A\` run and no throwaway index"
  show_commands
else
  fail "main: the typed commit did not stage once"
fi

if [ "$ok" = 1 ]; then
  echo "VERDICT: #40248 is fixed on main by #40282"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: not shown"
exit 1
