#!/usr/bin/env bash
# PR #32378 (fix(server): deleted threads release their stored history)
# Claim: already-fixed. #42119 (91f0b32e2d) makes deleting a thread purge its conversation rows,
# and its maintenance pass sweeps every deleted thread that still holds content (issue #17845).
# Shows: the PR's own purge tests, adapted only to main's result field name (purgedRowCount) and
# without the PR's 1-day wait (main purges at once), pass on main and fail at #42119's parent.
# Needs deps installed (`vp i`) and `gh` authenticated. Run from the root of a clean checkout.
set -euo pipefail

REPO=pingdotgg/t3code
FIX=91f0b32e2db2cb8abca5fdd33c33609a0f57b15e
TEST=apps/server/src/orchestration-v2/ProjectionMaintenance.test.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/32378/head
PR_HEAD=$(git rev-parse FETCH_HEAD)
echo "main=$MAIN pr_head=$PR_HEAD fix=$FIX"

# 1. #42119 is merged, on main, and closed the PR's issue.
if git merge-base --is-ancestor "$FIX" "$MAIN"; then
  pass "#42119 is on main as ${FIX:0:10} ($(git log -1 --format=%s "$FIX"))"
else
  fail "${FIX:0:10} is not on main"
fi
merged=$(gh pr view 42119 --repo "$REPO" --json state,mergeCommit --jq '"\(.state) \(.mergeCommit.oid)"')
if [ "$merged" = "MERGED $FIX" ]; then
  pass "gh: #42119 is MERGED with merge commit ${FIX:0:10}"
else
  fail "gh: #42119 state/merge commit is '$merged'"
fi
issue=$(gh issue view 17845 --repo "$REPO" --json state,closedByPullRequestsReferences --jq '"\(.state) \([.closedByPullRequestsReferences[].number]|map(tostring)|join(","))"')
case "$issue" in
  "CLOSED "*42119*) pass "gh: issue #17845 (the PR's 'Fixes') is CLOSED by #42119" ;;
  *) fail "gh: issue #17845 is '$issue'" ;;
esac
if git show "$FIX:apps/server/src/orchestration-v2/ThreadDeletion.ts" | grep -q 'type: "thread-content.purge"' \
  && git show "$FIX:apps/server/src/orchestration-v2/ProjectionMaintenance.ts" | grep -q 'purgedRowCount = yield\* purgeThreads(undefined, betweenPages)'; then
  pass "at ${FIX:0:10}, thread.delete queues thread-content.purge and pruneEventStore sweeps all deleted threads"
else
  fail "the purge-on-delete and maintenance sweep are not in ${FIX:0:10}"
fi

