#!/usr/bin/env bash
# BlackRoad OS — Autonomous Git Sync Agent
set -euo pipefail
ORG="blackboxprogramming"
SYNC_DIR="$HOME/blackroad-sync"
LOG="$HOME/.blackroad-autonomy/git-sync.log"
HOSTNAME=$(hostname)
NODE_NAME="${BLACKROAD_NODE_NAME:-$HOSTNAME}"
mkdir -p "$SYNC_DIR" "$(dirname "$LOG")"
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$NODE_NAME] $*" >> "$LOG"; }
sync_repo() {
  local repo="$1" dir="$SYNC_DIR/$repo"
  if [ ! -d "$dir" ]; then
    git clone --depth 1 "git@github.com:${ORG}/${repo}.git" "$dir" 2>/dev/null && log "CLONED $repo" || log "CLONE_FAIL $repo"
    return
  fi
  cd "$dir"
  git fetch origin 2>/dev/null || { log "FETCH_FAIL $repo"; return; }
  local LOCAL REMOTE BRANCH
  BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo main)
  LOCAL=$(git rev-parse HEAD 2>/dev/null)
  REMOTE=$(git rev-parse "origin/${BRANCH}" 2>/dev/null || echo "")
  if [ "$LOCAL" != "$REMOTE" ] && [ -n "$REMOTE" ]; then
    git pull --ff-only origin "$BRANCH" 2>/dev/null && log "PULLED $repo" || log "PULL_CONFLICT $repo"
  fi
  local AHEAD
  AHEAD=$(git rev-list --count "origin/${BRANCH}..HEAD" 2>/dev/null || echo "0")
  if [ "$AHEAD" -gt 0 ]; then
    git push origin "$BRANCH" 2>/dev/null && log "PUSHED $repo ($AHEAD commits)" || log "PUSH_FAIL $repo"
  fi
  if [ -f ".blackroad-auto-commit" ]; then
    if ! git diff --quiet 2>/dev/null || ! git diff --cached --quiet 2>/dev/null; then
      git add -A
      git commit -m "auto: sync from $NODE_NAME [$(date '+%Y-%m-%d %H:%M')]" 2>/dev/null
      git push origin "$BRANCH" 2>/dev/null && log "AUTO_COMMITTED $repo" || log "AUTO_COMMIT_FAIL $repo"
    fi
  fi
}
log "=== Git sync started ==="
ACTION="${1:-sync}"
case "$ACTION" in
  sync) for dir in "$SYNC_DIR"/*/; do [ -d "$dir/.git" ] || continue; sync_repo "$(basename "$dir")"; done ;;
  clone-all) for repo in $(gh repo list "$ORG" --limit 200 --json name --jq '.[].name' 2>/dev/null); do [ -d "$SYNC_DIR/$repo" ] && continue; sync_repo "$repo"; done ;;
  clone) shift; for repo in "$@"; do sync_repo "$repo"; done ;;
  push) for dir in "$SYNC_DIR"/*/; do [ -d "$dir/.git" ] || continue; cd "$dir"; BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo main); AHEAD=$(git rev-list --count "origin/${BRANCH}..HEAD" 2>/dev/null || echo "0"); [ "$AHEAD" -gt 0 ] && git push origin "$BRANCH" 2>/dev/null && log "PUSHED $(basename "$dir") ($AHEAD)" || true; done ;;
  status) echo "Sync: $SYNC_DIR"; for dir in "$SYNC_DIR"/*/; do [ -d "$dir/.git" ] || continue; cd "$dir"; BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "?"); DIRTY=$(git status --porcelain 2>/dev/null | wc -l); printf "  %-30s %s  dirty:%d\n" "$(basename "$dir")" "$BRANCH" "$DIRTY"; done ;;
esac
log "=== Git sync complete ==="
