#!/usr/bin/env bash
set -euo pipefail

# ─────────────────────────────────────────────────────────────
# Hardening: Add publishConfig to all @bytelyst/* packages
# to prevent accidental publish to npmjs.org or JFrog
# ─────────────────────────────────────────────────────────────

REGISTRY="https://gitea.bytelyst.com/api/packages/learning_ai_user/npm/"
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
PACKAGES_DIR="$REPO_ROOT/packages"

# Skip native SDKs (not published to npm)
SKIP_DIRS="swift-platform-sdk swift-diagnostics kotlin-platform-sdk"

fixed=0
skipped=0
already=0

for pkg_json in "$PACKAGES_DIR"/*/package.json; do
  dir_name=$(basename "$(dirname "$pkg_json")")

  # Skip native SDKs
  if echo "$SKIP_DIRS" | grep -qw "$dir_name"; then
    echo "SKIP (native): $dir_name"
    ((skipped++))
    continue
  fi

  # Check if publishConfig already exists with correct registry
  if node -e "
    const p = JSON.parse(require('fs').readFileSync('$pkg_json', 'utf8'));
    process.exit(p.publishConfig && p.publishConfig.registry === '$REGISTRY' ? 0 : 1);
  " 2>/dev/null; then
    echo "OK: $dir_name"
    ((already++))
    continue
  fi

  # Add publishConfig
  node -e "
    const fs = require('fs');
    const pkg = JSON.parse(fs.readFileSync('$pkg_json', 'utf8'));
    pkg.publishConfig = { registry: '$REGISTRY' };
    fs.writeFileSync('$pkg_json', JSON.stringify(pkg, null, 2) + '\n');
  "
  echo "FIXED: $dir_name"
  ((fixed++))
done

# Also fix @actiontrail/sdk
SDK_FILE="/Users/sd9235/code/mygh/learning_ai_trails/sdk/package.json"
if [ -f "$SDK_FILE" ]; then
  if ! node -e "
    const p = JSON.parse(require('fs').readFileSync('$SDK_FILE', 'utf8'));
    process.exit(p.publishConfig && p.publishConfig.registry === '$REGISTRY' ? 0 : 1);
  " 2>/dev/null; then
    node -e "
      const fs = require('fs');
      const pkg = JSON.parse(fs.readFileSync('$SDK_FILE', 'utf8'));
      pkg.publishConfig = { registry: '$REGISTRY' };
      fs.writeFileSync('$SDK_FILE', JSON.stringify(pkg, null, 2) + '\n');
    "
    echo "FIXED: @actiontrail/sdk"
    ((fixed++))
  else
    echo "OK: @actiontrail/sdk"
  fi
fi

echo ""
echo "✅ Done: $fixed fixed, $already already ok, $skipped skipped (native)"
