#!/bin/bash
# verify-selectors.sh - Script to verify critical selectors before deployment
# Usage: ./bin/verify-selectors.sh [--ci] [--fix]

set -e

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

# Parse arguments
CI_MODE=false
FIX_MODE=false

for arg in "$@"; do
  case $arg in
    --ci)
      CI_MODE=true
      shift
      ;;
    --fix)
      FIX_MODE=true
      shift
      ;;
  esac
done

echo -e "${GREEN}=== Selector Verification Tool ===${NC}"
echo "Checking critical selectors in the HVAC Community Events plugin..."

# Define critical pages and their selectors to verify
declare -A CRITICAL_PAGES
CRITICAL_PAGES[login]="/community-login/"
CRITICAL_PAGES[dashboard]="/hvac-dashboard/"
CRITICAL_PAGES[certificate_report]="/certificates-report/"

# Check if we're in the right directory
if [ ! -d "tests/e2e" ]; then
  echo -e "${RED}Error: Please run this script from the wordpress-dev directory${NC}"
  exit 1
fi

# Create screenshots directory if it doesn't exist
mkdir -p screenshots/selector-verification

# Function to verify selectors
verify_selectors() {
  local page_name=$1
  local page_url=$2
  
  echo -e "\n${YELLOW}Verifying selectors for: ${page_name}${NC}"
  
  # Run Playwright test to verify selectors
  npx playwright test tests/e2e/debug-login-page.spec.ts --config=playwright.config.ts || {
    echo -e "${RED}Error: Selector verification failed for ${page_name}${NC}"
    
    if [ "$CI_MODE" = true ]; then
      echo "CI mode enabled, failing build due to selector verification failure"
      exit 1
    fi
    
    if [ "$FIX_MODE" = true ]; then
      echo -e "${YELLOW}Fix mode enabled, attempting to auto-fix selectors...${NC}"
      # Create a debug selector test for this page if it doesn't exist
      if [ ! -f "tests/e2e/debug-${page_name}-page.spec.ts" ]; then
        echo "Creating debug test for ${page_name}..."
        # Template for debug test
        cat > "tests/e2e/debug-${page_name}-page.spec.ts" << EOF
import { test, expect } from '@playwright/test';
import { STAGING_URL } from './config/staging-config';

test('Debug ${page_name} page selectors', async ({ page }) => {
  console.log('Starting ${page_name} page debug');
  
  // Navigate to the page
  await page.goto('${STAGING_URL}${page_url}', { waitUntil: 'networkidle' });
  console.log(\`Current URL: \${page.url()}\`);
  
  // Take screenshot
  await page.screenshot({ path: 'screenshots/selector-verification/${page_name}-page.png' });
  
  // Dump HTML structure
  const html = await page.content();
  console.log('First 500 chars of HTML:');
  console.log(html.substring(0, 500));
  
  // Look for form elements
  const forms = await page.$$('form');
  console.log(\`Number of forms: \${forms.length}\`);
  
  // Output all forms
  for (let i = 0; i < forms.length; i++) {
    const form = forms[i];
    const action = await form.evaluate(f => f.getAttribute('action') || 'No action').catch(() => 'Unknown');
    const method = await form.evaluate(f => f.getAttribute('method') || 'No method').catch(() => 'Unknown');
    const id = await form.evaluate(f => f.getAttribute('id') || 'No id').catch(() => 'Unknown');
    const className = await form.evaluate(f => f.getAttribute('class') || 'No class').catch(() => 'Unknown');
    
    console.log(\`\nForm #\${i+1}:\`);
    console.log(\`  ID: \${id}\`);
    console.log(\`  Class: \${className}\`);
    console.log(\`  Action: \${action}\`);
    console.log(\`  Method: \${method}\`);
    
    // Get inputs in the form
    const inputs = await form.$$('input');
    console.log(\`  Inputs: \${inputs.length}\`);
    
    for (const input of inputs) {
      const type = await input.evaluate(i => i.getAttribute('type') || 'No type').catch(() => 'Unknown');
      const name = await input.evaluate(i => i.getAttribute('name') || 'No name').catch(() => 'Unknown');
      const id = await input.evaluate(i => i.getAttribute('id') || 'No id').catch(() => 'Unknown');
      console.log(\`    Input: Type=\${type}, Name=\${name}, ID=\${id}\`);
    }
  }
  
  // Look for buttons, links and other interactive elements
  const buttons = await page.$$('button, input[type="button"], input[type="submit"]');
  console.log(\`\nNumber of buttons: \${buttons.length}\`);
  
  for (let i = 0; i < buttons.length; i++) {
    const button = buttons[i];
    const id = await button.evaluate(b => b.getAttribute('id') || 'No id').catch(() => 'Unknown');
    const text = await button.evaluate(b => b.innerText || b.value || 'No text').catch(() => 'Unknown');
    console.log(\`  Button #\${i+1}: ID=\${id}, Text=\${text}\`);
  }
  
  console.log('\nDebug complete');
});
EOF
        echo "Debug test created. Running the debug test..."
        npx playwright test "tests/e2e/debug-${page_name}-page.spec.ts" --config=playwright.config.ts
      fi
    fi
    
    return 1
  }
  
  echo -e "${GREEN}✓ Selectors verified for ${page_name}${NC}"
  return 0
}

# Main verification logic
FAILURES=0

# Verify login page selectors first (most critical)
if ! verify_selectors "login" "${CRITICAL_PAGES[login]}"; then
  FAILURES=$((FAILURES + 1))
fi

# Verify dashboard selectors
if ! verify_selectors "dashboard" "${CRITICAL_PAGES[dashboard]}"; then
  FAILURES=$((FAILURES + 1))
fi

# Verify certificate report selectors
if ! verify_selectors "certificate_report" "${CRITICAL_PAGES[certificate_report]}"; then
  FAILURES=$((FAILURES + 1))
fi

# Summary
echo -e "\n${GREEN}=== Selector Verification Summary ===${NC}"
if [ $FAILURES -eq 0 ]; then
  echo -e "${GREEN}✓ All selectors verified successfully${NC}"
  exit 0
else
  echo -e "${RED}✗ ${FAILURES} selector verification(s) failed${NC}"
  echo "Please check the debug test results and update selectors as needed"
  
  if [ "$CI_MODE" = true ]; then
    echo "CI build failed due to selector verification failures"
    exit 1
  fi
  
  echo "You can run with --fix to create debug tests for failing pages"
  exit 1
fi