#!/bin/zsh
# sync-workflows.sh — Sync common repo_* workflows from common-plat to all repos
# Usage: ./sync-workflows.sh [--dry-run]

set -eo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPOS_ROOT="/Users/sd9235/code/mygh"
COMMON_PLAT="$REPOS_ROOT/learning_ai_common_plat"
REPOS_TXT="$COMMON_PLAT/.windsurf/workflows/repos.txt"

if [ ! -f "$REPOS_TXT" ]; then
  echo "❌ Canonical repos.txt not found: $REPOS_TXT"
  exit 1
fi

REPOS=()
while IFS= read -r line; do
  [[ "$line" =~ ^[[:space:]]*# ]] && continue
  [[ -z "${line// }" ]] && continue
  [[ "$line" == "learning_ai_common_plat" ]] && continue
  REPOS+=("$line")
done < "$REPOS_TXT"

WORKFLOWS_TO_SYNC=(
  "repo_backup-main-branch.md"
  "repo_backup-and-push.md"
  "repo_sync-repos.md"
  "repo_commit-workspace.md"
  "repo_push-repos.md"
  "repo_update-agent-docs.md"
  "refresh-chat-history.md"
)

DRY_RUN=false
if [ "${1:-}" = "--dry-run" ]; then
  DRY_RUN=true
fi

sync_count=0
skip_count=0

for repo in "${REPOS[@]}"; do
  repo_path="$REPOS_ROOT/$repo"
  
  if [ ! -d "$repo_path" ]; then
    echo "⚠ Skipping $repo (not found)"
    continue
  fi
  
  # Create .windsurf/workflows if missing
  wf_dir="$repo_path/.windsurf/workflows"
  if [ ! -d "$wf_dir" ]; then
    if [ "$DRY_RUN" = true ]; then
      echo "[dry-run] mkdir -p $wf_dir"
    else
      mkdir -p "$wf_dir"
      echo "✓ Created $wf_dir"
    fi
  fi
  
  for wf in "${WORKFLOWS_TO_SYNC[@]}"; do
    src="$COMMON_PLAT/.windsurf/workflows/$wf"
    dest="$wf_dir/$wf"
    
    if [ ! -f "$src" ]; then
      echo "⚠ Source not found: $src"
      continue
    fi
    
    if [ "$DRY_RUN" = true ]; then
      if [ -f "$dest" ]; then
        # Compare files
        if diff -q "$src" "$dest" > /dev/null 2>&1; then
          echo "[dry-run] $repo/$wf (identical, skip)"
          skip_count=$((skip_count + 1))
        else
          echo "[dry-run] $repo/$wf (would update)"
          sync_count=$((sync_count + 1))
        fi
      else
        echo "[dry-run] $repo/$wf (would copy)"
        sync_count=$((sync_count + 1))
      fi
    else
      if [ -f "$dest" ]; then
        if diff -q "$src" "$dest" > /dev/null 2>&1; then
          echo "  = $repo/$wf (identical)"
          skip_count=$((skip_count + 1))
        else
          cp "$src" "$dest"
          echo "  ✓ $repo/$wf (updated)"
          sync_count=$((sync_count + 1))
        fi
      else
        cp "$src" "$dest"
        echo "  ✓ $repo/$wf (new)"
        sync_count=$((sync_count + 1))
      fi
    fi
  done
done

echo ""
echo "=== Sync complete ==="
echo "  Updated: $sync_count"
echo "  Skipped (identical): $skip_count"
echo ""

if [ "$sync_count" -eq 0 ] && [ "$skip_count" -gt 0 ]; then
  echo "✓ All workflows are synchronized across all repos."
  echo "  No changes needed — everything is up to date."
elif [ "$sync_count" -gt 0 ]; then
  echo "✓ Synced $sync_count workflow(s) to repos."
  echo "  Run again to verify all repos are identical."
else
  echo "✓ Nothing to sync."
fi
