#!/usr/bin/env bash
# ============================================================
# HalaVoice — full backup (code + config + database)
#
# Produces backups/full-backup-<TS>/ containing:
#   agentlabs-db.sql.gz    full pg_dump (gzip)
#   code-config.tar.gz     source + config (heavy/sensitive dirs excluded)
#   .env                   live secrets (dir is chmod 700)
#   ecosystem.config.cjs   PM2 config
#   nginx-*.conf           nginx site config (if readable)
#   pm2-processes.json     `pm2 jlist` snapshot
#   MANIFEST.txt           versions + contents
#   SHA256SUMS.txt         integrity checksums
#
# Then (unless --no-git) commits + pushes source to GitHub.
# Keeps the newest $KEEP local backups and prunes older ones.
#
# Usage: ops/backup.sh [--no-git] [--keep N]
# ============================================================
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"

KEEP=7
DO_GIT=1
while [ $# -gt 0 ]; do
  case "$1" in
    --no-git) DO_GIT=0 ;;
    --keep)   KEEP="$2"; shift ;;
    *) die "unknown arg: $1" ;;
  esac
  shift
done

need pg_dump; need gzip; need tar
TS="$(date -u +%Y%m%d-%H%M%S)"
DEST="$BACKUP_ROOT/full-backup-$TS"
mkdir -p "$DEST"
chmod 700 "$DEST"

log "Backing up to $DEST"

# --- 1) database -------------------------------------------------------
log "Dumping database…"
pg_dump "$(db_url)" | gzip -9 > "$DEST/agentlabs-db.sql.gz"
DB_TABLES=$(gzip -dc "$DEST/agentlabs-db.sql.gz" | grep -c "^CREATE TABLE" || true)
ok "DB dump: $(du -h "$DEST/agentlabs-db.sql.gz" | cut -f1), $DB_TABLES tables"

# --- 2) code + config --------------------------------------------------
log "Archiving code + config…"
tar -C "$REPO_ROOT" \
  --exclude='./node_modules' --exclude='*/node_modules' \
  --exclude='./dist' --exclude='./build' --exclude='./cache' \
  --exclude='./backups' --exclude='./.git' \
  --exclude='./models' --exclude='./541' --exclude='./code' \
  --exclude='./data' --exclude='./exports' --exclude='./kyc' \
  --exclude='./salla-app' --exclude='./whatsapp-server' \
  --exclude='./hala5.0Backup-*' --exclude='*.dump' \
  --exclude='./logs' --exclude='*.log' \
  --exclude='./whatsapp-server-v2/sessions' \
  --exclude='./mobile/android' --exclude='./mobile/ios' \
  -czf "$DEST/code-config.tar.gz" . 2>/dev/null || true
ok "Code archive: $(du -h "$DEST/code-config.tar.gz" | cut -f1)"

# --- 3) loose config snapshots ----------------------------------------
cp "$REPO_ROOT/.env" "$DEST/.env" 2>/dev/null || warn ".env not copied"
cp "$REPO_ROOT/ecosystem.config.cjs" "$DEST/" 2>/dev/null || true
NGINX_CONF="/etc/nginx/conf.d/users/ashraffarid2010/halavoice.store.happy-times.me/agentlabs-api.conf"
[ -r "$NGINX_CONF" ] && cp "$NGINX_CONF" "$DEST/nginx-agentlabs-api.conf" 2>/dev/null || true
command -v pm2 >/dev/null 2>&1 && pm2 jlist > "$DEST/pm2-processes.json" 2>/dev/null || true

# --- 4) manifest + checksums ------------------------------------------
{
  echo "HalaVoice full backup"
  echo "created_utc: $(date -u +%FT%TZ)"
  echo "host: $(hostname)"
  echo "node: $(node -v 2>/dev/null || echo n/a)"
  echo "npm: $(npm -v 2>/dev/null || echo n/a)"
  echo "postgres: $(psql --version 2>/dev/null | awk '{print $3}' || echo n/a)"
  echo "app_version: $(node -e "console.log(require('$REPO_ROOT/package.json').version)" 2>/dev/null || echo n/a)"
  echo "db_tables: $DB_TABLES"
  echo "git_commit: $(git -C "$REPO_ROOT" rev-parse HEAD 2>/dev/null || echo 'no-git')"
} > "$DEST/MANIFEST.txt"
( cd "$DEST" && sha256sum ./* > SHA256SUMS.txt 2>/dev/null || true )
ok "Manifest + checksums written"

# --- 5) prune old local backups ---------------------------------------
log "Pruning old backups (keeping newest $KEEP)…"
mapfile -t OLD < <(ls -1dt "$BACKUP_ROOT"/full-backup-* 2>/dev/null | tail -n +$((KEEP+1)))
for d in "${OLD[@]:-}"; do [ -n "$d" ] && rm -rf "$d" && log "  removed $(basename "$d")"; done

# --- 6) push source to GitHub -----------------------------------------
if [ "$DO_GIT" = "1" ] && [ -d "$REPO_ROOT/.git" ]; then
  log "Syncing source to GitHub…"
  "$OPS_DIR/git-sync.sh" || warn "git sync failed (backup itself is fine)"
fi

ok "Backup complete: $DEST"
