#!/bin/bash

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

TARGET_DIRS=(
  "$REPO_ROOT/packages/cms-infra/extensions"
  "$REPO_ROOT/directus/extensions"
)

echo "🛡️  Directus Extension Validator"
echo "================================="

for TARGET in "${TARGET_DIRS[@]}"; do
  echo ""
  echo "📂 Checking: $TARGET"
  
  if [ ! -d "$TARGET" ]; then
    echo "  ❌ Directory does not exist!"
    continue
  fi

  CATEGORIES=("endpoints" "hooks" "layouts" "modules" "operations" "panels" "displays" "interfaces")
  FOUND_ANY=false

  for CAT in "${CATEGORIES[@]}"; do
    CAT_PATH="$TARGET/$CAT"
    if [ -d "$CAT_PATH" ]; then
      EXTS=$(ls "$CAT_PATH")
      if [ -n "$EXTS" ]; then
        FOUND_ANY=true
        echo "  📦 $CAT:"
        for EXT in $EXTS; do
          EXT_PATH="$CAT_PATH/$EXT"
          if [ -f "$EXT_PATH/package.json" ]; then
            VERSION=$(node -e "console.log(require('$EXT_PATH/package.json').version)")
            echo "    ✅ $EXT (v$VERSION)"
          else
            echo "    ⚠️  $EXT (MISSING package.json!)"
          fi
        done
      fi
    fi
  done

  if [ "$FOUND_ANY" = false ]; then
    echo "  📭 No extensions found in standard category folders."
  fi
  
  # Check for legacy files
  LEGACY=$(find "$TARGET" -maxdepth 1 -not -path "$TARGET" -not -name ".*" -type d)
  for L in $LEGACY; do
    BN=$(basename "$L")
    IS_CAT=false
    for CAT in "${CATEGORIES[@]}"; do
      if [ "$BN" == "$CAT" ]; then IS_CAT=true; break; fi
    done
    
    if [ "$IS_CAT" = false ]; then
      echo "  🚨 LEGACY/UNRESOLVED FOLDER FOUND: $BN (Will NOT be loaded by Directus)"
    fi
  done
done

echo ""
echo "✨ Validation complete."
