#!/usr/bin/env bash
# hermes-config-sync — sync live ~/.hermes state into the hermes-config repo
# Usage: hermes-config-sync [commit message]
# If no message provided, generates one from changed files.

set -euo pipefail

HERMES_DIR="$HOME/.hermes"
REPO_DIR="$HOME/hermes-config"

if [ ! -d "$REPO_DIR/.git" ]; then
  echo "ERROR: $REPO_DIR is not a git repo"
  exit 1
fi

# ── Copy live files into repo ─────────────────────────────────────────
# Bin scripts
for f in "$HERMES_DIR"/bin/*; do
  [ -f "$f" ] && cp "$f" "$REPO_DIR/bin/"
done

# Memories
cp "$HERMES_DIR/memories/MEMORY.md" "$REPO_DIR/memories/" 2>/dev/null || true
cp "$HERMES_DIR/memories/USER.md" "$REPO_DIR/memories/" 2>/dev/null || true

# Config (not secrets)
cp "$HERMES_DIR/config.yaml" "$REPO_DIR/" 2>/dev/null || true
cp "$HERMES_DIR/SOUL.md" "$REPO_DIR/" 2>/dev/null || true
cp "$HERMES_DIR/channel_directory.json" "$REPO_DIR/" 2>/dev/null || true

# Cron
cp "$HERMES_DIR/cron/jobs.json" "$REPO_DIR/cron/" 2>/dev/null || true

# Skills (full recursive sync, respecting .gitignore)
rsync -a --delete \
  --exclude='.hub/' \
  --exclude='.bundled_manifest' \
  "$HERMES_DIR/skills/" "$REPO_DIR/skills/"

# ── Check for changes ────────────────────────────────────────────────
cd "$REPO_DIR"
git add -A

if git diff --cached --quiet; then
  echo "Nothing to commit — already in sync."
  exit 0
fi

# ── Commit ───────────────────────────────────────────────────────────
CHANGED=$(git diff --cached --name-only | wc -l | tr -d ' ')
if [ $# -gt 0 ]; then
  MSG="$*"
else
  FILES=$(git diff --cached --name-only | head -5 | tr '\n' ', ' | sed 's/,$//')
  MSG="sync: ${CHANGED} files updated (${FILES})"
fi

git commit -m "$MSG"

# ── Push ─────────────────────────────────────────────────────────────
git push origin main 2>&1 | cat
echo "✓ Synced ${CHANGED} files to hermes/hermes-config"
