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

/**
 * Comprehensive Create Event Page 404 Debugging Script
 * 
 * This script systematically checks:
 * 1. Page existence in WordPress database
 * 2. Template assignment and shortcode content
 * 3. Authentication and access permissions
 * 4. TEC shortcode rendering
 * 5. REST API script loading
 * 6. URL routing and rewrite rules
 */

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 color codes for terminal output
const colors = {
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    magenta: '\x1b[35m',
    cyan: '\x1b[36m',
    reset: '\x1b[0m',
    bold: '\x1b[1m'
};

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

function logSection(title) {
    log('\n' + '='.repeat(60), 'cyan');
    log(`  ${title}`, 'bold');
    log('='.repeat(60), 'cyan');
}

function logStep(step, description) {
    log(`\n${step}. ${description}`, 'blue');
}

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

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

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

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

    // Enable request/response logging
    page.on('request', request => {
        if (request.url().includes('create-event') || request.url().includes('hvac')) {
            log(`📤 REQUEST: ${request.method()} ${request.url()}`, 'magenta');
        }
    });

    page.on('response', response => {
        if (response.url().includes('create-event') || response.url().includes('hvac')) {
            log(`📥 RESPONSE: ${response.status()} ${response.url()}`, 'magenta');
        }
    });

    // Capture console logs
    page.on('console', msg => {
        if (msg.text().includes('Create Event') || msg.text().includes('HVAC') || msg.text().includes('REST API')) {
            log(`🖥️  CONSOLE: ${msg.text()}`, 'cyan');
        }
    });

    try {
        logSection('CREATE EVENT PAGE 404 DEBUGGING');

        // Step 1: Test direct access without authentication
        logStep(1, 'Testing direct access to create-event page (no auth)');
        const directResponse = await page.goto(CREATE_EVENT_URL, { waitUntil: 'networkidle' });
        log(`Status: ${directResponse.status()}`);
        
        if (directResponse.status() === 404) {
            logError('Page returns 404 - page may not exist in database');
        } else if (directResponse.status() === 302 || directResponse.status() === 301) {
            logWarning('Page redirects - likely authentication required');
        } else {
            logSuccess('Page accessible without authentication');
        }

        await page.screenshot({ path: './test-results/01-create-event-no-auth.png', fullPage: true });

        // Step 2: Check if login is required
        logStep(2, 'Checking if page requires authentication');
        const currentUrl = page.url();
        if (currentUrl.includes('login') || currentUrl.includes('wp-admin')) {
            logWarning('Page requires authentication - redirected to login');
        } else {
            log(`Current URL: ${currentUrl}`);
        }

        // Step 3: Authenticate as test trainer
        logStep(3, 'Authenticating as test trainer');
        await page.goto(`${BASE_URL}/trainer/login/`);
        
        try {
            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);
            logSuccess('Successfully authenticated');
        } catch (error) {
            logError(`Authentication failed: ${error.message}`);
            await page.screenshot({ path: './test-results/02-auth-failed.png', fullPage: true });
        }

        // Step 4: Test authenticated access to create-event page
        logStep(4, 'Testing authenticated access to create-event page');
        const authResponse = await page.goto(CREATE_EVENT_URL, { waitUntil: 'networkidle' });
        log(`Status: ${authResponse.status()}`);
        
        if (authResponse.status() === 404) {
            logError('Still returns 404 with authentication - page definitely doesn\'t exist');
        } else {
            logSuccess('Page accessible with authentication');
        }

        await page.screenshot({ path: './test-results/03-create-event-auth.png', fullPage: true });

        // Step 5: Check page content and title
        logStep(5, 'Analyzing page content');
        const pageTitle = await page.title();
        log(`Page Title: ${pageTitle}`);
        
        const hasHVACContent = await page.locator('.hvac-create-event-wrapper').count() > 0;
        log(`HVAC wrapper present: ${hasHVACContent}`);
        
        const hasNavigation = await page.locator('.hvac-trainer-nav').count() > 0;
        log(`HVAC navigation present: ${hasNavigation}`);

        // Step 6: Check for TEC form presence
        logStep(6, 'Checking for The Events Calendar form');
        const hasTECForm = await page.locator('#tribe-community-events').count() > 0;
        log(`TEC form container present: ${hasTECForm}`);
        
        const hasSubmissionForm = await page.locator('form[id*="tribe"]').count() > 0;
        log(`TEC submission form present: ${hasSubmissionForm}`);

        if (!hasTECForm && !hasSubmissionForm) {
            logError('No TEC form found - shortcode may not be rendering');
            
            // Check for error messages
            const errorText = await page.textContent('body');
            if (errorText.includes('do_shortcode')) {
                logError('Shortcode syntax error detected');
            }
            if (errorText.includes('tribe_community_events')) {
                logError('TEC Community Events shortcode not recognized');
            }
        }

        // Step 7: Check REST API script loading
        logStep(7, 'Checking REST API script loading');
        const restApiScriptLoaded = await page.evaluate(() => {
            return typeof HVACRestEventSubmission !== 'undefined';
        });
        log(`REST API script loaded: ${restApiScriptLoaded}`);

        const restApiScriptExists = await page.locator('script[src*="hvac-rest-api-event-submission"]').count() > 0;
        log(`REST API script tag present: ${restApiScriptExists}`);

        // Step 8: Test alternative URLs
        logStep(8, 'Testing alternative URL patterns');
        const alternativeUrls = [
            `${BASE_URL}/trainer/create-event`,  // Without trailing slash
            `${BASE_URL}/create-event/`,          // Direct path
            `${BASE_URL}/events/community/add`,   // TEC default
            `${BASE_URL}/?page_id=create-event`   // Query parameter
        ];

        for (const url of alternativeUrls) {
            try {
                const response = await page.goto(url, { waitUntil: 'networkidle', timeout: 5000 });
                log(`${url}: ${response.status()}`);
            } catch (error) {
                log(`${url}: TIMEOUT/ERROR`, 'red');
            }
        }

        // Step 9: Check WordPress database via REST API
        logStep(9, 'Checking WordPress pages via REST API');
        try {
            const apiResponse = await page.goto(`${BASE_URL}/wp-json/wp/v2/pages?search=create-event`, { waitUntil: 'networkidle' });
            const pages = await apiResponse.json();
            log(`Found ${pages.length} pages matching 'create-event'`);
            
            if (pages.length > 0) {
                pages.forEach((page, index) => {
                    log(`Page ${index + 1}: ID=${page.id}, Title="${page.title.rendered}", Slug="${page.slug}"`);
                    log(`  Status: ${page.status}, Template: ${page.template || 'default'}`);
                });
            } else {
                logError('No pages found with "create-event" in title or content');
            }
        } catch (error) {
            logError(`Failed to check REST API: ${error.message}`);
        }

        // Step 10: Generate debugging summary
        logStep(10, 'Generating debugging summary');
        await page.screenshot({ path: './test-results/04-final-state.png', fullPage: true });

        logSection('DEBUGGING SUMMARY');
        
        if (authResponse.status() === 404) {
            logError('ROOT CAUSE: Page does not exist in WordPress database');
            log('\nRECOMMENDED ACTIONS:', 'yellow');
            log('1. Run the create-event-pages.sh script again');
            log('2. Check if the script completed successfully');
            log('3. Verify page was created with correct parent hierarchy');
            log('4. Check WordPress admin for any error messages');
        } else if (!hasTECForm && !hasSubmissionForm) {
            logError('ROOT CAUSE: TEC shortcode not rendering properly');
            log('\nRECOMMENDED ACTIONS:', 'yellow');
            log('1. Verify The Events Calendar Community Events plugin is active');
            log('2. Check if TEC Community Events is properly configured');
            log('3. Test TEC shortcode on a simple page');
            log('4. Review plugin dependencies');
        } else if (!restApiScriptLoaded) {
            logWarning('ISSUE: REST API enhancement script not loading');
            log('\nRECOMMENDED ACTIONS:', 'yellow');
            log('1. Check if HVAC plugin assets are enqueued properly');
            log('2. Verify script path and permissions');
            log('3. Test script loading independently');
        } else {
            logSuccess('Page appears to be working correctly');
            log('\nIf still experiencing issues:', 'yellow');
            log('1. Clear all caches (WordPress, CDN, browser)');
            log('2. Check for JavaScript errors in browser console');
            log('3. Verify user permissions for event creation');
        }

    } catch (error) {
        logError(`Script failed: ${error.message}`);
        await page.screenshot({ path: './test-results/error-state.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

// Run the debugging script
debugCreateEventPage().catch(console.error);