#!/usr/bin/env bash
# PR #34202 (fix(server): a revoked T3 Connect link can be relinked to another account), for issue #34193.
# Claim: already-fixed. #34194 (b39eb755aa) fixed the same bug: an explicit app link (applyRelayConfig) drops a
# revoked link before the account check. Shows: #34194 closed #34193; the PR's own regression test, copied verbatim
# from the PR head into the test file, passes at b39eb755aa and on current main, and its different-account row fails
# at b39eb755aa's parent. Also shows the PR's remaining source delta (skipping the check on every path) breaks
# #34194's guard that the unattended startup reconcile keeps rejecting a revoked link to another account.
# Needs deps installed (`vp i`), node, git, and `gh` authenticated. Run from a clean t3code checkout root.
set -euo pipefail

REPO=pingdotgg/t3code
FIX=b39eb755aaf8c86fa1ce56d2447d197eabc6d9d7
TEST=apps/server/src/cloud/CloudLink.lifecycle.test.ts
SRC=apps/server/src/cloud/CloudLink.ts
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)
WORK=$(mktemp -d)
cleanup() {
  git checkout -q -f -- . 2>/dev/null || true
  git checkout -q -f "$ORIG"
  rm -rf "$WORK"
}
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)
git fetch -q origin pull/34202/head
PR_HEAD=$(git rev-parse FETCH_HEAD)
git cat-file -e "$FIX^{commit}"
PARENT=$(git rev-parse "$FIX^")
PR_BASE=$(git merge-base "$PR_HEAD" "$MAIN")
echo "main=$MAIN pr_head=$PR_HEAD fix=$FIX fix_parent=$PARENT"

# 1. The issue and the superseding PR.
issue=$(gh api "repos/$REPO/issues/34193" --jq '"\(.state) \(.state_reason)"')
closer=$(gh api graphql -f query='{repository(owner:"pingdotgg",name:"t3code"){issue(number:34193){timelineItems(itemTypes:CLOSED_EVENT,last:1){nodes{...on ClosedEvent{closer{...on PullRequest{number merged}}}}}}}}' \
  --jq '.data.repository.issue.timelineItems.nodes[0].closer | "\(.number) \(.merged)"')
if [ "$issue" = "closed completed" ] && [ "$closer" = "34194 true" ]; then
  pass "issue #34193 (the bug this PR fixes) is closed as completed by merged PR #34194"
else
  fail "issue #34193 state='$issue' closer='$closer'"
fi
subject=$(git log -1 --format=%s "$FIX")
if git merge-base --is-ancestor "$FIX" "$MAIN" && ! git merge-base --is-ancestor "$FIX" "$PR_HEAD" \
  && grep -qF "(#34194)" <<< "$subject"; then
  pass "#34194 is on main as ${FIX:0:10} ($subject); the PR branch predates it"
else
  fail "$FIX is not #34194 on main, or the PR branch already contains it"
fi

# 2. Behavioral: the PR's own test ("clears the revoked mark when the environment is linked again to
#    {the same, a different} account"), cut verbatim from the PR head and inserted into the target commit's file.
git show "$PR_HEAD:$TEST" > "$WORK/pr-test.ts"
insert_pr_test() {
  node -e '
    const fs = require("fs");
    const [prFile, target] = process.argv.slice(1);
    const anchor = "  it.effect(\n    \"starts a connector with a marker for the current origin without contacting relay\",";
    const start = "  it.effect.each([\n    { account: \"the same\", cloudUserId: \"user-123\" },";
    const pr = fs.readFileSync(prFile, "utf8");
    const s = pr.indexOf(start), e = pr.indexOf(anchor);
    if (s < 0 || e < s) { console.error("PR test block not found"); process.exit(3); }
    const t = fs.readFileSync(target, "utf8");
    const at = t.indexOf(anchor);
    if (at < 0) { console.error("anchor not found in target"); process.exit(4); }
    fs.writeFileSync(target, t.slice(0, at) + pr.slice(s, e) + t.slice(at));
  ' "$WORK/pr-test.ts" "$TEST"
}
run_tests() {
  (cd apps/server && vp test run src/cloud/CloudLink.lifecycle.test.ts -t "$1") > "$2" 2>&1 || true
  sed 's/\x1b\[[0-9;]*m//g' "$2" | grep -E "^ +[✓×] |Tests +[0-9]|CloudLinkAccountMismatchError|getOrThrow called" | sort -u | head -12 || tail -20 "$2"
}
PR_ROWS="linked again to (the same|a different) account"

