#!/bin/bash
# BlackRoad Monorepo Sync — keeps the monorepo current with all sources
# Usage: ./sync.sh [push]
# Run without args to sync locally, with "push" to also push to Gitea

set -e

MONO=~/blackroad-monorepo
PINK='\033[38;5;205m'
GREEN='\033[38;5;82m'
BLUE='\033[38;5;69m'
RESET='\033[0m'

echo -e "${PINK}🛣️  BlackRoad Monorepo Sync${RESET}"
echo ""

# Sync bin/ and scripts/ from ~/local
echo -e "${BLUE}Syncing bin/...${RESET}"
rsync -a --delete --exclude='rclone' --exclude='cloudflared' --exclude='nsc' \
  ~/local/bin/ "$MONO/bin/"

echo -e "${BLUE}Syncing scripts/...${RESET}"
rsync -a --delete ~/local/scripts/ "$MONO/scripts/"

echo -e "${BLUE}Syncing fleet/...${RESET}"
rsync -a --delete ~/local/fleet/ "$MONO/fleet/"

echo -e "${BLUE}Syncing roadc/...${RESET}"
rsync -a --delete ~/local/roadc/ "$MONO/roadc/"

echo -e "${BLUE}Syncing roadnet/...${RESET}"
rsync -a --delete ~/local/roadnet/ "$MONO/roadnet/"

echo -e "${BLUE}Syncing config/...${RESET}"
rsync -a --delete ~/local/config/ "$MONO/config/"

echo -e "${BLUE}Syncing dotfiles/...${RESET}"
rsync -a --delete ~/local/dotfiles/ "$MONO/dotfiles/"

echo -e "${BLUE}Syncing memory/...${RESET}"
rsync -a --delete ~/local/memory/ "$MONO/memory/"

# Sync worker sources
echo -e "${BLUE}Syncing workers/...${RESET}"
mkdir -p "$MONO/workers"
for worker_dir in roadcode-squad squad-webhook tollbooth road-search stats-blackroad blackroad-stripe; do
  src=~/"$worker_dir"
  if [ -d "$src/src" ]; then
    rsync -a "$src/src/" "$MONO/workers/${worker_dir}-src/"
    [ -f "$src/wrangler.toml" ] && cp "$src/wrangler.toml" "$MONO/workers/${worker_dir}.toml"
  elif [ -f "$src/collect.sh" ]; then
    cp "$src/collect.sh" "$MONO/workers/stats-collect.sh"
  fi
done

# Sync operator memory scripts
echo -e "${BLUE}Syncing operator/...${RESET}"
mkdir -p "$MONO/operator"
rsync -a ~/blackroad-operator/scripts/memory/ "$MONO/operator/memory/"

# Sync docs
if [ -d ~/docs-blackroad-io ]; then
  echo -e "${BLUE}Syncing docs/...${RESET}"
  rsync -a --exclude='.git' ~/docs-blackroad-io/ "$MONO/docs/"
fi

# Commit if there are changes
cd "$MONO"
changes=$(git status --porcelain | wc -l | tr -d ' ')
if [ "$changes" -gt 0 ]; then
  git add -A
  file_count=$(git diff --cached --stat | tail -1 | grep -oE '[0-9]+ file' | grep -oE '[0-9]+')
  git commit -m "sync: $(date +%Y-%m-%d\ %H:%M) — ${file_count:-0} files from Alexandria"
  echo -e "${GREEN}✅ Committed ${file_count:-0} changed files${RESET}"

  if [ "$1" = "push" ]; then
    echo -e "${BLUE}Pushing to Gitea...${RESET}"
    git -c http.extraHeader="Authorization: token $(cat ~/.blackroad-gitea-token 2>/dev/null || echo 'd5a02fc6a82ce1a71a30023804df3fd404401303')" \
      push gitea main 2>&1
    echo -e "${GREEN}✅ Pushed to git.blackroad.io${RESET}"
  fi
else
  echo -e "${GREEN}✅ Already up to date${RESET}"
fi

echo ""
echo -e "${PINK}BlackRoad OS — Pave Tomorrow.${RESET}"
