#!/usr/bin/env bash
# R1 lead capture - the recipe's own smoke test. Read-date 2026-11-10.
#
# It runs the real program over the shipped sample leads, into ONE temporary
# directory it creates and removes, and prints one evidence line at the end.
# Nothing here writes into the recipe folder, reaches the network, or sends
# anything: the program's answer is a sheet row and a DRAFT, and the drafts are
# checked as files on disk.
#
#   bash smoke.sh        # exit 0 with one evidence line, or a named failure
#
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT

python3 "$HERE/lead_capture_to_sheets.py" \
    --incoming "$HERE/samples/incoming" \
    --sheet "$WORK/leads_sheet.csv" \
    --outbox "$WORK/leads_drafts" \
    --now "2026-11-10T14:00:00Z" >"$WORK/out.txt" 2>&1; rc=$?
if [ "$rc" -ne 0 ]; then
  echo "FAIL: the program exited $rc over its own sample; its words were:"
  sed 's/^/      /' "$WORK/out.txt"
  exit 1
fi

# --- the three things a buyer actually relies on --------------------------- #
if [ ! -s "$WORK/leads_sheet.csv" ]; then
  echo "FAIL: no sheet was written into $WORK"; exit 1
fi
rows=$(( $(wc -l < "$WORK/leads_sheet.csv") - 1 ))
if [ "$rows" -lt 1 ]; then
  echo "FAIL: the sheet holds a header and no lead rows"; exit 1
fi

drafts=$(find "$WORK/leads_drafts" -name '*.txt' 2>/dev/null | wc -l)
if [ "$drafts" -lt 1 ]; then
  echo "FAIL: not one reply draft was written"; exit 1
fi

# Refusals have to be said out loud, not swallowed. These two are in the
# shipped sample on purpose: a row with no usable address, and a repeat.
grep -q 'skipped : email value is not an address' "$WORK/out.txt"; grep_rc=$?
if [ "$grep_rc" -ne 0 ]; then
  echo "FAIL: a row with an unreadable email was not reported as skipped"; exit 1
fi
grep -q 'duplicate:' "$WORK/out.txt"; dup_rc=$?
if [ "$dup_rc" -ne 0 ]; then
  echo "FAIL: a repeated lead was not reported as a duplicate"; exit 1
fi

# A draft is a draft: it must never claim to have been sent.
first_draft=$(find "$WORK/leads_drafts" -name '*.txt' | sort | head -1)
if grep -qi 'has been sent' "$first_draft"; then
  echo "FAIL: a draft states that something was already sent"; exit 1
fi

echo "R1 smoke OK: $rows lead row(s) on the sheet, $drafts draft(s) on disk, an unreadable address and a repeat both reported, and no draft claims to have been sent."
