/**
 * TEC Template Validation Script
 * 
 * Specific validation for enhanced TEC Community Events template
 * Uses correct "network" URLs based on actual TEC configuration
 */

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

const config = {
    baseUrl: process.env.UPSKILL_STAGING_URL || 'https://upskill-staging.measurequick.com',
    timeout: 30000,
    testCredentials: {
        username: 'test_trainer',
        password: 'TestTrainer123!'
    }
};

console.log('🧪 TEC Enhanced Template Validation');
console.log(`🌐 Testing URL: ${config.baseUrl}`);
console.log('🎯 Target: Validate enhanced template with correct TEC URLs');
console.log('');

async function runTECTemplateValidation() {
    const browser = await chromium.launch({ 
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
    });
    
    const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 }
    });
    
    const page = await context.newPage();
    
    // Track console messages and errors
    const consoleMessages = [];
    const pageErrors = [];
    
    page.on('console', msg => {
        const message = msg.text();
        consoleMessages.push(message);
        if (message.includes('HVAC') || message.includes('Enhanced')) {
            console.log(`🔍 Browser: ${message}`);
        }
    });
    
    page.on('pageerror', error => {
        pageErrors.push(error.message);
        console.error(`❌ Page Error: ${error.message}`);
    });
    
    try {
        console.log('📋 Step 1: Login to staging site');
        
        await page.goto(`${config.baseUrl}/training-login/`, { 
            waitUntil: 'networkidle',
            timeout: config.timeout 
        });
        
        // Login
        const usernameField = page.locator('input[name="log"], #user_login').first();
        const passwordField = page.locator('input[name="pwd"], #user_pass').first();
        const submitButton = page.locator('input[type="submit"], button[type="submit"]').first();
        
        await usernameField.fill(config.testCredentials.username);
        await passwordField.fill(config.testCredentials.password);
        await submitButton.click();
        await page.waitForLoadState('networkidle');
        
        console.log('✅ Login completed');
        
        console.log('📋 Step 2: Test TEC event creation URLs');
        
        // Test the correct TEC Community Events URL structure
        const tecUrls = [
            '/events/network/add',           // Correct TEC Community URL
            '/events/community/add/',        // Expected but incorrect
            '/events/add/',                  // Alternative
        ];
        
        let enhancedTemplateFound = false;
        let workingUrl = null;
        
        for (const url of tecUrls) {
            try {
                console.log(`🔍 Testing: ${config.baseUrl}${url}`);
                
                await page.goto(`${config.baseUrl}${url}`, { 
                    waitUntil: 'networkidle',
                    timeout: 15000 
                });
                
                // Take screenshot for this URL
                await page.screenshot({ 
                    path: `test-results/tec-url-${url.replace(/\//g, '-')}.png`,
                    fullPage: true 
                });
                
                // Check for TEC Community Events form
                const tecForm = page.locator('form, .tribe-community').first();
                const formExists = await tecForm.count() > 0;
                
                if (formExists) {
                    console.log(`✅ TEC form found at: ${url}`);
                    workingUrl = url;
                    
                    // Check for enhanced template indicators
                    const enhancedIndicators = [
                        '.hvac-success-indicator',
                        '.hvac-tec-enhanced-form',
                        'style#hvac-tec-enhanced-styles'
                    ];
                    
                    for (const indicator of enhancedIndicators) {
                        const element = page.locator(indicator).first();
                        if (await element.count() > 0) {
                            console.log(`✅ Enhanced template active: ${indicator} found`);
                            enhancedTemplateFound = true;
                            break;
                        }
                    }
                    
                    if (enhancedTemplateFound) {
                        break;
                    }
                } else {
                    console.log(`❌ No TEC form at: ${url}`);
                }
                
            } catch (error) {
                console.log(`❌ Error testing ${url}: ${error.message}`);
            }
        }
        
        if (!workingUrl) {
            throw new Error('No working TEC Community Events URL found');
        }
        
        console.log('📋 Step 3: Validate enhanced template features');
        
        if (enhancedTemplateFound) {
            console.log('🎉 Enhanced template detected! Validating features...');
            
            const validationResults = await validateEnhancedFeatures(page);
            
            console.log('📋 Step 4: Test field population capabilities');
            
            const populationResults = await testFieldPopulation(page);
            
            const finalReport = generateValidationReport({
                working_url: workingUrl,
                enhanced_template: enhancedTemplateFound,
                feature_validation: validationResults,
                field_population: populationResults,
                page_errors: pageErrors,
                console_messages: consoleMessages.filter(msg => 
                    msg.includes('HVAC') || msg.includes('Enhanced') || msg.includes('✅') || msg.includes('❌')
                )
            });
            
            console.log('\n🎉 TEC TEMPLATE VALIDATION COMPLETE');
            console.log('='.repeat(60));
            console.log(finalReport);
            
            return finalReport;
            
        } else {
            console.log('⚠️ Enhanced template not detected, but TEC form is working');
            console.log('📋 This means the base TEC functionality is intact');
            
            const basicReport = generateValidationReport({
                working_url: workingUrl,
                enhanced_template: false,
                feature_validation: { message: 'Enhanced template not active' },
                field_population: { message: 'Not tested - enhanced template required' },
                page_errors: pageErrors,
                console_messages: consoleMessages
            });
            
            console.log('\n⚠️ TEC TEMPLATE VALIDATION PARTIAL');
            console.log('='.repeat(60));
            console.log(basicReport);
            
            return basicReport;
        }
        
    } catch (error) {
        console.error('❌ TEC template validation failed:', error.message);
        
        await page.screenshot({ 
            path: 'test-results/tec-validation-error.png',
            fullPage: true 
        });
        
        throw error;
    } finally {
        await browser.close();
    }
}

