#!/bin/bash
#
# Command Registration Audit Script
# Verifies that all commands defined in package.json are registered in the codebase
#

set -e

VSCODE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
SRC_DIR="$VSCODE_DIR/src"
PACKAGE_JSON="$VSCODE_DIR/package.json"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo "🔍 Auditing VS Code Extension Commands..."
echo "=========================================="
echo ""

# Extract commands from package.json (only from commands section, not configuration)
echo "📦 Extracting commands from package.json..."
# Extract commands from the commands array specifically, filtering out configuration keys
COMMANDS=$(grep -A2 '"command":' "$PACKAGE_JSON" | grep -oE '"snapback\.[^"]+"' | tr -d '"' | sort -u)

if [ -z "$COMMANDS" ]; then
    echo -e "${RED}❌ No commands found in package.json${NC}"
    exit 1
fi

TOTAL=$(echo "$COMMANDS" | wc -l | tr -d ' ')
echo "Found $TOTAL commands in package.json"
echo ""

# Check each command for registration
MISSING=0
FOUND=0

echo "🔎 Checking command registrations..."
echo "-----------------------------------"

while IFS= read -r cmd; do
    # Skip internal commands (starting with snapback.internal.)
    if [[ "$cmd" == snapback.internal.* ]]; then
        continue
    fi

    # Skip when-clause contexts (contain spaces, &&, ||, ==, !=, etc.)
    if [[ "$cmd" =~ [[:space:]] ]] || [[ "$cmd" == *"&&"* ]] || [[ "$cmd" == *"||"* ]] || [[ "$cmd" == *"=="* ]] || [[ "$cmd" == *"!="* ]]; then
        continue
    fi

    # Search for command registration in TypeScript files
    # Check both direct string registration and constant-based registration
    if grep -r "registerCommand.*\"$cmd\"" "$SRC_DIR" --include="*.ts" > /dev/null 2>&1 || \
       grep -r "registerCommand.*'$cmd'" "$SRC_DIR" --include="*.ts" > /dev/null 2>&1 || \
       grep -r "\"$cmd\"" "$SRC_DIR/constants/commands.ts" > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} $cmd"
        ((FOUND++))
    else
        echo -e "${RED}✗${NC} $cmd - NOT REGISTERED"
        ((MISSING++))
    fi
done <<< "$COMMANDS"

echo ""
echo "=========================================="
echo "📊 Audit Summary"
echo "=========================================="
echo -e "Registered: ${GREEN}$FOUND${NC}"
echo -e "Missing: ${RED}$MISSING${NC}"
echo ""

if [ $MISSING -gt 0 ]; then
    echo -e "${RED}❌ Audit failed: $MISSING command(s) not registered${NC}"
    echo ""
    echo "To fix:"
    echo "1. Find the command definition in src/commands/"
    echo "2. Ensure it's imported and called in src/commands/index.ts"
    echo "3. Re-run this audit"
    exit 1
else
    echo -e "${GREEN}✅ All commands are properly registered!${NC}"
    exit 0
fi