git checkout -q --detach "$FIX"
insert_pr_test
run_tests "$PR_ROWS" "$WORK/fix.log"
if grep -qE "Tests +2 passed" "$WORK/fix.log" && ! grep -qE "Tests +.*failed" "$WORK/fix.log"; then
  pass "at ${FIX:0:10}, the PR's test passes: a revoked link relinked through applyRelayConfig to the same or a different account ends linked and no longer revoked"
else
  fail "the PR's test did not pass at $FIX"
fi
git checkout -q -f -- .

git checkout -q --detach "$MAIN"
insert_pr_test
run_tests "$PR_ROWS" "$WORK/main.log"
if grep -qE "Tests +2 passed" "$WORK/main.log" && ! grep -qE "Tests +.*failed" "$WORK/main.log"; then
  pass "on main ${MAIN:0:10}, the PR's test passes"
else
  fail "the PR's test did not pass on main $MAIN"
fi
git checkout -q -f -- .

git checkout -q --detach "$PARENT"
insert_pr_test
run_tests "$PR_ROWS" "$WORK/parent.log"
if grep -qE "Tests +1 failed \| 1 passed" "$WORK/parent.log" \
  && grep -qE "× .*linked again to a different account" "$WORK/parent.log" \
  && grep -qF "CloudLinkAccountMismatchError" "$WORK/parent.log"; then
  pass "at the fix's parent ${PARENT:0:10}, the PR's different-account row fails with CloudLinkAccountMismatchError (the reported bug)"
else
  fail "the PR's test did not fail as expected at the fix's parent $PARENT"
fi
git checkout -q -f -- .

# 3. The PR's only remaining delta: its CloudLink.ts change also lets the unattended startup reconcile switch a
#    revoked link to another account. #34194 rejects that on purpose (a clock-skew 401 can mark a live link
#    revoked) and tests it; with the PR's source change applied at the fix, that test fails.
# vitest truncates interpolated row names at 40 characters, so match the prefix.
GUARD="keeps a revoked link when startup"
git checkout -q --detach "$FIX"
run_tests "$GUARD" "$WORK/guard.log"
guard_ok=0
if grep -qE "Tests +1 passed" "$WORK/guard.log" && ! grep -qE "Tests +.*failed" "$WORK/guard.log"; then guard_ok=1; fi
git diff "$PR_BASE" "$PR_HEAD" -- "$SRC" > "$WORK/pr-src.patch"
git apply "$WORK/pr-src.patch"
run_tests "$GUARD" "$WORK/guard-pr.log"
# With the PR's change the startup relink succeeds, so the test's expected mismatch error is missing.
if [ "$guard_ok" = 1 ] && grep -qE "Tests +1 failed" "$WORK/guard-pr.log" \
  && grep -qF "getOrThrow called on a None" "$WORK/guard-pr.log"; then
  pass "at ${FIX:0:10}, #34194's test 'keeps a revoked link when startup links another account' passes, and fails once the PR's CloudLink.ts change is applied on top"
else
  fail "could not show the PR's source delta conflicts with #34194's startup guard"
fi
git checkout -q -f -- .

if [ "$ok" = 1 ]; then
  echo "VERDICT: already-fixed by #34194 (${FIX:0:10}); PR #34202 can be closed"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: not proven; keep PR #34202 open"
exit 1
