#!/usr/bin/env bash
# sync-npmrc.sh — Copy canonical .npmrc to all ByteLyst product repos.
#
# Single source of truth: scripts/npmrc.template
# Run from learning_ai_common_plat root:
#   bash scripts/sync-npmrc.sh           # apply to all repos
#   bash scripts/sync-npmrc.sh --dry-run # show what would change
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
TEMPLATE="$SCRIPT_DIR/npmrc.template"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PARENT_DIR="$(dirname "$REPO_ROOT")"

if [ ! -f "$TEMPLATE" ]; then
  echo "❌ Template not found: $TEMPLATE" >&2
  exit 1
fi

DRY_RUN=false
[ "${1:-}" = "--dry-run" ] && DRY_RUN=true

# All product repos that need .npmrc (sibling directories)
REPOS=(
  learning_voice_ai_agent
  learning_multimodal_memory_agents
  learning_ai_clock
  learning_ai_efforise
  learning_ai_fastgap
  learning_ai_flowmonk
  learning_ai_jarvis_jr
  learning_ai_local_llms
  learning_ai_local_memory_gpt
  learning_ai_notes
  learning_ai_peakpulse
  learning_ai_trails
  learning_ai_talk2obsidian
)

changed=0
skipped=0
up_to_date=0

shopt -s nullglob

for repo in "${REPOS[@]}"; do
  target="$PARENT_DIR/$repo/.npmrc"
  
  if [ ! -d "$PARENT_DIR/$repo" ]; then
    echo "⏭  $repo — not found, skipping"
    ((skipped++)) || true
    continue
  fi

  if [ -f "$target" ] && diff -q "$TEMPLATE" "$target" >/dev/null 2>&1; then
    echo "✅ $repo — up to date"
    ((up_to_date++)) || true
    continue
  fi

  if $DRY_RUN; then
    echo "🔄 $repo — would update"
    if [ -f "$target" ]; then
      diff --color=auto "$target" "$TEMPLATE" || true
    fi
  else
    cp "$TEMPLATE" "$target"
    echo "🔄 $repo — updated"
  fi
  ((changed++)) || true
done

echo ""
echo "Summary: $changed changed, $up_to_date up-to-date, $skipped skipped"
$DRY_RUN && echo "(dry run — no files modified)"