async function validateEnhancedFeatures(page) {
    console.log('🔍 Validating enhanced template features...');
    
    const features = {
        success_indicator: '.hvac-success-indicator',
        enhanced_styles: '#hvac-tec-enhanced-styles',
        excerpt_field: '#hvac_post_excerpt, textarea[name="post_excerpt"]',
        categories_section: '#hvac-categories-section, .hvac-categories-container',
        featured_image_section: '#hvac-featured-image-section, .hvac-featured-image-container', 
        tags_section: '#hvac-tags-section, .hvac-tags-container',
        enhanced_form: '.hvac-tec-enhanced-form',
        form_sections: '.hvac-form-section'
    };
    
    const results = {};
    let foundCount = 0;
    
    for (const [featureName, selector] of Object.entries(features)) {
        try {
            const element = page.locator(selector).first();
            const exists = await element.count() > 0;
            results[featureName] = exists;
            
            if (exists) {
                console.log(`✅ ${featureName}: Found`);
                foundCount++;
            } else {
                console.log(`❌ ${featureName}: Not found`);
            }
        } catch (error) {
            results[featureName] = false;
            console.log(`❌ ${featureName}: Error - ${error.message}`);
        }
    }
    
    const totalFeatures = Object.keys(features).length;
    const successRate = Math.round((foundCount / totalFeatures) * 100);
    
    console.log(`📊 Feature validation: ${foundCount}/${totalFeatures} features (${successRate}%)`);
    
    return {
        success: successRate >= 50, // Adjusted threshold
        successRate: successRate,
        results: results
    };
}

async function testFieldPopulation(page) {
    console.log('🎯 Testing field population capabilities...');
    
    try {
        const populationResult = await page.evaluate(() => {
            const results = {
                enhanced_system_available: false,
                basic_fields_accessible: false,
                field_count: 0,
                test_population: false
            };
            
            // Check for enhanced system
            if (window.HVACEnhancedFieldPopulation) {
                results.enhanced_system_available = true;
                console.log('Enhanced field population system found');
                
                try {
                    const testData = {
                        excerpt: 'Test excerpt for validation',
                        categories: [1],
                        tags: ['test', 'validation'],
                        featured_image: { id: 1, url: 'test.jpg' }
                    };
                    
                    const accessTest = window.HVACEnhancedFieldPopulation.testFieldAccess();
                    const populationTest = window.HVACEnhancedFieldPopulation.populateAllFields(testData);
                    
                    results.access_test = accessTest;
                    results.population_test = populationTest;
                    results.test_population = true;
                } catch (e) {
                    results.enhanced_error = e.message;
                }
            }
            
            // Check basic field accessibility
            const basicFields = [
                '#post_title',
                'textarea[name="content"]',
                '#hvac_post_excerpt',
                'input[name="tax_input[tribe_events_cat][]"]',
                '.hvac-categories-container',
                '.hvac-tags-container'
            ];
            
            let accessibleFields = 0;
            basicFields.forEach(selector => {
                if (document.querySelector(selector)) {
                    accessibleFields++;
                }
            });
            
            results.field_count = accessibleFields;
            results.basic_fields_accessible = accessibleFields > 0;
            
            return results;
        });
        
        console.log(`🔧 Enhanced System: ${populationResult.enhanced_system_available ? 'Available' : 'Not Available'}`);
        console.log(`📊 Accessible Fields: ${populationResult.field_count}`);
        
        if (populationResult.enhanced_system_available && populationResult.population_test) {
            const rate = populationResult.population_test.successRate || 0;
            console.log(`🎯 Population Success Rate: ${rate}%`);
        }
        
        return populationResult;
        
    } catch (error) {
        console.error('❌ Field population test failed:', error.message);
        return { error: error.message };
    }
}

