#!/usr/bin/env bash
# PR #24795 (fix(web): find ignored files past the copy picker cutoff), for issue #24504.
# Claim: already-fixed. #36228 (f62fa296f0) landed the same change: projects.listIgnoredFiles takes a
# case-insensitive `query` applied before the 200-file cap, an `ignoredFileSearch` capability, and the same
# search field, cross-search selection and 200-file selection cap in AddProjectToMachineDialog.
# Shows: the PR's own regression test passes on current main and fails at #36228's parent; the PR's
# server/contract code equals #36228's; its dialog differs only in debounce and label copy.
# Needs deps installed (`vp i`), git, and `gh` authenticated. Run from the root of a clean t3code checkout.
set -euo pipefail

REPO=pingdotgg/t3code
FIX=f62fa296f065b6399fb68edf1863e6f4c831641b
TEST=apps/server/src/workspace/WorkspaceEntries.test.ts
DIALOG=apps/web/src/components/AddProjectToMachineDialog.tsx
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/24795/head
PR_HEAD=$(git rev-parse FETCH_HEAD)
git cat-file -e "$FIX^{commit}"
PARENT=$(git rev-parse "$FIX^")
MB=$(git merge-base "$MAIN" "$PR_HEAD")
echo "main=$MAIN pr_head=$PR_HEAD fix=$FIX fix_parent=$PARENT pr_merge_base=$MB"

