#!/usr/bin/env bash
# Re-pull the shop data from the M1 Ultra MariaDB clone into RecordGod (ultra + VPS).
# Run whenever you've refreshed the ultra clone from the live site.
#
# Scope: the Discogs-style custom tables only (inventory / virtual store / sales / crates) +
# disc_cache. WooCommerce never leaves WP — it's remote-managed via the Woo API.
#
# ponytail: this CLEAN-REBUILDS the migrated tables (correct while live WP/MariaDB is still
# source-of-truth). The vault (app_secret) is excluded so dash credentials survive a refresh.
# Once you start entering stock via the RecordGod dash (staged intake rows in `inventory`),
# switch the migrate steps to non-destructive UPSERT so a refresh stops clobbering them.
# See RECORDGOD_PLAN.md §6 (live owns sale-state, local owns intake).
set -e
cd "$(dirname "$0")"
VPS=${VPS:-root@100.94.195.115}
PY=${PY:-./.venv/bin/python}
PGDUMP=${PGDUMP:-/opt/homebrew/opt/postgresql@16/bin/pg_dump}

echo "[1/5] inventory + sales + crate   (MariaDB → recordgod)"; $PY migrate.py --truncate
echo "[2/5] virtual store tables        (MariaDB → recordgod)"; $PY migrate_virtual.py
echo "[3/5] disc_cache                  (discogs_full → recordgod)"; $PY build_disc_cache.py
echo "[4/5] push recordgod → VPS (vault preserved)"
$PGDUMP --no-owner --no-privileges --clean --if-exists --exclude-table='app_secret' recordgod \
  | ssh "$VPS" 'docker exec -i recordgod-db psql -U recordgod -d recordgod -q' 2>&1 | grep -i error || true
# Woo online customers go straight to the VPS AFTER the --clean push (which only carries POS customers).
# Non-destructive upsert: links/refreshes/inserts, never clobbers POS-entered rows.
echo "[5/5] Woo online customers → recordgod CRM (non-destructive)"
$PY customer_woo_sync.py | ssh "$VPS" 'docker exec -i recordgod-db psql -U recordgod -d recordgod -q' 2>&1 | grep -i error || true
echo "done — recordgod refreshed on ultra + VPS"
