#!/bin/bash
# Dump the paper-trading DB (gzip) and force-push as a SINGLE commit to the data branch.
# 2026-07-10: plain-text dump hit GitHub's 100MB blob limit (snapshots growth);
# now gzip + parentless commit — backup is disaster recovery of latest state, not an archive.
# 2026-07-28: the full dump crossed the limit again even gzipped (188MB) and had been
# failing every 6h since 07-09 without anyone noticing. snapshots + clob_l2_events are
# 90% of the DB and are raw market feed, not derived state, so they stay on the box.
# The tables below are the irreplaceable part: trading record, experiment record,
# calibration inputs, and the bot_meta period boundaries needed to read any of it.
set -e
REPO=~/predit-backup
TABLES="bot_meta paper_orders paper_cycles settlements shadow_orders \
experiment_orders experiment_rearms calibration_observations station_bias \
station_lead_bias forecast_batches forecasts maker_sim_orders"
MAX_BYTES=$((90 * 1024 * 1024))

if [ ! -d "$REPO/.git" ]; then
  git clone -q git@github-predit:dylanwuzc/predit-bot.git "$REPO"
fi
cd "$REPO"
git switch -q data 2>/dev/null || git switch -q --orphan data
mkdir -p data
rm -f data/weatherbot.sql
sqlite3 ~/predit-bot/weatherbot.db ".dump $TABLES" | gzip -9 > data/weatherbot.sql.gz

# Fail here rather than against GitHub's blob limit, so a table outgrowing the budget
# shows up as a clear message instead of a rejected push nobody reads.
SIZE=$(stat -c %s data/weatherbot.sql.gz)
if [ "$SIZE" -gt "$MAX_BYTES" ]; then
  echo "backup aborted: data/weatherbot.sql.gz is $SIZE bytes, over the $MAX_BYTES guard" >&2
  echo "a backed-up table has outgrown the budget — trim it or drop it from TABLES" >&2
  exit 1
fi

cp ~/predit-bot/config.toml data/config.toml
git add -A
TREE=$(git write-tree)
COMMIT=$(git -c user.name=weatherbot -c user.email=bot@predit commit-tree "$TREE" -m "data backup $(date -u +%FT%TZ)")
git reset -q --soft "$COMMIT"
git push -qf origin data
echo "backup ok: $SIZE bytes"