# 1. The issue and the superseding PR.
issue=$(gh api "repos/$REPO/issues/24504" --jq '"\(.state) \(.state_reason)"')
closer=$(gh api graphql -f query='{repository(owner:"pingdotgg",name:"t3code"){issue(number:24504){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" = "36228 true" ]; then
  pass "issue #24504 (the bug this PR fixes) is closed as completed by merged PR #36228"
else
  fail "issue #24504 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 "(#36228)" <<< "$subject"; then
  pass "#36228 is on main as ${FIX:0:10} ($subject); the PR branch predates it"
else
  fail "$FIX is not #36228 on main, or the PR branch already contains it"
fi

# 2. The PR touches only the seven files #36228 touches.
pr_files=$(git diff --name-only "$MB" "$PR_HEAD" | sort)
fix_files=$(git diff --name-only "$PARENT" "$FIX" | sort)
if [ "$pr_files" = "$fix_files" ]; then
  pass "the PR and #36228 change the same $(wc -l <<< "$pr_files" | tr -d ' ') files"
else
  fail "the PR's files differ from #36228's: $(comm -3 <(echo "$pr_files") <(echo "$fix_files") | tr '\n' ' ')"
fi

# 3. Server and contract code: the PR's added/removed code lines equal #36228's (comments ignored;
#    the PR's `Schema.optional` is #36228's `Schema.optionalKey` for the same optional `query` field).
code_lines() {
  git diff "$1" "$2" -- "$3" | grep -E '^[-+][^-+]' | sed -E 's/^([-+])[[:space:]]+/\1/' \
    | grep -vE '^[-+](//|/\*\*|\*)' | sed 's/Schema\.optionalKey(/Schema.optional(/' | sort || true
}
same=1
for f in apps/server/src/workspace/WorkspaceEntries.ts apps/server/src/environment/ServerEnvironment.ts \
  apps/web/src/lib/addProjectToMachine.ts packages/contracts/src/environment.ts packages/contracts/src/project.ts; do
  if [ "$(code_lines "$MB" "$PR_HEAD" "$f")" != "$(code_lines "$PARENT" "$FIX" "$f")" ]; then
    same=0
    echo "  differs: $f"
  fi
done
if [ "$same" = 1 ]; then
  pass "server query filter, ignoredFileSearch capability, contracts and COPIED_FILES_MAX_COUNT are the same code in the PR and #36228"
else
  fail "the PR's server/contract code differs from #36228's"
fi

# 4. Dialog: every line the PR has that #36228's dialog lacks is the 150 ms debounce, a moved
#    `searching` line, the "N selected" label (main shows "N of M"), or an "Up to 200 files" note at the cap.
git show "$PR_HEAD:$DIALOG" > "$WORK/dialog-pr.tsx"
git show "$FIX:$DIALOG" > "$WORK/dialog-fix.tsx"
diff "$WORK/dialog-pr.tsx" "$WORK/dialog-fix.tsx" | grep '^<' | sed -E 's/^<[[:space:]]*//' | grep -v '^$' | sort -u > "$WORK/pr-only.txt" || true
cat > "$WORK/expected.txt" <<'EOF'
const sentFileQuery = useDebouncedValue(fileQuery.trim(), 150);
project && canSearchFiles && sentFileQuery.length > 0
const searching = canSearchFiles && sentFileQuery.length > 0;
{selectedFiles.size > 0 ? (
<span className="text-muted-foreground text-xs">
{selectedFiles.size} selected
{selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
</span>
) : null}
<Button type="button" variant="ghost" size="xs" onClick={toggleShownFiles}>
{allCopyableSelected ? "None" : "All"}
</Button>
</p>
{atSelectionLimit ? (
<p className="text-muted-foreground text-xs">
Up to {COPIED_FILES_MAX_COUNT} files can be copied.
EOF
sort -u -o "$WORK/expected.txt" "$WORK/expected.txt"
if cmp -s "$WORK/pr-only.txt" "$WORK/expected.txt"; then
  pass "the PR's dialog differs from #36228's only in the debounce (150 vs 120 ms), the count label, and an 'Up to 200 files can be copied.' note"
else
  fail "the PR's dialog has lines beyond the known copy differences:"
  diff "$WORK/expected.txt" "$WORK/pr-only.txt" || true
fi
for needle in 'capabilities?.ignoredFileSearch === true' 'aria-label="Search ignored files"' \
  'input: { cwd: project.workspaceRoot, query: sentFileQuery }' \
  'useState<ReadonlyMap<string, ProjectIgnoredFile> | null>' \
  'disabled={atSelectionLimit && !selectedFiles.has(file.path)}' 'files: [...selectedFiles.keys()]'; do
  if ! grep -qF "$needle" "$WORK/dialog-fix.tsx"; then
    fail "#36228's dialog lacks: $needle"
  fi
done
if grep -qF 'ignoredFileSearch' <(git show "$PARENT:$DIALOG"); then
  fail "the fix's parent already had ignoredFileSearch in the dialog"
else
  pass "#36228's dialog searches past the cutoff when the server has ignoredFileSearch, keeps picks across searches in a Map, caps selection at 200, and submits every pick; its parent had none of this"
fi

# 5. Behavioral: the PR's own regression test, taken verbatim from its diff, in its own describe block.
git diff "$MB" "$PR_HEAD" -- "$TEST" | grep -E '^\+' | grep -vE '^\+\+\+' | sed 's/^+//' > "$WORK/pr-test.ts"
if ! grep -qF 'query: "FILE-205"' "$WORK/pr-test.ts"; then
  fail "could not extract the PR's regression test"
fi
append_claim_test() {
  {
    echo
    echo 'it.layer(layerTest, { excludeTestServices: true })("PR 24795 claim", (it) => {'
    cat "$WORK/pr-test.ts"
    echo '});'
  } >> "$TEST"
}
run_claim() {
  (cd apps/server && vp test run src/workspace/WorkspaceEntries.test.ts -t "PR 24795 claim") > "$1" 2>&1 || true
  sed 's/\x1b\[[0-9;]*m//g' "$1" | grep -E "Tests +[0-9]|AssertionError|truncated" | head -8 || tail -20 "$1"
}

git checkout -q --detach "$MAIN"
append_claim_test
run_claim "$WORK/main.log"
if grep -qE "Tests +1 passed" "$WORK/main.log" && ! grep -qE "Tests +.*failed" "$WORK/main.log"; then
  pass "on main ${MAIN:0:10}, the PR's test passes: listIgnoredFiles({ query: \"FILE-205\" }) over 205 ignored files returns exactly file-205.secret, not truncated"
else
  fail "the PR's test does not pass on main"
fi
git checkout -q -f -- .

git checkout -q --detach "$PARENT"
append_claim_test
run_claim "$WORK/parent.log"
if grep -qE "Tests +1 failed" "$WORK/parent.log" && grep -qF "AssertionError" "$WORK/parent.log" \
  && sed 's/\x1b\[[0-9;]*m//g' "$WORK/parent.log" | grep -qE '"truncated": true'; then
  pass "at #36228's parent ${PARENT:0:10}, the same test fails: the query is ignored and the first 200 files come back truncated"
else
  fail "the PR's test did not fail as expected at the fix's parent $PARENT"
fi
git checkout -q -f -- .

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