const { chromium } = require('playwright');

/**
 * The Events Calendar (TEC) Diagnosis Script
 * 
 * This script specifically diagnoses why the TEC form is not rendering
 * on the now-working create-event page.
 */

const BASE_URL = 'https://upskill-staging.measurequick.com';
const CREATE_EVENT_URL = `${BASE_URL}/trainer/create-event/`;
const TEST_CREDENTIALS = {
    username: 'test_trainer',
    password: 'TestTrainer123!'
};

// ANSI colors
const colors = {
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    cyan: '\x1b[36m',
    reset: '\x1b[0m',
    bold: '\x1b[1m'
};

function log(message, color = 'reset') {
    console.log(`${colors[color]}${message}${colors.reset}`);
}

function logSuccess(message) {
    log(`✅ ${message}`, 'green');
}

function logError(message) {
    log(`❌ ${message}`, 'red');
}

function logWarning(message) {
    log(`⚠️  ${message}`, 'yellow');
}

async function diagnoseTEC() {
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext();
    const page = await context.newPage();

    // Capture TEC-related console messages
    page.on('console', msg => {
        const text = msg.text();
        if (text.includes('tribe') || text.includes('TEC') || text.includes('Events Calendar') || text.includes('shortcode')) {
            log(`🖥️  CONSOLE: ${text}`, 'cyan');
        }
    });

    try {
        log('\n=== TEC FORM DIAGNOSIS ===', 'bold');

        // Authenticate first
        log('\n1. Authenticating...', 'blue');
        await page.goto(`${BASE_URL}/trainer/login/`);
        await page.fill('#user_login', TEST_CREDENTIALS.username);
        await page.fill('#user_pass', TEST_CREDENTIALS.password);
        await page.click('#wp-submit');
        await page.waitForTimeout(2000);

        // Go to create event page
        log('\n2. Loading create-event page...', 'blue');
        await page.goto(CREATE_EVENT_URL, { waitUntil: 'networkidle' });

        // Check page content
        log('\n3. Analyzing page content for TEC indicators...', 'blue');
        
        const pageContent = await page.content();
        
        // Check for TEC-related content
        const hasTribeString = pageContent.includes('tribe');
        const hasEventString = pageContent.includes('event');
        const hasShortcodeOutput = pageContent.includes('[tribe_community_events');
        const hasErrorMessage = pageContent.includes('requires') && pageContent.includes('add-on');
        
        log(`Contains "tribe": ${hasTribeString}`);
        log(`Contains "event": ${hasEventString}`);
        log(`Shortcode visible in output: ${hasShortcodeOutput}`);
        log(`Contains error message: ${hasErrorMessage}`);

        // Check for specific TEC elements
        const tecElements = {
            'TEC container': await page.locator('#tribe-community-events').count() > 0,
            'TEC form': await page.locator('form[id*="tribe"]').count() > 0,
            'Any form': await page.locator('form').count() > 0,
            'Community events content': await page.locator('.tribe-community-events').count() > 0,
            'Event submission content': await page.locator('[class*="submission"]').count() > 0
        };

        log('\n4. TEC Element Detection:', 'blue');
        Object.entries(tecElements).forEach(([name, present]) => {
            log(`${name}: ${present}`, present ? 'green' : 'red');
        });

        // Check for HVAC shortcode output
        log('\n5. Checking HVAC shortcode processing...', 'blue');
        const shortcodeContent = await page.locator('.hvac-page-content').textContent();
        
        if (shortcodeContent.includes('Event management requires')) {
            logError('TEC Community Events add-on not available');
            logWarning('The plugin dependency is missing or not activated');
        } else if (shortcodeContent.trim().length < 50) {
            logWarning('Shortcode output is very short - may not be rendering properly');
        } else {
            logSuccess('Shortcode appears to be processing content');
        }

        // Test alternative TEC URLs
        log('\n6. Testing TEC direct access...', 'blue');
        const tecUrls = [
            `${BASE_URL}/events/community/add/`,
            `${BASE_URL}/events/community/list/`,
            `${BASE_URL}/community/add/`,
            `${BASE_URL}/?tribe_events=community&action=add`
        ];

        for (const url of tecUrls) {
            try {
                const response = await page.goto(url, { waitUntil: 'networkidle', timeout: 5000 });
                log(`${url}: ${response.status()}`);
                if (response.status() === 200) {
                    const hasForm = await page.locator('form').count() > 0;
                    log(`  Has form: ${hasForm}`, hasForm ? 'green' : 'red');
                }
            } catch (error) {
                log(`${url}: ERROR`, 'red');
            }
        }

        // Check WordPress admin for TEC
        log('\n7. Checking WordPress plugin status via REST API...', 'blue');
        try {
            const pluginsResponse = await page.goto(`${BASE_URL}/wp-json/wp/v2/plugins`, { waitUntil: 'networkidle' });
            if (pluginsResponse.status() === 200) {
                const plugins = await pluginsResponse.json();
                const tecPlugins = plugins.filter(p => 
                    p.name.toLowerCase().includes('events') || 
                    p.name.toLowerCase().includes('tribe') ||
                    p.name.toLowerCase().includes('community')
                );
                
                if (tecPlugins.length > 0) {
                    logSuccess(`Found ${tecPlugins.length} TEC-related plugins`);
                    tecPlugins.forEach(p => {
                        log(`  - ${p.name}: ${p.status}`, p.status === 'active' ? 'green' : 'red');
                    });
                } else {
                    logError('No TEC-related plugins found');
                }
            }
        } catch (error) {
            logWarning('Could not check plugin status via REST API');
        }

        // Save screenshot
        await page.screenshot({ path: './test-results/tec-diagnosis.png', fullPage: true });

        // Final diagnosis
        log('\n=== DIAGNOSIS SUMMARY ===', 'bold');
        
        if (hasErrorMessage) {
            logError('TEC Community Events plugin not available');
            log('\nSOLUTION:', 'yellow');
            log('1. Install The Events Calendar Community Events plugin');
            log('2. Configure plugin with proper permissions');
            log('3. Verify plugin activation');
        } else if (!tecElements['Any form']) {
            logError('No forms found on page - shortcode not rendering');
            log('\nSOLUTION:', 'yellow');
            log('1. Check if TEC plugins are properly activated');
            log('2. Verify shortcode registration');
            log('3. Check for JavaScript errors preventing form display');
        } else if (tecElements['Any form'] && !tecElements['TEC form']) {
            logWarning('Forms present but not TEC forms');
            log('\nSOLUTION:', 'yellow');
            log('1. Check TEC form configuration');
            log('2. Verify user permissions for event creation');
            log('3. Test with admin user');
        } else {
            logSuccess('Basic TEC infrastructure appears to be working');
            log('\nNEXT STEPS:', 'yellow');
            log('1. Check form functionality');
            log('2. Test event submission');
            log('3. Verify REST API enhancements');
        }

    } catch (error) {
        logError(`Diagnosis failed: ${error.message}`);
    } finally {
        await browser.close();
    }
}

// Run diagnosis
diagnoseTEC().catch(console.error);