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

async function testGeocodingTrigger() {
    console.log('🗺️ TRIGGERING MANUAL GEOCODING');
    console.log('================================================================================');
    
    const browser = await chromium.launch({ headless: false });
    const context = await browser.newContext();
    const page = await context.newPage();
    
    try {
        // Login as master trainer
        console.log('📝 Logging in as master trainer...');
        await page.goto('https://upskill-staging.measurequick.com/wp-login.php');
        await page.fill('#user_login', 'JoeMedosch@gmail.com');
        await page.fill('#user_pass', 'JoeTrainer2025@');
        await page.click('#wp-submit');
        await page.waitForURL('**/master-trainer/master-dashboard/**', { timeout: 15000 });
        console.log('✅ Master trainer login successful');
        
        // Go to a page with AJAX access
        await page.goto('https://upskill-staging.measurequick.com/trainer/profile/');
        await page.waitForLoadState('networkidle');
        
        // Get initial statistics
        console.log('📊 Getting initial geocoding statistics...');
        const initialStats = await page.evaluate(async () => {
            if (typeof hvac_ajax === 'undefined') {
                return { error: 'hvac_ajax not available' };
            }
            
            try {
                const response = await fetch(hvac_ajax.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'hvac_get_geocoding_stats',
                        nonce: hvac_ajax.nonce
                    })
                });
                
                const data = await response.json();
                return data;
            } catch (e) {
                return { error: 'Exception: ' + e.message };
            }
        });
        
        console.log('📋 Initial statistics result:', initialStats);
        
        if (initialStats.success) {
            const stats = initialStats.data;
            console.log(`   Total Profiles: ${stats.total_profiles}`);
            console.log(`   Currently Geocoded: ${stats.geocoded_profiles}`);
            console.log(`   Public Profiles: ${stats.public_profiles}`);
            console.log(`   Sync Issues: ${stats.sync_issues}`);
        }
        
        // Trigger geocoding
        console.log('\n🚀 Triggering manual geocoding...');
        console.log('⏱️ This may take several minutes...');
        
        const geocodingResult = await page.evaluate(async () => {
            if (typeof hvac_ajax === 'undefined') {
                return { error: 'hvac_ajax not available' };
            }
            
            try {
                const response = await fetch(hvac_ajax.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'hvac_trigger_geocoding',
                        nonce: hvac_ajax.nonce
                    })
                });
                
                const data = await response.json();
                return data;
            } catch (e) {
                return { error: 'Exception: ' + e.message };
            }
        });
        
        console.log('\n📋 Geocoding results:', geocodingResult);
        
        if (geocodingResult.success) {
            const results = geocodingResult.data;
            console.log('\n🎉 GEOCODING COMPLETED SUCCESSFULLY!');
            console.log('================================================================================');
            console.log(`📊 SUMMARY:`);
            console.log(`   Total Profiles Processed: ${results.total_profiles}`);
            console.log(`   Successfully Geocoded: ${results.geocoded_count}`);
            console.log(`   Skipped (no address): ${results.skipped_count}`);
            console.log(`   Errors: ${results.error_count}`);
            console.log(`   Duration: ${results.duration} seconds`);
            console.log(`   API Key Valid: ${results.api_key_valid ? 'Yes' : 'No'}`);
            
            console.log('\n📍 PROFILE DETAILS:');
            if (results.details && results.details.length > 0) {
                results.details.forEach(detail => {
                    const status = detail.status === 'geocoded' ? '✅' : 
                                 detail.status === 'already_geocoded' ? '✅' :
                                 detail.status === 'no_address' ? '⚠️' : '❌';
                    
                    console.log(`   ${status} ${detail.title} (ID: ${detail.id})`);
                    
                    if (detail.address) {
                        console.log(`      Address: ${detail.address}`);
                    }
                    
                    if (detail.coordinates) {
                        console.log(`      Coordinates: ${detail.coordinates.lat}, ${detail.coordinates.lng}`);
                    }
                    
                    if (detail.message) {
                        console.log(`      Message: ${detail.message}`);
                    }
                });
            }
            
        } else {
            console.log('\n❌ GEOCODING FAILED:');
            console.log('   Error:', geocodingResult.data || geocodingResult.error);
        }
        
        // Get final statistics
        console.log('\n📈 Getting final statistics...');
        const finalStats = await page.evaluate(async () => {
            try {
                const response = await fetch(hvac_ajax.ajax_url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'hvac_get_geocoding_stats',
                        nonce: hvac_ajax.nonce
                    })
                });
                
                const data = await response.json();
                return data;
            } catch (e) {
                return { error: 'Exception: ' + e.message };
            }
        });
        
        if (finalStats.success) {
            const stats = finalStats.data;
            console.log('📊 Final Statistics:');
            console.log(`   Total Profiles: ${stats.total_profiles}`);
            console.log(`   Now Geocoded: ${stats.geocoded_profiles}`);
            
            if (initialStats.success) {
                const improvement = stats.geocoded_profiles - initialStats.data.geocoded_profiles;
                console.log(`   Improvement: +${improvement}`);
            }
            
            if (stats.total_profiles > 0) {
                const geocodedPercent = Math.round((stats.geocoded_profiles / stats.total_profiles) * 100);
                console.log(`   Geocoding Coverage: ${geocodedPercent}%`);
            }
        }
        
        await page.screenshot({ path: 'geocoding-completed.png', fullPage: true });
        
        console.log('\n================================================================================');
        console.log('🎯 GEOCODING TRIGGER TEST COMPLETE');
        
    } catch (error) {
        console.error('❌ Error during geocoding trigger:', error);
        await page.screenshot({ path: 'geocoding-trigger-error.png', fullPage: true });
    } finally {
        await browser.close();
    }
}

testGeocodingTrigger();