#!/usr/bin/env bash

set -euo pipefail

DB_HOST="${DB_HOST:-127.0.0.1}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-quantengine_app}"
DB_PASSWORD="${DB_PASSWORD:-}"
DB_NAME="${DB_NAME:-quantenginedb}"
SCHEMA="${SCHEMA:-quantengine}"

if [ -z "${DB_PASSWORD}" ]; then
    echo "ERROR: DB_PASSWORD must be set."
    exit 1
fi

echo "Row counts in ${DB_NAME}.${SCHEMA}:"
for table in workspace_account workspace_session settings account_snapshot workspace_approval_v2 workspace_lock kis_tokens kis_collection_runs kis_collection_snapshots kis_collection_errors; do
    count=$(PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -Atc "SELECT COUNT(*) FROM ${SCHEMA}.${table};" 2>/dev/null || echo "MISSING")
    printf '%s %s\n' "${table}" "${count}"
done
