#!/usr/bin/env bash
# PR #32378 real-app check: what a thread leaves in a dev server's statev2.sqlite.
# Usage: count-thread-rows.sh <statev2.sqlite> <thread id> <marker text>
# Opens the database read-only. Prints every table with rows for the thread (tables with a
# thread_id column), the thread row's deleted_at, and how many rows anywhere contain the marker.
set -euo pipefail
DB=$1 THREAD=$2 MARKER=$3
q() { sqlite3 -readonly "$DB" "$1"; }

echo "thread $THREAD"
echo "deleted_at: $(q "SELECT coalesce(deleted_at, 'null') FROM orchestration_v2_projection_threads WHERE thread_id = '$THREAD';")"
total=0
for table in $(q "SELECT m.name FROM sqlite_master m WHERE m.type = 'table' AND EXISTS (SELECT 1 FROM pragma_table_info(m.name) p WHERE p.name = 'thread_id') ORDER BY m.name;"); do
  n=$(q "SELECT count(*) FROM \"$table\" WHERE thread_id = '$THREAD';")
  if [ "$n" -gt 0 ]; then
    printf '  %-48s %6d\n' "$table" "$n"
    total=$((total + n))
  fi
done
echo "rows keyed by this thread: $total"
hits=$(sqlite3 -readonly "$DB" .dump | grep -c -- "$MARKER" || true)
echo "rows anywhere containing \"$MARKER\": $hits"
