#!/usr/bin/env bash
# R2 weekly numbers - the recipe's own smoke test. Read-date 2026-11-10.
#
# Runs the real report over the shipped export into ONE temporary directory it
# creates, checks the arithmetic against numbers a person can re-add by hand,
# and proves the two files shipped in out/ are what the program writes at its
# own fixed clock rather than a hand-edit of it.
#
#   bash smoke.sh
#
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT

# The clock the shipped pair was generated at, taken from the test file so the
# two cannot drift apart.
STAMP=$(grep -oP 'SHIP_STAMP\s*=\s*"\K[^"]+' "$HERE/test_weekly_report.py" | head -1)
if [ -z "$STAMP" ]; then
  echo "FAIL: no SHIP_STAMP found in test_weekly_report.py, so nothing can be compared"
  exit 1
fi

cd "$HERE"
python3 weekly_report.py --input samples/weekly_sales.csv --outdir "$WORK/out" \
    --now "$STAMP" --quiet; rc=$?
if [ "$rc" -ne 0 ]; then
  echo "FAIL: the program exited $rc over its own sample"; exit 1
fi
for f in report.txt report.html; do
  if [ ! -s "$WORK/out/$f" ]; then echo "FAIL: $f was not written"; exit 1; fi
done

report="$WORK/out/report.txt"

# --- the arithmetic, checked against a hand addition ------------------------ #
# The shipped sample totals units 48 this week against 39 last week.
# (48 - 39) / 39 * 100 = 23.076923 %, printed to one decimal as +23.1 %.
grep -q 'units .*48 .*39 .*+9 .*+23.1%' "$report"; units_rc=$?
if [ "$units_rc" -ne 0 ]; then
  echo "FAIL: the units row is not 48 against 39 with the +23.1 % that follows from it"
  grep '^units' "$report" | sed 's/^/      /'
  exit 1
fi

# A column that is not numbers is named as left out, not added up as zero.
for col in region export_email; do
  grep -qi "$col" "$report"; col_rc=$?
  if [ "$col_rc" -ne 0 ]; then
    echo "FAIL: the non-numeric column $col is not named anywhere in the report"; exit 1
  fi
done

# What was refused says so with its row, instead of becoming a zero.
grep -qi 'blank' "$report"; blank_rc=$?
if [ "$blank_rc" -ne 0 ]; then
  echo "FAIL: the blank cells in the sample are not reported"; exit 1
fi

# --- the shipped pair is the program's own output --------------------------- #
for f in report.txt report.html; do
  cmp -s "out/$f" "$WORK/out/$f"; cmp_rc=$?
  if [ "$cmp_rc" -ne 0 ]; then
    echo "FAIL: out/$f does not match what the program writes at $STAMP - one of them was edited by hand"
    diff "out/$f" "$WORK/out/$f" | head -8 | sed 's/^/      /'
    exit 1
  fi
done

echo "R2 smoke OK: units 48 vs 39 stated as +23.1 % (hand addition agrees), region and export_email named as left out, blanks reported, and out/report.txt plus out/report.html match the program byte for byte at $STAMP."
