#!/usr/bin/env bash
# PR #36432 (fix(mobile): project filter lists recently used projects first), for issue #36424.
# Claim: already-fixed. #36433 (6b47939e60) changed the same three mobile thread-list filter surfaces
# (HomeScreen iOS pill, HomeRouteScreen header menu, ThreadNavigationSidebar) to list projects pinned first,
# then by recent thread activity, using the sortHomeProjectScopes + pickableProjectGroups composition this PR wraps.
# Shows: the issue is closed by #36433; the call sites at 6b47939e60 use that composition and its parent did not;
# the PR's own test fixture yields the PR's expected order through 6b47939e60's call-site expression.
# Needs deps installed (`vp i`) and `gh` authenticated. Run from the root of a clean t3code checkout.
set -euo pipefail

REPO=pingdotgg/t3code
FIX=6b47939e606b17fc6fab278eec3fcbde65995514
TEST=apps/mobile/src/features/home/prove-pr-36432.test.ts
SURFACES="apps/mobile/src/features/home/HomeRouteScreen.tsx apps/mobile/src/features/home/HomeScreen.tsx apps/mobile/src/features/threads/ThreadNavigationSidebar.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() {
  rm -f "$TEST"
  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/36432/head
PR_HEAD=$(git rev-parse FETCH_HEAD)
PARENT=$(git rev-parse "$FIX^")
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/36424" --jq '"\(.state) \(.state_reason)"')
closer=$(gh api graphql -f query='{repository(owner:"pingdotgg",name:"t3code"){issue(number:36424){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" = "36433 true" ]; then
  pass "issue #36424 (the bug this PR fixes) is closed as completed by merged PR #36433"
else
  fail "issue #36424 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 "(#36433)" <<< "$subject"; then
  pass "#36433 is on main as ${FIX:0:10} ($subject); the PR branch predates it"
else
  fail "$FIX is not #36433 on main, or the PR branch already contains it"
fi

# 2. Static: #36433 changed only the three filter surfaces this PR changes, and each now sorts by recency.
fix_files=$(git diff --name-only "$PARENT" "$FIX" | sort | tr '\n' ' ')
want_files=$(echo $SURFACES | tr ' ' '\n' | sort | tr '\n' ' ')
pr_files=$(git diff --name-only "$(git merge-base "$MAIN" "$PR_HEAD")" "$PR_HEAD" | tr '\n' ' ')
covered=1
for f in $SURFACES; do grep -qF " $f " <<< " $pr_files " || covered=0; done
if [ "$fix_files" = "$want_files" ] && [ "$covered" = 1 ]; then
  pass "#36433 touched exactly the three filter surfaces this PR changes: $fix_files"
else
  fail "file sets differ: #36433='$fix_files' PR='$pr_files'"
fi
SORTED_TAIL='pendingTasks:[],projectSortOrder:"updated_at",}),).map((scope)=>({key:scope.key,label:scope.title,}))'
SORTED_A="pickableProjectGroups(sortHomeProjectScopes({scopes:projectScopes,threads,$SORTED_TAIL"
SORTED_B="pickableProjectGroups(sortHomeProjectScopes({scopes:projectScopes,threads:props.threads,$SORTED_TAIL"
UNSORTED='pickableProjectGroups(projectScopes).map((scope)=>({key:scope.key,label:scope.title,}))'
for f in $SURFACES; do
  after=$(git show "$FIX:$f" | tr -d ' \n')
  before=$(git show "$PARENT:$f" | tr -d ' \n')
  if { grep -qF "$SORTED_A" <<< "$after" || grep -qF "$SORTED_B" <<< "$after"; } \
    && grep -qF "$UNSORTED" <<< "$before" \
    && ! grep -qF "$UNSORTED" <<< "$after"; then
    pass "$(basename "$f"): filter options are pickableProjectGroups(sortHomeProjectScopes(..., \"updated_at\")) at ${FIX:0:10}; unsorted pickableProjectGroups(projectScopes) at its parent"
  else
    fail "$(basename "$f"): expected sorted filter options at $FIX and unsorted at $PARENT"
  fi
done
picker=$(git show "$FIX:apps/mobile/src/features/threads/new-task-flow-provider.tsx" | tr -d ' \n')
if grep -qF 'threads,pendingTasks:[],projectSortOrder:"updated_at",});' <<< "$picker"; then
  pass "at ${FIX:0:10} the filter passes the same sortHomeProjectScopes arguments as the new-task project picker the issue asks it to match"
else
  fail "new-task picker sort arguments differ at $FIX"
fi

# 3. Behavioral at the fix commit: the PR's own test fixture and expected orders, run through the
#    call-site expression from step 2 (and the parent's unsorted expression for contrast).
git checkout -q --detach "$FIX"
cat > "$TEST" <<'EOF'
import type {
  EnvironmentProject,
  EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";

import { buildHomeProjectScopes, sortHomeProjectScopes, type HomeProjectScope } from "./homeThreadList";
import { makeThreadShellFixture } from "../../test-fixtures";

function makeProject(
  input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
): EnvironmentProject {
  return {
    workspaceRoot: `/workspaces/${input.id}`,
    repositoryIdentity: null,
    defaultModelSelection: null,
    scripts: [],
    createdAt: "2026-06-01T00:00:00.000Z",
    updatedAt: "2026-06-01T00:00:00.000Z",
    ...input,
  };
}

function makeThread(
  input: Partial<EnvironmentThreadShell> &
    Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
): EnvironmentThreadShell {
  return makeThreadShellFixture({
    modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
    runtimeMode: "full-access",
    interactionMode: "default",
    branch: null,
    worktreePath: null,
    createdAt: "2026-06-01T00:00:00.000Z",
    updatedAt: "2026-06-01T00:00:00.000Z",
    archivedAt: null,
    latestUserMessageAt: null,
    hasPendingApprovals: false,
    hasPendingUserInput: false,
    hasActionableProposedPlan: false,
    ...input,
  });
}

// PR #36432's fixture: alpha last active 06-02, gamma 06-03, beta never.
const environmentId = EnvironmentId.make("local");
const projects = ["alpha", "beta", "gamma"].map((name) =>
  makeProject({ environmentId, id: ProjectId.make(name), title: name }),
);
const scopes = buildHomeProjectScopes({ projects, environmentId: null, projectGroupingMode: "separate" });
const threads = [
  ["alpha", "2026-06-02T00:00:00.000Z"],
  ["gamma", "2026-06-03T00:00:00.000Z"],
].map(([projectId, messagedAt]) =>
  makeThread({
    environmentId,
    projectId: ProjectId.make(projectId!),
    id: ThreadId.make(`thread-${projectId}`),
    title: projectId!,
    latestUserAuthoredMessageAt: messagedAt!,
  }),
);
const pinned = (pinnedKey?: string) => scopes.map((scope) => ({ ...scope, pinned: scope.key === pinnedKey }));
const betaKey = scopes.find((scope) => scope.title === "beta")!.key;

// The expression HomeScreen, HomeRouteScreen and ThreadNavigationSidebar use at the fix commit.
const fixOptions = (projectScopes: ReadonlyArray<HomeProjectScope>) =>
  pickableProjectGroups(
    sortHomeProjectScopes({ scopes: projectScopes, threads, pendingTasks: [], projectSortOrder: "updated_at" }),
  ).map((scope) => ({ key: scope.key, label: scope.title }));
// The expression they used at the fix commit's parent.
const parentOptions = (projectScopes: ReadonlyArray<HomeProjectScope>) =>
  pickableProjectGroups(projectScopes).map((scope) => ({ key: scope.key, label: scope.title }));
const labels = (options: ReadonlyArray<{ label: string }>) => options.map((option) => option.label);

describe("PR 36432 claim", () => {
  it("fix call sites: filter options are ordered by most recent thread activity, pinned first", () => {
    expect(labels(fixOptions(pinned()))).toEqual(["gamma", "alpha", "beta"]);
    expect(labels(fixOptions(pinned(betaKey)))).toEqual(["beta", "gamma", "alpha"]);
  });

  it("parent call sites: filter options ignore recent activity", () => {
    expect(labels(parentOptions(pinned()))).not.toEqual(["gamma", "alpha", "beta"]);
  });
});
EOF
vp test run --reporter=verbose "$TEST" > "$WORK/test.log" 2>&1 || true
grep -E "(✓|×) .*PR 36432|Tests +[0-9]" "$WORK/test.log" || tail -30 "$WORK/test.log"
if grep -qE "Tests +2 passed" "$WORK/test.log" && ! grep -qE "Tests +.*failed" "$WORK/test.log"; then
  pass "at ${FIX:0:10}, the PR's fixture through the call-site expression lists gamma, alpha, beta (beta first when pinned), the PR's own expected orders; the parent's expression does not"
else
  fail "the PR's expected order did not hold through the fix commit's call-site expression"
fi

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