#!/usr/bin/env bash
# Issue #33197: switching threads while dictating clears the recording and everything said.
# Claim: already fixed by #35761 (c24255826b). A thread draft is now a persistent voice target, so an
# owner change no longer cancels its recording, and the transcript lands in that thread's draft.
# Shows: the issue's three steps through useEnvironmentSpeechInput with the composer's thread-draft
# wiring. Before #35761, returning to thread A finds the dictation idle, nothing transcribed and A's
# draft unchanged. On main the recording is still running, and stopping it adds the transcript to A's
# draft while B's stays empty. 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/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx
LOG=$(mktemp)
cleanup() {
  git checkout -q -f -- "$TEST" 2>/dev/null || true
  rm -f "$LOG"
  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=c24255826be5aabb0f32ee18f6ac7dec0b3f1347
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" = "feat(web): dictation keeps recording into its thread when you switch away (#35761)" ]; then
  pass "#35761 ($(git rev-parse --short "$FIX")) is on main: $subject"
else
  fail "#35761 is not on main, or $FIX is a different commit ($subject)"
fi

# Appended to the hook's own browser test file so it reuses its mocked platform, transcriber and
# chosen environment. Two named cases share one scenario; each run selects exactly one of them.
append_test() {
  cat >> "$TEST" <<'EOF'

// prove-issue-33197: ChatComposer keeps one editor mounted and changes its owner when another thread
// opens. Each thread's draft lives in the draft store, which the composer passes as persistentDraft
// on main (the hook ignores the prop before #35761).
const proveIssue33197Drafts = new Map<string, string>();

function ProveIssue33197Composer(props: { readonly thread: string }) {
  const draft = () => proveIssue33197Drafts.get(props.thread) ?? "";
  const value = useEnvironmentSpeechInput({
    environmentId: THREAD_ENV as EnvironmentId,
    ownerKey: props.thread,
    label: props.thread,
    readDraft: () => ({ text: draft(), selection: { start: draft().length, end: draft().length } }),
    commitDraft: (text) => {
      proveIssue33197Drafts.set(props.thread, text);
    },
    persistentDraft: {
      readStoredText: draft,
      commitStoredText: (text: string) => {
        proveIssue33197Drafts.set(props.thread, text);
      },
      open: () => {},
    },
  });
  useLayoutEffect(() => {
    mocks.voice = value;
  });
  return null;
}

async function proveIssue33197Steps() {
  setup({ destination: "env-a" });
  proveIssue33197Drafts.clear();
  proveIssue33197Drafts.set("thread-a", "Earlier text");
  await using screen = await render(<ProveIssue33197Composer thread="thread-a" />);
  // 1. Start voice input in thread A's composer.
  await act(() => mocks.voice.start());
  expect(mocks.voice.state.phase).toBe("recording");
  // 2. While it's still recording, open thread B.
  await screen.rerender(<ProveIssue33197Composer thread="thread-b" />);
  // 3. Go back to thread A, and stop the dictation if it is still running.
  await screen.rerender(<ProveIssue33197Composer thread="thread-a" />);
  const phaseOnReturn = mocks.voice.state.phase;
  if (phaseOnReturn === "recording") await act(() => mocks.voice.stop());
  const result = {
    phaseOnReturn,
    transcribeCalls: [...mocks.transcribeCalls],
    draftA: proveIssue33197Drafts.get("thread-a"),
    draftB: proveIssue33197Drafts.get("thread-b") ?? "",
  };
  console.log(
    `prove-issue-33197: back in thread A the dictation is ${result.phaseOnReturn}; ` +
      `transcribed ${result.transcribeCalls.length}x; thread A's draft is "${result.draftA}"; ` +
      `thread B's draft is "${result.draftB}"`,
  );
  return result;
}

it("prove-issue-33197 bug: switching threads mid-dictation loses it", async () => {
  const result = await proveIssue33197Steps();
  expect(result.phaseOnReturn).toBe("idle");
  expect(result.transcribeCalls).toEqual([]);
  expect(result.draftA).toBe("Earlier text");
  expect(result.draftB).toBe("");
});

it("prove-issue-33197 fixed: switching threads mid-dictation keeps it for thread A", async () => {
  const result = await proveIssue33197Steps();
  expect(result.phaseOnReturn).toBe("recording");
  expect(result.transcribeCalls).toEqual(["env-a"]);
  expect(result.draftA).toBe("Earlier text dictated");
  expect(result.draftB).toBe("");
});
EOF
}

SEEN=""
run_at() {
  git checkout -q --detach "$1"
  append_test
  local rc=0
  vp test run "$TEST" -t "prove-issue-33197 $2" --silent=false > "$LOG" 2>&1 || rc=$?
  git checkout -q -f -- "$TEST"
  SEEN=$(grep -o 'prove-issue-33197: .*' "$LOG" | sed 's/^prove-issue-33197: //' | head -1)
  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 -30; fi
  return "$rc"
}

if run_at "$BEFORE" bug; then
  pass "before #35761 ($(git rev-parse --short "$BEFORE")): $SEEN"
else
  fail "before #35761: switching threads did not lose the dictation"
fi
if run_at "$MAIN" fixed; then
  pass "main ($(git rev-parse --short "$MAIN")): $SEEN"
else
  fail "main: switching threads did not keep the dictation for thread A"
fi

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