#!/usr/bin/env bash
set -euo pipefail
# ─────────────────────────────────────────────────────────────
# fix-npmrc-all-repos.sh — Standardize .npmrc + pnpm-workspace.yaml
#                          across all ByteLyst repos
# ─────────────────────────────────────────────────────────────
#
# Problem: repos hardcode "gitea.bytelyst.com" in .npmrc, which
#          breaks on corp network (TLS-intercepting proxy).
#
# Solution:
#   1. Replace hardcoded Gitea URL with env-var-based URL
#      using $GITEA_NPM_HOST (set by switch-network.sh).
#   2. Add workspace link to ../learning_ai_common_plat/packages/*
#      so @bytelyst/* resolve locally (no registry needed).
#   3. Add link-workspace-packages + prefer-workspace-packages.
#
# Usage:
#   bash scripts/fix-npmrc-all-repos.sh          # dry run
#   bash scripts/fix-npmrc-all-repos.sh --apply   # actually write files
#
# ─────────────────────────────────────────────────────────────

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPOS_ROOT="$(cd "$SCRIPT_DIR/../../" && pwd)"

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

# All repos that use @bytelyst/* packages
REPOS=(
  learning_ai_clock
  learning_ai_common_plat
  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_voice_ai_agent
  learning_multimodal_memory_agents
)

# Minimal template for nested .npmrc (e.g. dashboard/.npmrc inside a repo)
NPMRC_NESTED_TEMPLATE='@bytelyst:registry=http://${GITEA_NPM_HOST:-localhost}:3300/api/packages/learning_ai_user/npm/
//localhost:3300/api/packages/learning_ai_user/npm/:_authToken=${GITEA_NPM_TOKEN}
strict-ssl=false'

NPMRC_TEMPLATE='@bytelyst:registry=http://${GITEA_NPM_HOST:-localhost}:3300/api/packages/learning_ai_user/npm/
//localhost:3300/api/packages/learning_ai_user/npm/:_authToken=${GITEA_NPM_TOKEN}
strict-ssl=false
link-workspace-packages=true
prefer-workspace-packages=true'

COMMON_PLAT_LINK="  - ../learning_ai_common_plat/packages/*"

fixed_npmrc=0
fixed_workspace=0
skipped=0

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

  # ── Fix .npmrc ───────────────────────────────────────────
  npmrc_file="$repo_path/.npmrc"
  if [ -f "$npmrc_file" ]; then
    if grep -q "gitea.bytelyst.com" "$npmrc_file"; then
      if $DRY_RUN; then
        echo "📝 $repo/.npmrc — would replace hardcoded gitea.bytelyst.com"
      else
        echo "$NPMRC_TEMPLATE" > "$npmrc_file"
        echo "✅ $repo/.npmrc — fixed"
      fi
      ((fixed_npmrc++))
    else
      echo "✓  $repo/.npmrc — already uses env var or localhost"
    fi
  else
    if $DRY_RUN; then
      echo "📝 $repo/.npmrc — would create"
    else
      echo "$NPMRC_TEMPLATE" > "$npmrc_file"
      echo "✅ $repo/.npmrc — created"
    fi
    ((fixed_npmrc++))
  fi

  # ── Fix pnpm-workspace.yaml ─────────────────────────────
  # (skip common-plat itself — it IS the workspace source)
  workspace_file="$repo_path/pnpm-workspace.yaml"
  if [ -f "$workspace_file" ] && [ "$repo" != "learning_ai_common_plat" ]; then
    if ! grep -q "learning_ai_common_plat" "$workspace_file"; then
      if $DRY_RUN; then
        echo "📝 $repo/pnpm-workspace.yaml — would add common-plat link"
      else
        echo "$COMMON_PLAT_LINK" >> "$workspace_file"
        echo "✅ $repo/pnpm-workspace.yaml — added common-plat link"
      fi
      ((fixed_workspace++))
    else
      echo "✓  $repo/pnpm-workspace.yaml — already has common-plat link"
    fi
  fi

  # ── Fix nested .npmrc files (e.g. dashboard/.npmrc) ────
  while IFS= read -r nested_npmrc; do
    if grep -q "gitea.bytelyst.com" "$nested_npmrc"; then
      rel_path="${nested_npmrc#$repo_path/}"
      if $DRY_RUN; then
        echo "📝 $repo/$rel_path — would replace hardcoded gitea.bytelyst.com"
      else
        echo -e "$NPMRC_NESTED_TEMPLATE" > "$nested_npmrc"
        echo "✅ $repo/$rel_path — fixed"
      fi
      ((fixed_npmrc++))
    fi
  done < <(find "$repo_path" -name ".npmrc" -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "$repo_path/.npmrc" 2>/dev/null)
done

echo ""
echo "─── Summary ───"
echo "npmrc:     $fixed_npmrc repos to fix"
echo "workspace: $fixed_workspace repos to fix"
echo "skipped:   $skipped repos not found"

if $DRY_RUN; then
  echo ""
  echo "This was a DRY RUN. Run with --apply to write changes:"
  echo "  bash scripts/fix-npmrc-all-repos.sh --apply"
fi
