#!/usr/bin/env bash
# Applies each mutation inside a transaction, evaluates the catalogue assertions
# under both predicates, and rolls back. Baseline violations are subtracted.
set -euo pipefail
DB=${1:-wayclub_test}; HERE=$(cd "$(dirname "$0")/.." && pwd)
PSQL="${PSQL:-/opt/homebrew/opt/postgresql@17/bin/psql} -h localhost -p ${PGPORT_EXP:-55499} -U postgres -d $DB -At -F| -v ON_ERROR_STOP=1 -q"
run() { { echo "begin;"; [ -n "$1" ] && cat "$1"; cat "$HERE/sql/catalogue_assertions.sql"; echo "rollback;"; } | $PSQL; }
base=$(run "")
echo "mutation|predicate|new_violations"
for m in "$HERE"/sql/mutations/M*.sql; do
  out=$(run "$m")
  for p in new old scope-free; do
    nv=$(comm -13 <(echo "$base" | grep "^$p|" | sort) <(echo "$out" | grep "^$p|" | sort) | cut -d'|' -f2,3 | paste -sd';' -)
    echo "$(basename "$m" .sql)|$p|${nv:-NONE (suite stays green)}"
  done
done
