#!/usr/bin/env bash
# upgrade.sh — Upgrade Spec-Driven Docs framework in an existing project.
#
# Usage:
#   bash scripts/upgrade.sh
#   bash scripts/upgrade.sh --module java-spring   # also upgrade a stack module
#
# What it does:
#   1. Reads current installed version from .agent/FRAMEWORK_VERSION
#   2. Checks npm registry for the latest published version
#   3. If newer: runs npx @edupia-tutor/spec-driven-docs@latest --init to update .agent/
#   4. Reports what changed so you can review before committing
#
# Requirements:
#   - Project was set up with init.sh (or npx ... --init)
#   - .agent/FRAMEWORK_VERSION exists

set -euo pipefail

AGENT_DIR=".agent"
VERSION_FILE="${AGENT_DIR}/FRAMEWORK_VERSION"

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║   Spec-Driven Docs — Upgrade              ║"
echo "╚══════════════════════════════════════════╝"
echo ""

# ── Prerequisite checks ───────────────────────────────────────────────────────

if ! command -v node &> /dev/null; then
  echo "❌ Node.js is required. Install from https://nodejs.org"
  exit 1
fi

if ! command -v npm &> /dev/null; then
  echo "❌ npm is required. Install Node.js from https://nodejs.org"
  exit 1
fi

if [ ! -f "$VERSION_FILE" ]; then
  echo "❌ .agent/FRAMEWORK_VERSION not found."
  echo ""
  echo "   This project was not set up with --init."
  echo "   To set up the new structure:"
  echo ""
  echo "     bash scripts/init.sh"
  echo "   or:"
  echo "     npx @edupia-tutor/spec-driven-docs --init"
  echo ""
  exit 1
fi

# ── Version comparison ────────────────────────────────────────────────────────

CURRENT=$(cat "$VERSION_FILE" | tr -d '[:space:]')
echo "Checking npm registry ..."

LATEST=$(npm view @edupia-tutor/spec-driven-docs version 2>/dev/null || echo "unknown")

echo ""
echo "  Installed : v${CURRENT}"
echo "  Latest    : v${LATEST}"
echo ""

if [ "$LATEST" = "unknown" ]; then
  echo "⚠️  Could not reach npm registry. Check your internet connection."
  exit 1
fi

if [ "$CURRENT" = "$LATEST" ]; then
  echo "✅ Already up to date (v${CURRENT}). Nothing to do."
  echo ""
  exit 0
fi

# ── Upgrade ───────────────────────────────────────────────────────────────────

echo "Upgrading v${CURRENT} → v${LATEST} ..."
echo ""

npx -y @edupia-tutor/spec-driven-docs@latest --init "$@"

# ── Post-upgrade guidance ─────────────────────────────────────────────────────

echo ""
echo "✅ Upgraded to v${LATEST}!"
echo ""
echo "Review what changed in .agent/ before committing:"
echo ""
echo "  git diff .agent/"
echo "  git add .agent/"
echo "  git commit -m 'chore: upgrade spec-driven-docs v${CURRENT} → v${LATEST}'"
echo ""
