#!/usr/bin/env bash
# Backs up Teletraan databases, config, and agent CLAUDE.md files.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="${HOME}/.teletraan-backups"
STAGING_DIR="${BACKUP_DIR}/staging_${TIMESTAMP}"
ARCHIVE="${BACKUP_DIR}/teletraan_backup_${TIMESTAMP}.tar.gz"

mkdir -p "$STAGING_DIR"

echo ""
echo "Teletraan Backup"
echo "─────────────────────────────────"
echo "Timestamp : ${TIMESTAMP}"
echo "Staging   : ${STAGING_DIR}"
echo "Archive   : ${ARCHIVE}"
echo ""

# ── Resolve install path from system.json ───────────────────────────────────

INSTALL_PATH=""
SYSTEM_JSON="${REPO_ROOT}/config/system.json"

if [ -f "$SYSTEM_JSON" ] && command -v node &>/dev/null; then
  INSTALL_PATH=$(node -e "
    const c = JSON.parse(require('fs').readFileSync('${SYSTEM_JSON}', 'utf8'));
    process.stdout.write(c.installPath || '');
  " 2>/dev/null || true)
fi

if [ -z "$INSTALL_PATH" ]; then
  INSTALL_PATH="${HOME}/teletraan"
fi

echo "Install path: ${INSTALL_PATH}"
echo ""

# ── SQLite databases ─────────────────────────────────────────────────────────

echo "[1/4] Backing up SQLite databases..."
DB_STAGING="${STAGING_DIR}/databases"
mkdir -p "$DB_STAGING"

DB_COUNT=0
while IFS= read -r -d '' db_file; do
  rel_path="${db_file#"${INSTALL_PATH}/"}"
  dest="${DB_STAGING}/${rel_path//\//_}"
  cp "$db_file" "$dest"
  echo "      + ${rel_path}"
  DB_COUNT=$((DB_COUNT + 1))
done < <(find "${INSTALL_PATH}" -name "*.db" -not -path "*/node_modules/*" -print0 2>/dev/null || true)

if [ "$DB_COUNT" -eq 0 ]; then
  echo "      (no databases found at ${INSTALL_PATH})"
fi

# ── Config files ─────────────────────────────────────────────────────────────

echo ""
echo "[2/4] Backing up config files..."
CONFIG_STAGING="${STAGING_DIR}/config"
mkdir -p "$CONFIG_STAGING"

CONFIG_COUNT=0

copy_if_exists() {
  local src="$1"
  local dest_name="$2"
  if [ -f "$src" ]; then
    cp "$src" "${CONFIG_STAGING}/${dest_name}"
    echo "      + ${dest_name}"
    CONFIG_COUNT=$((CONFIG_COUNT + 1))
  fi
}

copy_if_exists "${REPO_ROOT}/config/system.json"   "system.json"
copy_if_exists "${REPO_ROOT}/config/manifest.json" "manifest.json"

# Module data configs
while IFS= read -r -d '' config_file; do
  rel_path="${config_file#"${INSTALL_PATH}/services/"}"
  safe_name="${rel_path//\//_}"
  cp "$config_file" "${CONFIG_STAGING}/${safe_name}"
  echo "      + services/${rel_path}"
  CONFIG_COUNT=$((CONFIG_COUNT + 1))
done < <(find "${INSTALL_PATH}/services" -name "config.json" -not -path "*/node_modules/*" -print0 2>/dev/null || true)

# PM2 ecosystem config
copy_if_exists "${INSTALL_PATH}/ecosystem.config.js" "ecosystem.config.js"

if [ "$CONFIG_COUNT" -eq 0 ]; then
  echo "      (no config files found)"
fi

# ── Agent CLAUDE.md files ────────────────────────────────────────────────────

echo ""
echo "[3/4] Backing up agent CLAUDE.md files..."
AGENTS_STAGING="${STAGING_DIR}/agents"
mkdir -p "$AGENTS_STAGING"

AGENT_COUNT=0
while IFS= read -r -d '' claude_md; do
  rel_path="${claude_md#"${INSTALL_PATH}/agents/"}"
  safe_name="${rel_path//\//_}"
  cp "$claude_md" "${AGENTS_STAGING}/${safe_name}"
  echo "      + agents/${rel_path}"
  AGENT_COUNT=$((AGENT_COUNT + 1))
done < <(find "${INSTALL_PATH}/agents" -name "CLAUDE.md" -print0 2>/dev/null || true)

# Also back up repo-level agent templates
while IFS= read -r -d '' claude_md; do
  rel_path="${claude_md#"${REPO_ROOT}/"}"
  safe_name="repo_${rel_path//\//_}"
  cp "$claude_md" "${AGENTS_STAGING}/${safe_name}"
  echo "      + ${rel_path}"
  AGENT_COUNT=$((AGENT_COUNT + 1))
done < <(find "${REPO_ROOT}/core/agents" -name "CLAUDE.md*" -print0 2>/dev/null || true)

if [ "$AGENT_COUNT" -eq 0 ]; then
  echo "      (no CLAUDE.md files found)"
fi

# ── Create archive ────────────────────────────────────────────────────────────

echo ""
echo "[4/4] Creating archive..."
tar -czf "$ARCHIVE" -C "$STAGING_DIR" .
rm -rf "$STAGING_DIR"

ARCHIVE_SIZE=$(du -sh "$ARCHIVE" | cut -f1)
echo "      Archive: ${ARCHIVE} (${ARCHIVE_SIZE})"

# ── Summary ───────────────────────────────────────────────────────────────────

echo ""
echo "─────────────────────────────────"
echo "Backup complete."
echo "  Databases : ${DB_COUNT} file(s)"
echo "  Configs   : ${CONFIG_COUNT} file(s)"
echo "  Agents    : ${AGENT_COUNT} file(s)"
echo "  Archive   : ${ARCHIVE}"
echo ""

# Prune backups older than 30 days
OLD_BACKUPS=$(find "$BACKUP_DIR" -name "teletraan_backup_*.tar.gz" -mtime +30 2>/dev/null || true)
if [ -n "$OLD_BACKUPS" ]; then
  echo "Pruning backups older than 30 days..."
  echo "$OLD_BACKUPS" | xargs rm -f
  echo "Done."
  echo ""
fi