# 2. Behavior: the PR's purge tests, appended to the test file at each commit.
write_block() {
  cat >> "$TEST" <<'EOF'

import { MessageId as Pr32378MessageId, RunId as Pr32378RunId } from "@t3tools/contracts";

// Adapted from PR #32378's tests: result field renamed to main's purgedRowCount, and the
// "kept within one day" assertions dropped because main purges a deleted thread at once.
const pr32378Count = (threadId: ThreadId) =>
  Effect.flatMap(
    SqlClient.SqlClient,
    (sql) => sql<{
      readonly items: number;
      readonly positions: number;
      readonly counts: number;
      readonly messages: number;
      readonly found: number;
      readonly threads: number;
    }>`
      SELECT
        (SELECT COUNT(*) FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId}) AS items,
        (SELECT COUNT(*) FROM orchestration_v2_turn_item_positions WHERE thread_id = ${threadId}) AS positions,
        (SELECT COUNT(*) FROM orchestration_v2_projection_turn_item_counts WHERE thread_id = ${threadId}) AS counts,
        (SELECT COUNT(*) FROM orchestration_v2_projection_messages WHERE thread_id = ${threadId}) AS messages,
        (SELECT COUNT(*) FROM orchestration_v2_message_search WHERE orchestration_v2_message_search MATCH ${`purgeable${threadId.replace(/\W/g, "")}`}) AS found,
        (SELECT COUNT(*) FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId}) AS threads
    `,
  ).pipe(Effect.map((rows) => rows[0]));

const pr32378Fixture = Effect.gen(function* () {
  const sink = yield* EventSink.EventSinkV2;
  const projections = yield* ProjectionStore.ProjectionStoreV2;
  const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
  const now = yield* DateTime.now;
  const seed = Effect.fnUntraced(function* (
    name: string,
    forkedFrom: OrchestrationV2AppThread["forkedFrom"] = null,
  ) {
    const threadId = ThreadId.make(`thread:purge-${name}`);
    const thread = { ...makeThread(threadId, now), forkedFrom };
    yield* sink.write({
      events: [{ ...threadCreated(thread, now), id: EventId.make(`event:purge:${name}:thread`) }],
    });
    const item = itemEvent(threadId, now, itemSpecs[0], 0, `event:purge:${name}:item`);
    yield* sink.write({
      events: [
        item.type === "turn-item.updated"
          ? { ...item, payload: { ...item.payload, id: TurnItemId.make(`turn-item:purge:${name}`) } }
          : item,
      ],
    });
    yield* sink.write({
      events: [
        {
          id: EventId.make(`event:purge:${name}:message`),
          type: "message.updated",
          threadId,
          occurredAt: now,
          payload: {
            id: Pr32378MessageId.make(`message:purge:${name}`),
            threadId,
            runId: null,
            nodeId: null,
            createdBy: "agent",
            creationSource: "provider",
            role: "assistant",
            text: `purgeable${threadId.replace(/\W/g, "")}`,
            streaming: false,
            attachments: [],
            createdAt: now,
            updatedAt: now,
          },
        },
      ],
    });
    return thread;
  });
  const remove = (thread: OrchestrationV2AppThread, at: DateTime.Utc) =>
    sink.write({
      events: [
        {
          id: EventId.make(`event:purge:${thread.id}:deleted`),
          type: "thread.deleted",
          threadId: thread.id,
          occurredAt: at,
          payload: { ...thread, deletedAt: at, updatedAt: at },
        },
      ],
    });
  return { projections, maintenance, now, seed, remove };
});

it.effect("pr-32378: purges content of a deleted thread and keeps its tombstone", () =>
  Effect.gen(function* () {
    const { projections, maintenance, now, seed, remove } = yield* pr32378Fixture;
    const old = yield* seed("old");
    const live = yield* seed("live");
    yield* remove(old, now);
    yield* TestClock.adjust("1 day");
    const liveBefore = yield* projections.getThreadProjection(live.id);
    const beforeOld = yield* pr32378Count(old.id);
    assert.isAbove(beforeOld?.items ?? 0, 0);
    assert.isAbove(beforeOld?.positions ?? 0, 0);
    assert.isAbove(beforeOld?.counts ?? 0, 0);
    assert.equal(beforeOld?.found, 1);

    const first = yield* maintenance.pruneEventStore();
    assert.deepEqual(yield* pr32378Count(old.id), {
      items: 0,
      positions: 0,
      counts: 0,
      messages: 0,
      found: 0,
      threads: 1,
    });
    assert.isAbove((first as { readonly purgedRowCount?: number }).purgedRowCount ?? 0, 0);
    assert.deepEqual(yield* projections.getThreadProjection(live.id), liveBefore);
    assert.equal((yield* pr32378Count(live.id))?.found, 1);
    assert.equal(
      ((yield* maintenance.pruneEventStore()) as { readonly purgedRowCount?: number })
        .purgedRowCount,
      0,
    );
  }).pipe(Effect.provide(layerTest)),
);

it.effect("pr-32378: keeps deleted threads a live thread still inherits or merges back from", () =>
  Effect.gen(function* () {
    const { maintenance, now, seed, remove } = yield* pr32378Fixture;
    const sql = yield* SqlClient.SqlClient;
    const root = yield* seed("root");
    const middle = yield* seed("middle", {
      type: "run",
      threadId: root.id,
      runId: Pr32378RunId.make("run:purge:root"),
    });
    const fork = yield* seed("fork", {
      type: "run",
      threadId: middle.id,
      runId: Pr32378RunId.make("run:purge:middle"),
    });
    const unrelated = yield* seed("unrelated");
    const mergedBack = yield* seed("merged-back");
    yield* sql`
      INSERT INTO orchestration_v2_projection_context_transfers
        (context_transfer_id, source_thread_id, target_thread_id, type, status, updated_at, payload_json)
      VALUES ('transfer:purge', ${mergedBack.id}, ${fork.id},
        'merge_back', 'pending', ${DateTime.formatIso(now)}, '{}')
    `;
    yield* remove(mergedBack, yield* DateTime.now);
    yield* remove(root, yield* DateTime.now);
    yield* remove(middle, yield* DateTime.now);
    yield* remove(unrelated, yield* DateTime.now);
    yield* TestClock.adjust("2 days");

    yield* maintenance.pruneEventStore();
    assert.equal((yield* pr32378Count(root.id))?.items, 1);
    assert.equal((yield* pr32378Count(middle.id))?.items, 1);
    assert.equal((yield* pr32378Count(fork.id))?.items, 1);
    assert.equal((yield* pr32378Count(unrelated.id))?.items, 0);
    assert.equal((yield* pr32378Count(mergedBack.id))?.items, 1);
  }).pipe(Effect.provide(layerTest)),
);

it.effect("pr-32378: purges a very large thread in bounded batches", () =>
  Effect.gen(function* () {
    const { maintenance, seed, remove } = yield* pr32378Fixture;
    const sql = yield* SqlClient.SqlClient;
    const big = yield* seed("big");
    yield* sql`
      INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal)
      WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1200)
      SELECT ${big.id}, 'turn-item:purge:filler:' || i, i + 100 FROM n
    `;
    yield* remove(big, yield* DateTime.now);
    yield* TestClock.adjust("2 days");

    const result = yield* maintenance.pruneEventStore();
    assert.equal((yield* pr32378Count(big.id))?.positions, 0);
    assert.isAtLeast((result as { readonly purgedRowCount?: number }).purgedRowCount ?? 0, 1200);
  }).pipe(Effect.provide(layerTest)),
);
EOF
}

