#!/usr/bin/env bash
# Renders /sale-report for three windows as an administrator and checks the
# "Total Amount" strip against the values verified in Round 8 / Round 21.
#
# These three numbers are the contract for any change to the sale report's
# total: they must not move.
#
#   2026-07-01 .. 2026-08-31   $4,716.00
#   2026-06-01 .. 2026-06-30   $3,200.00
#   2025-01-01 .. 2025-12-31   $349,606.35
#
# The total is rendered TWICE per page (the attachment sits above and below the
# table), so the expected result is exactly two occurrences of each.
#
# Run from the D10 directory:
#   bash scripts/reconcile/verify_sale_report_totals.sh
set -uo pipefail

BASE="${BASE_URL:-http://ceonline-d10.ddev.site}"
COOKIE="$(mktemp)"
trap 'rm -f "$COOKIE" /tmp/srt_page.html' EXIT

curl -s -c "$COOKIE" -L "$(ddev drush uli --uid=1 --no-browser 2>/dev/null | tail -1)" -o /dev/null

WINDOWS=(
  "2026-07-01|2026-08-31|\$4,716.00"
  "2026-06-01|2026-06-30|\$3,200.00"
  "2025-01-01|2025-12-31|\$349,606.35"
)

fail=0
printf "%-26s %-8s %-16s %s\n" "WINDOW" "ROWS" "TOTAL" "RESULT"
printf -- "------------------------------------------------------------------------\n"

for spec in "${WINDOWS[@]}"; do
  IFS='|' read -r min max want <<< "$spec"
  url="$BASE/sale-report?created%5Bmin%5D=$min&created%5Bmax%5D=$max&title=&field_instructor_s__value=&field_ce_or_non_ce_value=All"
  start=$(date +%s)
  curl -s -b "$COOKIE" --max-time 300 "$url" -o /tmp/srt_page.html
  elapsed=$(( $(date +%s) - start ))

  result="$(WANT="$want" ELAPSED="$elapsed" python3 - /tmp/srt_page.html <<'PY'
import os, re, sys
want = os.environ['WANT']
html = open(sys.argv[1]).read()
rows = len(re.findall(r'<tr[^>]*>', html))
totals = re.findall(r'Total Amount:\s*</span>\s*<div class="field-content">([^<]*)', html)
fatal = bool(re.search(r'Allowed memory size|Fatal error', html))
ok = (totals == [want, want]) and not fatal
note = 'PASS' if ok else ('FATAL' if fatal else 'MISMATCH -> ' + repr(totals))
print(f"{rows}|{want}|{note}|{os.environ['ELAPSED']}")
PY
)"
  IFS='|' read -r rows wanted note secs <<< "$result"
  printf "%-26s %-8s %-16s %s (%ss)\n" "$min..$max" "$rows" "$wanted" "$note" "$secs"
  [[ "$note" == "PASS" ]] || fail=$((fail + 1))
done

echo
if [[ $fail -eq 0 ]]; then
  echo "All three totals match."
else
  echo "$fail window(s) FAILED."
fi
exit $fail
