#!/usr/bin/env bash
# sweep-publish.sh — Bump versions and publish all OC packages
#
# Usage:
#   ./scripts/sweep-publish.sh          # Dry run (show what would happen)
#   ./scripts/sweep-publish.sh --pypi   # Build + publish to PyPI
#   ./scripts/sweep-publish.sh --clawhub # Publish to ClawHub
#   ./scripts/sweep-publish.sh --all    # Both PyPI + ClawHub
#
# Prerequisites:
#   - PyPI API token configured (~/.pypirc or TWINE_PASSWORD)
#   - ClawHub logged in (npx clawhub login)
#   - All repos cloned in the same parent directory
#
# IMPORTANT: Run the version bump script FIRST to update versions in all 3 places
# (pyproject.toml, __init__.py, clawhub/metadata.json) before publishing.

set -uo pipefail
# Note: NOT using -e so the script continues if one package fails

BASE_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
MODE="${1:-dry}"

# ── Package registry (order matters — dependencies first) ────
# Format: repo_dir|pypi_name|clawhub_slug|new_version
PACKAGES=(
  "nostrkey.app.OC-python.src|nostrkey|nostrkey|0.3.0"
  "nwc.app.OC-python.src|nostrwalletconnect|nostrwalletconnect|0.1.4"
  "nostrcalendar.app.OC-python.src|nostrcalendar|nostrcalendar|0.2.3"
  "nostrsocial.app.OC-python.src|nostrsocial|nostrsocial|0.1.3"
  "nostralignment.app.OC-python.src|social-alignment|social-alignment|0.1.5"
  "huje.sensememory.OC-python.src|sense-memory|sense-memory|0.1.3"
  "huje.sensemusic.OC-python.src|sense-music|sense-music|0.1.5"
  "huje.sensewonder.OC-python.src|sense-wonder|sense-wonder|0.1.2"
  "huje.nostrprofile.OC-python.src|nostr-profile|nostr-profile|0.2.0"
  "huje.socialcard.OC-python.src|social-card|social-card|0.2.1"
  "huje.socialvalue.OC-python.src|social-value|social-value|0.1.0"
  "nse-orchestrator.app.OC-python.src|nse-orchestrator|nse|0.2.2"
)

echo "═══════════════════════════════════════════════════════"
echo "  social-value sweep — OC package publish pipeline"
echo "  Mode: $MODE"
echo "═══════════════════════════════════════════════════════"
echo ""

for entry in "${PACKAGES[@]}"; do
  IFS='|' read -r repo pypi_name clawhub_slug new_version <<< "$entry"
  dir="$BASE_DIR/$repo"

  if [ ! -d "$dir" ]; then
    echo "⚠  SKIP $repo — directory not found"
    continue
  fi

  echo "── $pypi_name ($new_version) ──"

  # Check version sync
  if [ -f "$dir/pyproject.toml" ]; then
    toml_ver=$(grep '^version' "$dir/pyproject.toml" | head -1 | sed 's/.*"\(.*\)".*/\1/')
    echo "   pyproject.toml: $toml_ver"
  fi
  if [ -f "$dir/clawhub/metadata.json" ]; then
    ch_ver=$(python3 -c "import json; print(json.load(open('$dir/clawhub/metadata.json'))['version'])")
    echo "   metadata.json:  $ch_ver"
  fi

  if [ "$MODE" = "--pypi" ] || [ "$MODE" = "--all" ]; then
    if [ -f "$dir/pyproject.toml" ]; then
      echo "   → Building..."
      (cd "$dir" && rm -rf dist/ && python3 -m build --quiet)
      echo "   → Publishing to PyPI..."
      (cd "$dir" && twine upload dist/${pypi_name//-/_}-${new_version}*) || echo "   ⚠  PyPI publish failed for $pypi_name (continuing)"
    else
      echo "   → No pyproject.toml — skipping PyPI"
    fi
  fi

  if [ "$MODE" = "--clawhub" ] || [ "$MODE" = "--all" ]; then
    if [ -d "$dir/clawhub" ]; then
      echo "   → Publishing to ClawHub..."
      (cd "$dir" && npx clawhub publish ./clawhub \
        --slug "$clawhub_slug" \
        --name "$pypi_name" \
        --version "$new_version" \
        --tags latest \
        --changelog "Security hardening: SecretStr, sanitized exceptions, input validation" \
        2>&1) || echo "   ⚠  ClawHub publish failed for $pypi_name (continuing)"
    else
      echo "   → No clawhub/ — skipping ClawHub"
    fi
  fi

  if [ "$MODE" = "dry" ]; then
    echo "   → DRY RUN — no changes"
  fi

  echo ""
done

echo "═══════════════════════════════════════════════════════"
echo "  Done. Published ${#PACKAGES[@]} packages."
echo "═══════════════════════════════════════════════════════"
