#!/usr/bin/env bash
# check-token-drift.sh — Verify generated design token files are up to date.
#
# Regenerates all token outputs from the canonical bytelyst.tokens.json
# and diffs them against the committed files. Non-zero exit if any drift.
#
# Usage:
#   bash scripts/check-token-drift.sh        # check for drift
#   bash scripts/check-token-drift.sh --fix  # regenerate and stage changes

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TOKENS_DIR="$REPO_ROOT/packages/design-tokens"
GENERATED_DIR="$TOKENS_DIR/generated"

FIX=false
if [[ "${1:-}" == "--fix" ]]; then
  FIX=true
fi

echo "🔍 Checking design token drift..."

# 1. Snapshot current generated files
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

if [ -d "$GENERATED_DIR" ]; then
  cp -r "$GENERATED_DIR" "$TMPDIR/before"
else
  mkdir -p "$TMPDIR/before"
fi

# 2. Regenerate tokens
echo "   Regenerating tokens from bytelyst.tokens.json..."
cd "$TOKENS_DIR"
if [ -f "package.json" ] && grep -q '"generate"' package.json; then
  npx tsx scripts/generate.ts 2>/dev/null || {
    echo "⚠️  Token generation script failed — skipping drift check"
    exit 0
  }
else
  echo "⚠️  No generate script found in packages/design-tokens — skipping"
  exit 0
fi

# 3. Snapshot regenerated output
cp -r "$GENERATED_DIR" "$TMPDIR/after"

# 4. Diff
DIFF_OUTPUT=$(diff -rq "$TMPDIR/before" "$TMPDIR/after" 2>/dev/null || true)

if [ -z "$DIFF_OUTPUT" ]; then
  echo "✅ No token drift detected — generated files are up to date."
  exit 0
fi

echo ""
echo "❌ Token drift detected! The following files are out of date:"
echo ""
echo "$DIFF_OUTPUT" | while IFS= read -r line; do
  # Extract just the relative path
  file=$(echo "$line" | sed "s|.*$TMPDIR/before/||; s|.*$TMPDIR/after/||; s| differ||; s| and .*||")
  echo "   - generated/$file"
done

if $FIX; then
  echo ""
  echo "🔧 --fix mode: staging regenerated token files..."
  cd "$REPO_ROOT"
  git add "$GENERATED_DIR"
  echo "✅ Regenerated files staged. Commit and push to fix drift."
  exit 0
else
  echo ""
  echo "Run 'bash scripts/check-token-drift.sh --fix' to regenerate and stage."
  echo "Or: cd packages/design-tokens && npx tsx scripts/generate.ts"
  exit 1
fi
