#!/usr/bin/env bash
#
# check-updates.sh — Check if a new version of Bulma is available
#
# Compares the version tracked in SKILL.md against the latest npm release.
# Exit codes: 0 = up to date, 1 = update available, 2 = error
#
# Usage:
#   ./check-updates.sh              # Check and report
#   ./check-updates.sh --quiet      # Exit code only (for CI/cron)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_FILE="$SCRIPT_DIR/../SKILL.md"
NPM_REGISTRY="https://registry.npmjs.org/bulma/latest"

QUIET=false
[[ "${1:-}" == "--quiet" ]] && QUIET=true

# Extract current version from SKILL.md frontmatter
if [[ ! -f "$SKILL_FILE" ]]; then
  echo "ERROR: SKILL.md not found at $SKILL_FILE" >&2
  exit 2
fi

CURRENT_VERSION=$(grep -m1 '^framework_version:' "$SKILL_FILE" | sed 's/framework_version:[[:space:]]*//')
if [[ -z "$CURRENT_VERSION" ]]; then
  echo "ERROR: Could not extract framework_version from SKILL.md" >&2
  exit 2
fi

# Fetch latest version from npm
LATEST_VERSION=$(curl -sf "$NPM_REGISTRY" | grep -o '"version":"[^"]*"' | head -1 | sed 's/"version":"//;s/"//')
if [[ -z "$LATEST_VERSION" ]]; then
  echo "ERROR: Could not fetch latest version from npm" >&2
  exit 2
fi

# Compare
if [[ "$CURRENT_VERSION" == "$LATEST_VERSION" ]]; then
  if [[ "$QUIET" == false ]]; then
    echo "Bulma skill is up to date (v$CURRENT_VERSION)"
  fi
  exit 0
else
  if [[ "$QUIET" == false ]]; then
    echo "Bulma update available: v$CURRENT_VERSION -> v$LATEST_VERSION"
    echo ""
    echo "To update the skill, run one of:"
    echo "  /bulma-update              (in Claude Code)"
    echo "  /bulma-update --force      (force full re-fetch)"
    echo ""
    echo "Release notes: https://github.com/jgthms/bulma/releases"
  fi
  exit 1
fi