run_block() {
  git checkout -q --detach "$1"
  write_block
  vp test run "$TEST" -t "pr-32378" > "$2" 2>&1 || true
  git checkout -q -f -- "$TEST"
  grep -E "Tests +[0-9]" "$2" || true
}

run_block "$MAIN" "$WORK/main.log"
if grep -qE "Tests +3 passed" "$WORK/main.log" && ! grep -qE "Tests +.*[0-9]+ failed" "$WORK/main.log"; then
  pass "on main ${MAIN:0:10}, all 3 adapted PR tests pass: content purged, tombstone kept, fork/merge-back sources kept, a 1,200-row thread fully purged"
else
  fail "the adapted PR tests do not all pass on main ${MAIN:0:10}"
  grep -E "FAIL|AssertionError" "$WORK/main.log" | head -5 || true
fi

run_block "$FIX^" "$WORK/parent.log"
grep -E "AssertionError" "$WORK/parent.log" | head -3 || true
if grep -qE "Tests +3 failed" "$WORK/parent.log"; then
  pass "at #42119's parent ${FIX:0:10}^, the same 3 tests fail: deleted threads keep their rows"
else
  fail "the adapted PR tests do not all fail at ${FIX:0:10}^"
fi

if [ "$ok" = 1 ]; then
  echo "VERDICT: CLOSE (already-fixed) - #42119 purges deleted threads' projection content, which is what this PR delivers"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: claim not supported"
exit 1
