#!/bin/bash
# validate-sdk-imports.sh
# Validates that Directus extensions only use exports that exist in @directus/extensions-sdk.
# Prevents the "SyntaxError: doesn't provide an export named" runtime crash
# that silently breaks ALL extensions in the browser.

set -euo pipefail

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

# Valid exports from @directus/extensions-sdk in Directus 11.x
# If Directus is upgraded, update this list by running:
#   curl -s http://cms.localhost/admin/assets/@directus_extensions-sdk.*.entry.js | grep -oE 'export\{[^}]+\}'
VALID_EXPORTS=(
  "defineDisplay"
  "defineEndpoint"
  "defineHook"
  "defineInterface"
  "defineLayout"
  "defineModule"
  "defineOperationApi"
  "defineOperationApp"
  "definePanel"
  "defineTheme"
  "getFieldsFromTemplate"
  "getRelationType"
  "useApi"
  "useCollection"
  "useExtensions"
  "useFilterFields"
  "useItems"
  "useLayout"
  "useSdk"
  "useStores"
  "useSync"
)

ERRORS=0

echo "🔍 Validating @directus/extensions-sdk imports..."
echo ""

# Search all .ts and .vue files in extension directories
SEARCH_DIRS=(
  "$REPO_ROOT/packages/cms-infra/extensions"
  "$REPO_ROOT/packages/unified-dashboard"
  "$REPO_ROOT/packages/customer-manager"
  "$REPO_ROOT/packages/company-manager"
  "$REPO_ROOT/packages/people-manager"
  "$REPO_ROOT/packages/acquisition-manager"
  "$REPO_ROOT/packages/feedback-commander"
)

for DIR in "${SEARCH_DIRS[@]}"; do
  [ -d "$DIR" ] || continue

  # Find all imports from @directus/extensions-sdk
  while IFS= read -r line; do
    FILE=$(echo "$line" | cut -d: -f1)
    LINENUM=$(echo "$line" | cut -d: -f2)
    CONTENT=$(echo "$line" | cut -d: -f3-)

    # Extract imported names from the import statement
    IMPORTS=$(echo "$CONTENT" | grep -oE '\{[^}]+\}' | tr -d '{}' | tr ',' '\n' | sed 's/^ *//;s/ *$//' | sed 's/ as .*//')

    for IMPORT in $IMPORTS; do
      [ -z "$IMPORT" ] && continue
      FOUND=false
      for VALID in "${VALID_EXPORTS[@]}"; do
        if [ "$IMPORT" = "$VALID" ]; then
          FOUND=true
          break
        fi
      done

      if [ "$FOUND" = false ]; then
        echo "❌ INVALID IMPORT: '$IMPORT' in $FILE:$LINENUM"
        echo "   '$IMPORT' is NOT exported by @directus/extensions-sdk in Directus 11.x"
        echo "   This WILL crash ALL extensions at runtime!"
        echo ""
        ERRORS=$((ERRORS + 1))
      fi
    done
  done < <(grep -rn "from ['\"]@directus/extensions-sdk['\"]" "$DIR" --include="*.ts" --include="*.vue" 2>/dev/null || true)
done

if [ "$ERRORS" -gt 0 ]; then
  echo "💥 Found $ERRORS invalid import(s)!"
  echo ""
  echo "Valid exports from @directus/extensions-sdk:"
  printf "  %s\n" "${VALID_EXPORTS[@]}"
  echo ""
  echo "Common fixes:"
  echo "  useRouter → import { useRouter } from 'vue-router'"
  echo "  useRoute  → import { useRoute } from 'vue-router'"
  exit 1
else
  echo "✅ All @directus/extensions-sdk imports are valid."
fi
