#!/bin/sh
# REPLAY, not the live agent run. This script deterministically re-enacts the
# successful command path of the recorded agent run (see
# agent-run.transcript.md calls 15 and 20-21) in a fresh temporary directory:
# preview first, then apply, then check, balance and income statement.
# Inputs are the canonical challenge downloads; the rules are the agent's own
# rules.toml bytes, embedded verbatim. The full record, including the agent's
# exploratory reads and its one failed apply (sandboxed cache lock), lives in
# the transcript — this replay shows the working path only.
#
# Usage: sh demo-replay.sh   (needs `bea 0.1.0` on PATH)
set -eu

HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
INPUTS="$HERE/../agent-accounting"

WORK=$(mktemp -d "${TMPDIR:-/tmp}/agent-demo-XXXXXX")
trap 'rm -rf "$WORK"' EXIT INT TERM
mkdir -p "$WORK/books"

cp "$INPUTS/main.bean" "$WORK/books/main.bean"
cp "$INPUTS/statement.csv" "$WORK/statement.csv"

# The agent's rules, byte for byte (match is case-insensitive in bea).
cat > "$WORK/rules.toml" <<'EOF'
[[rule]]
match = "Client"
account = "Income:Consulting"

[[rule]]
match = "Hosting"
account = "Expenses:Software"

[[rule]]
match = "Cafe"
account = "Expenses:Dining"
EOF

# Isolated config and cache: the live run learned (the hard way) that bea
# locks live under XDG_CACHE_HOME, which must be writable here.
export BEA_CONFIG_DIR="$WORK/config"
export XDG_CACHE_HOME="$WORK/cache"
export BEA_NO_UPDATE_NOTIFIER=1
BEA_FILE="$WORK/books/main.bean"

echo "\$ bea --version"
bea --version

echo "\$ bea import (preview)"
bea --file "$BEA_FILE" import "$WORK/statement.csv" \
  --csv date=Date,amount=Amount,payee=Payee \
  --account Assets:Checking --rules "$WORK/rules.toml" | awk '/^--- \//{exit} {print}' | head -n 7

echo "\$ bea import --apply"
bea --file "$BEA_FILE" import "$WORK/statement.csv" \
  --csv date=Date,amount=Amount,payee=Payee \
  --account Assets:Checking --rules "$WORK/rules.toml" --apply | tail -n 1

echo "\$ bea check"
bea --file "$BEA_FILE" check

echo "\$ bea balance Assets:Checking"
BALANCE=$(bea --file "$BEA_FILE" balance Assets:Checking)
printf '%s\n' "$BALANCE" | grep -E 'Checking|Assets'

echo "\$ bea report income-statement -t 2026-09"
REPORT=$(bea --file "$BEA_FILE" report income-statement -t 2026-09)
printf '%s\n' "$REPORT" | grep -E 'Net Profit|Consulting|Dining|Software'

case "$BALANCE" in
  *"2,958.50 USD"*) echo "checking: 2958.50 USD (expected)" ;;
  *) echo "UNEXPECTED checking total:"; printf '%s\n' "$BALANCE"; exit 1 ;;
esac
case "$REPORT" in
  *"1,958.50 USD"*) echo "profit: 1958.50 USD (expected)" ;;
  *) echo "UNEXPECTED profit total"; exit 1 ;;
esac

echo "REPLAY OK: preview 3/0, applied 3, check clean, 2958.50 / 1958.50 USD."
