#!/bin/bash
# Check version consistency across package.json and documentation files
# Exit code 0 if consistent, 1 if inconsistent

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PROJECT_ROOT"

# Get version from package.json (source of truth)
PACKAGE_VERSION=$(node -e "console.log(require('./package.json').version)")

if [ -z "$PACKAGE_VERSION" ]; then
  echo "❌ ERROR: Could not read version from package.json"
  exit 1
fi

echo "📦 Package version (source of truth): $PACKAGE_VERSION"
echo ""

ERRORS=0

# Check README.md
if [ -f "README.md" ]; then
  README_VERSION=$(grep -iE "^\\*\\*Version\\*\\*:" README.md | head -1 | sed -E 's/.*Version\*\*:[[:space:]]*([0-9]+\.[0-9]+\.[0-9]+).*/\1/' || echo "")
  if [ -n "$README_VERSION" ] && [ "$README_VERSION" != "$PACKAGE_VERSION" ]; then
    echo "❌ README.md version mismatch: found '$README_VERSION', expected '$PACKAGE_VERSION'"
    ERRORS=1
  else
    echo "✅ README.md version matches"
  fi
fi

# Check src/definitions.ts
if [ -f "src/definitions.ts" ]; then
  DEFS_VERSION=$(grep -E "@version" src/definitions.ts | head -1 | sed -E 's/.*@version[[:space:]]+([0-9]+\.[0-9]+\.[0-9]+).*/\1/' || echo "")
  if [ -n "$DEFS_VERSION" ] && [ "$DEFS_VERSION" != "$PACKAGE_VERSION" ]; then
    echo "❌ src/definitions.ts version mismatch: found '$DEFS_VERSION', expected '$PACKAGE_VERSION'"
    ERRORS=1
  else
    echo "✅ src/definitions.ts version matches"
  fi
fi

# Check other common locations
for file in "src/index.ts" "src/web.ts" "src/observability.ts"; do
  if [ -f "$file" ]; then
    FILE_VERSION=$(grep -E "@version" "$file" 2>/dev/null | head -1 | sed -E 's/.*@version[[:space:]]+([0-9]+\.[0-9]+\.[0-9]+).*/\1/' || echo "")
    if [ -n "$FILE_VERSION" ] && [ "$FILE_VERSION" != "$PACKAGE_VERSION" ]; then
      echo "⚠️  $file version mismatch: found '$FILE_VERSION', expected '$PACKAGE_VERSION'"
      # Warning only, not an error
    fi
  fi
done

echo ""
if [ $ERRORS -eq 0 ]; then
  echo "✅ All version checks passed"
  exit 0
else
  echo "❌ Version consistency check failed"
  echo ""
  echo "Fix: Update version headers to match package.json version: $PACKAGE_VERSION"
  exit 1
fi

