#!/usr/bin/env bash
# R3 payment reminders - the recipe's own smoke test. Read-date 2026-11-10.
#
# Runs the real program over the shipped invoice export at a fixed date into
# ONE temporary outbox it creates, and checks the promise the recipe is sold
# on: the numbers arrive, and nothing goes anywhere by itself.
#
#   bash smoke.sh
#
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT

cd "$HERE"
python3 invoice_reminders.py --input samples/invoices_sample.csv \
    --outbox "$WORK/outbox" --as-of 2026-11-16 >"$WORK/out.txt" 2>&1; rc=$?
if [ "$rc" -ne 0 ]; then
  echo "FAIL: the program exited $rc over its own sample"; sed 's/^/      /' "$WORK/out.txt"; exit 1
fi

drafts=$(find "$WORK/outbox" -name '*.txt' -type f 2>/dev/null | wc -l)
if [ "$drafts" -lt 1 ]; then
  echo "FAIL: the sample produced no reminder draft at 2026-11-16"; exit 1
fi

# A draft must carry the three facts a customer will check. The shipped sample
# is invented data on .example addresses; INV-1002 is the one row that owes a
# thousand-odd with a comma in it, so it also proves the figure survives.
missing=""
for fact in 'Invoice' 'INV-' '2026-'; do
  grep -qs -- "$fact" "$WORK/outbox"/*.txt || missing="$missing $fact"
done
if [ -n "$missing" ]; then
  echo "FAIL: no draft states these: $missing"; exit 1
fi

# The point of the recipe, tested rather than asserted in prose: not one file
# here claims to have been delivered.
if grep -rli -e 'has been sent' -e 'successfully sent' "$WORK/outbox" >/dev/null 2>&1; then
  echo "FAIL: a draft says something was already sent"; exit 1
fi
grep -q 'send it yourself' "$WORK/out.txt"; close_rc=$?
if [ "$close_rc" -ne 0 ]; then
  echo "FAIL: the run did not hand the sending back to a person"; exit 1
fi

# The guard the file runs on itself at import is named in its own source and
# still exists; if either half disappears, the promise is gone.
guard=$(grep -oP 'SELF_CHECK\s*=\s*"\K[A-Za-z_][A-Za-z0-9_]*' invoice_reminders.py | head -1)
if [ -z "$guard" ]; then
  echo "FAIL: SELF_CHECK no longer names its own check"; exit 1
fi
grep -q "def $guard(" invoice_reminders.py; guard_rc=$?
if [ "$guard_rc" -ne 0 ]; then
  echo "FAIL: SELF_CHECK names $guard and no such function is defined"; exit 1
fi

echo "R3 smoke OK: $drafts draft(s) written to a temporary outbox, each naming an invoice and a date, none claiming to have been sent, the run handing the sending to a person, and the no-send guard $guard() still defined."