function generateValidationReport(results) {
    const {
        working_url,
        enhanced_template,
        feature_validation,
        field_population,
        page_errors,
        console_messages
    } = results;
    
    let report = '\n📊 TEC ENHANCED TEMPLATE VALIDATION REPORT\n';
    report += '='.repeat(60) + '\n\n';
    
    // URL and Template Status
    report += `🌐 WORKING TEC URL: ${working_url}\n`;
    report += `🎨 ENHANCED TEMPLATE: ${enhanced_template ? '✅ ACTIVE' : '❌ NOT ACTIVE'}\n`;
    
    // Feature Validation
    if (feature_validation.success !== undefined) {
        report += `🔍 FEATURE VALIDATION: ${feature_validation.success ? '✅ PASSED' : '❌ FAILED'} (${feature_validation.successRate}%)\n`;
    }
    
    // Field Population
    if (field_population.enhanced_system_available) {
        report += '🎯 FIELD POPULATION: ✅ ENHANCED SYSTEM AVAILABLE\n';
        if (field_population.population_test) {
            const rate = field_population.population_test.successRate || 0;
            report += `   📈 Success Rate: ${rate}%\n`;
            if (rate === 100) {
                report += '   🎉 TARGET ACHIEVED: 100% field population!\n';
            }
        }
    } else {
        report += `🎯 FIELD POPULATION: ⚠️ BASIC ONLY (${field_population.field_count} fields accessible)\n`;
    }
    
    // Error Analysis
    if (page_errors.length > 0) {
        report += `\n❌ PAGE ERRORS (${page_errors.length}):\n`;
        page_errors.slice(0, 3).forEach((error, index) => {
            report += `   ${index + 1}. ${error.substring(0, 80)}...\n`;
        });
    } else {
        report += '\n✅ NO PAGE ERRORS DETECTED\n';
    }
    
    // Overall Assessment
    let overallScore = 0;
    if (working_url) overallScore += 25;
    if (enhanced_template) overallScore += 35;
    if (feature_validation.success) overallScore += 25;
    if (field_population.enhanced_system_available) overallScore += 15;
    
    report += `\n🏆 OVERALL ASSESSMENT: ${overallScore}% Complete\n`;
    
    if (overallScore >= 90) {
        report += '   🎉 EXCELLENT: Ready for production!\n';
    } else if (overallScore >= 75) {
        report += '   ✅ GOOD: Enhanced template working well\n';
    } else if (overallScore >= 50) {
        report += '   ⚠️ PARTIAL: Core functionality working\n';
    } else {
        report += '   ❌ POOR: Significant issues need resolution\n';
    }
    
    // Next Steps
    report += '\n📋 NEXT STEPS:\n';
    if (!enhanced_template) {
        report += '   • Verify template override installation\n';
        report += '   • Check theme template directory structure\n';
    }
    if (!field_population.enhanced_system_available) {
        report += '   • Verify enhanced JavaScript system loading\n';
    }
    if (page_errors.length > 0) {
        report += '   • Resolve JavaScript errors\n';
    }
    
    report += '\n📍 MANUAL TEST: Visit ' + (working_url ? `${config.baseUrl}${working_url}` : 'TEC event creation page');
    
    return report;
}

// Run validation
if (require.main === module) {
    runTECTemplateValidation()
        .then(report => {
            console.log('\n✅ TEC Template Validation completed');
            process.exit(0);
        })
        .catch(error => {
            console.error('\n❌ TEC Template Validation failed:', error.message);
            process.exit(1);
        });
}

module.exports = { runTECTemplateValidation };