#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
OUT_DIR="$ROOT_DIR/docs/backups"
RETENTION="${DOCS_BACKUP_RETENTION:-20}"
DRY_RUN=1
APPLY=0

usage() {
  cat <<'USAGE'
Usage:
  bash scripts/docs/docs_backup.sh [--dry-run] [--apply] [--retention N]

Behavior:
  - default mode is --dry-run
  - --apply creates docs backup archive and rotates old backups
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run)
      DRY_RUN=1
      APPLY=0
      shift
      ;;
    --apply)
      APPLY=1
      DRY_RUN=0
      shift
      ;;
    --retention)
      RETENTION="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown arg: $1" >&2
      usage
      exit 2
      ;;
  esac
done

STAMP="$(date +%Y%m%d-%H%M%S)"
ARCHIVE="$OUT_DIR/docs_backup_${STAMP}.tar.gz"
LATEST_REF="$OUT_DIR/LATEST.txt"

backup_targets=(
  PROJECT-MASTER-INDEX.md
  NODA1-SAFE-DEPLOY.md
  docs/SESSION_STARTER.md
  docs/runbooks
  docs/standards
  docs/consolidation/README.md
  docs/consolidation/SOURCES.md
  docs/consolidation/docs_registry_curated.csv
  docs/consolidation/INTEGRATIONS_STATUS_LATEST.md
  docs/consolidation/jupyter/JUPYTER_SYNC_LATEST.md
  docs/consolidation/jupyter/notebooks_index_latest.csv
  docs/consolidation/pieces/PIECES_SYNC_LATEST.md
  docs/consolidation/pieces/pieces_index_latest.csv
)

existing=()
for t in "${backup_targets[@]}"; do
  [[ -e "$ROOT_DIR/$t" ]] && existing+=("$t")
done

if [[ "$DRY_RUN" -eq 1 ]]; then
  echo "[dry-run] backup archive: $ARCHIVE"
  echo "[dry-run] retention: $RETENTION"
  echo "[dry-run] targets:"
  printf '  - %s\n' "${existing[@]}"
  exit 0
fi

mkdir -p "$OUT_DIR"

tar -czf "$ARCHIVE" -C "$ROOT_DIR" "${existing[@]}"
printf '%s\n' "$ARCHIVE" > "$LATEST_REF"

mapfile -t backups < <(ls -1t "$OUT_DIR"/docs_backup_*.tar.gz 2>/dev/null || true)
if [[ "${#backups[@]}" -gt "$RETENTION" ]]; then
  for old in "${backups[@]:$RETENTION}"; do
    rm -f "$old"
  done
fi

echo "Wrote: $ARCHIVE"
echo "Updated: $LATEST_REF"
