#!/usr/bin/env bash
# check-npmrc-drift.sh — Detect .npmrc drift across ByteLyst repos.
#
# Returns exit code 1 if any repo's .npmrc differs from the canonical template.
# Use in CI or as a periodic audit:
#   bash scripts/check-npmrc-drift.sh
#
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

REPOS=(
  learning_ai_common_plat
  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
)

drifted=0
missing=0
ok=0

for repo in "${REPOS[@]}"; do
  target="$PARENT_DIR/$repo/.npmrc"

  if [ ! -d "$PARENT_DIR/$repo" ]; then
    continue
  fi

  if [ ! -f "$target" ]; then
    echo "⚠️  $repo — .npmrc missing"
    ((missing++)) || true
    continue
  fi

  if diff -q "$TEMPLATE" "$target" >/dev/null 2>&1; then
    ((ok++)) || true
  else
    echo "❌ $repo — .npmrc drifted from template"
    diff --color=auto "$TEMPLATE" "$target" 2>/dev/null | head -10 || true
    echo ""
    ((drifted++)) || true
  fi
done

echo "────────────────────────────────"
echo "✅ $ok repos match template"
[ "$missing" -gt 0 ] && echo "⚠️  $missing repos missing .npmrc"
[ "$drifted" -gt 0 ] && echo "❌ $drifted repos drifted"
echo ""

if [ "$drifted" -gt 0 ] || [ "$missing" -gt 0 ]; then
  echo "Fix: bash scripts/sync-npmrc.sh"
  exit 1
fi

echo "All repos in sync ✅"
