#!/bin/bash
# Hermes Sync Script - Push local memories and skills to Gitea with merge
set -e

SYNC_DIR="/root/hermes-sync-tmp"
HERMES_HOME="$HOME/.hermes"
cd "$SYNC_DIR"

echo "[$(date '+%H:%M:%S')] Starting bidirectional sync..."

# Stage local changes
cp "$HERMES_HOME/memories/MEMORY.md" memories/MEMORY.md 2>/dev/null || true
if [ -d "$HERMES_HOME/skills" ]; then
    mkdir -p memories
    rsync -a --delete "$HERMES_HOME/skills/" memories/ 2>/dev/null || true
fi
git add -A

# Check if there are local changes
HAS_LOCAL=false
if ! git diff --cached --quiet || ! git diff --quiet; then
    HAS_LOCAL=true
fi

# Fetch and merge remote
git fetch origin main

# Check if remote is ahead
if git rev-parse HEAD >/dev/null 2>&1 && \
   git rev-parse origin/main >/dev/null 2>&1 && \
   ! git merge-base --is-ancestor HEAD origin/main 2>/dev/null; then
    echo "[$(date '+%H:%M:%S')] Remote has new changes, merging..."
    
    if [ "$HAS_LOCAL" = true ]; then
        # Both changed: stash, merge, then rebase
        git stash push -m "local $(date)" 2>/dev/null || true
        if ! git merge origin/main --no-edit 2>/dev/null; then
            # Conflict: auto-resolve memories by keeping ours
            git checkout --ours memories/MEMORY.md 2>/dev/null || true
            git add -A
            git commit -m "Auto-resolve $(date)" 2>/dev/null || true
        fi
        if git stash list | grep -q "local "; then
            git stash pop 2>/dev/null || true
            git rebase origin/main 2>/dev/null || {
                git rebase --abort 2>/dev/null || true
                git merge origin/main --no-edit 2>/dev/null || true
            }
        fi
    else
        # Only remote changed
        git merge origin/main --no-edit 2>/dev/null || git merge --ff-only origin/main 2>/dev/null || git reset --hard origin/main
    fi
fi

# Commit and push local
if [ "$HAS_LOCAL" = true ]; then
    git commit -m "Sync $(date '+%Y-%m-%d %H:%M')" 2>/dev/null || true
    if ! git push origin main 2>&1; then
        echo "[$(date '+%H:%M:%S')] Push rejected, pulling and retrying..."
        git pull origin main --no-edit 2>/dev/null || true
        git push origin main 2>&1 || echo "[$(date '+%H:%M:%S')] Push failed"
    else
        echo "[$(date '+%H:%M:%S')] Push successful"
    fi
else
    echo "[$(date '+%H:%M:%S')] No local changes"
fi

echo "[$(date '+%H:%M:%S')] Sync complete"
