#!/usr/bin/env bash
# budget-guard.sh — Layer 06. The hard daily cap. The heartbeat calls this before every task;
# if today's spend has reached the wall, it exits non-zero and the loop refuses to start more.
# A number, not a judgment, ends the day — a prompt-injected task can't argue past it.
set -euo pipefail

CAP_USD=${CAP_USD:-15.00}
ledger="$(dirname "$0")/spend.jsonl"
today=$(date -u +%F)

spent=0
if [ -f "$ledger" ]; then
  spent=$(jq -r --arg d "$today" 'select(.ts | startswith($d)) | .usd' "$ledger" \
    | awk '{s += $1} END {print s + 0}')
fi

awk -v s="$spent" -v c="$CAP_USD" 'BEGIN {
  if (s >= c) { printf "HALT: $%.2f/$%.2f spent today\n", s, c; exit 1 }
  printf "ok: $%.2f/$%.2f spent today\n", s, c
}'
