/**
 * TEC Template Test Data Manager
 * 
 * Comprehensive test data management for the TEC template test automation suite.
 * Handles setup, cleanup, and management of test data for all testing scenarios.
 * 
 * Features:
 * - Test user management and authentication
 * - Sample event data generation
 * - Media asset management for testing
 * - Database state management
 * - Test environment setup and teardown
 * 
 * @author Claude Code - Test Automation Specialist
 * @version 1.0.0
 * @date August 12, 2025
 */

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

// Test data configuration
const TEST_DATA_CONFIG = {
    // Environment settings
    environment: {
        staging: 'https://upskill-staging.measurequick.com',
        production: 'https://upskillhvac.com' // Use with extreme caution
    },
    
    // Test users
    testUsers: {
        trainer: {
            username: 'test_trainer',
            password: 'TestTrainer123!',
            email: 'test.trainer@hvactest.com',
            role: 'hvac_trainer'
        },
        masterTrainer: {
            username: 'test_master',
            password: 'TestMaster123!',
            email: 'test.master@hvactest.com',
            role: 'hvac_master_trainer'
        },
        fieldTestUser: {
            username: 'field_test_user',
            password: 'FieldTest123!',
            email: 'field.test@hvactest.com',
            role: 'hvac_trainer'
        }
    },
    
    // Test data storage
    storage: {
        dataDir: 'test-data',
        backupDir: 'test-data/backups',
        mediaDir: 'test-data/media',
        outputDir: 'test-results'
    },
    
    // Cleanup settings
    cleanup: {
        deleteTestEvents: true,
        preserveUserAccounts: true,
        cleanupMedia: false,
        maxTestEvents: 50 // Max test events to keep
    }
};

// Sample test data sets
const TEST_DATA_SETS = {
    // Basic event for simple testing
    basicEvent: {
        title: 'Basic HVAC Workshop - Test Event',
        content: 'Simple test event for basic functionality validation.',
        excerpt: 'Basic test event excerpt',
        startDate: '2025-09-30',
        endDate: '2025-09-30',
        startTime: '10:00',
        endTime: '15:00',
        cost: '150',
        categories: ['Training'],
        tags: ['basic', 'test', 'HVAC']
    },
    
    // Comprehensive event for full testing
    comprehensiveEvent: {
        title: 'Advanced HVAC Diagnostics & Performance Workshop - Comprehensive Test',
        content: `
            <h2>Comprehensive HVAC Training Program</h2>
            <p>This comprehensive workshop covers all aspects of modern HVAC diagnostics and performance optimization.</p>
            
            <h3>Learning Objectives:</h3>
            <ul>
                <li>Master advanced diagnostic equipment and techniques</li>
                <li>Understand electrical systems and troubleshooting methods</li>
                <li>Learn energy efficiency assessment and optimization</li>
                <li>Develop customer communication and service skills</li>
                <li>Gain hands-on experience with real-world scenarios</li>
            </ul>
            
            <h3>Workshop Modules:</h3>
            <ol>
                <li>Refrigeration Cycle Analysis</li>
                <li>Electrical Diagnostics</li>
                <li>Airflow Measurement</li>
                <li>Energy Efficiency</li>
                <li>Smart Technology Integration</li>
            </ol>
            
            <h3>Prerequisites:</h3>
            <p>Basic HVAC knowledge required. Participants should bring laptops and basic tools.</p>
            
            <blockquote>
                <p><strong>Certification:</strong> Continuing education credits available upon completion.</p>
            </blockquote>
        `,
        excerpt: 'Comprehensive HVAC diagnostics workshop covering advanced techniques, electrical troubleshooting, energy efficiency optimization, and smart technology integration.',
        startDate: '2025-10-15',
        endDate: '2025-10-16',
        startTime: '08:30',
        endTime: '17:30',
        cost: '599',
        categories: ['Advanced Training', 'Diagnostics', 'Certification'],
        tags: ['advanced', 'diagnostics', 'HVAC', 'certification', 'energy-efficiency', 'smart-technology'],
        venue: {
            name: 'HVAC Training Excellence Center',
            address: '2500 Technology Boulevard',
            city: 'Dallas',
            state: 'TX',
            zip: '75201',
            phone: '+1-214-555-0199',
            url: 'https://hvac-training-center.com'
        },
        organizer: {
            name: 'Professional HVAC Training Solutions',
            email: 'training@hvac-pro-solutions.com',
            phone: '+1-214-555-0299',
            website: 'https://hvac-pro-solutions.com'
        }
    },
    
    // Performance stress test event
    performanceStressEvent: {
        title: 'HVAC Performance Stress Test Event - Large Content and Complex Structure',
        content: this.generateLargeContent(),
        excerpt: 'Performance stress test event with large content size and complex structure for testing template performance under load.',
        startDate: '2025-11-01',
        endDate: '2025-11-03',
        startTime: '07:00',
        endTime: '18:00',
        cost: '1299',
        categories: ['Intensive Training', 'Performance Testing', 'Advanced Diagnostics', 'Certification'],
        tags: ['performance', 'stress-test', 'intensive', 'advanced', 'HVAC', 'diagnostics', 'certification', 'workshop', 'training', 'professional']
    },
    
    // Minimal event for compatibility testing
    minimalEvent: {
        title: 'Minimal Test Event',
        content: 'Minimal content for compatibility testing.',
        startDate: '2025-12-01',
        endDate: '2025-12-01',
        startTime: '14:00',
        endTime: '16:00'
    }
};

/**
 * Test Data Manager Class
 */
class TestDataManager {
    constructor(environment = 'staging') {
        this.environment = environment;
        this.baseUrl = TEST_DATA_CONFIG.environment[environment];
        this.createdEvents = [];
        this.uploadedMedia = [];
        this.testSessions = [];
        
        this.ensureDirectories();
    }
    
    /**
     * Setup test environment
     */
    async setupTestEnvironment() {
        console.log('🛠️ SETTING UP TEST ENVIRONMENT');
        console.log('==============================');
        console.log(`Environment: ${this.environment}`);
        console.log(`Base URL: ${this.baseUrl}`);
        console.log('');
        
        try {
            // Verify test user access
            await this.verifyTestUsers();
            
            // Prepare test media
            await this.prepareTestMedia();
            
            // Clean up old test data
            await this.cleanupOldTestData();
            
            // Create test data sets
            await this.createTestDataSets();
            
            console.log('✅ Test environment setup complete');
            return true;
            
        } catch (error) {
            console.error('❌ Test environment setup failed:', error.message);
            throw error;
        }
    }
    
    /**
     * Verify test user access
     */
    async verifyTestUsers() {
        console.log('👤 Verifying test user access...');
        
        const browser = await chromium.launch({ headless: true });
        const context = await browser.newContext();
        const page = await context.newPage();
        
        try {
            for (const [userType, userConfig] of Object.entries(TEST_DATA_CONFIG.testUsers)) {
                try {
                    // Navigate to login
                    await page.goto(`${this.baseUrl}/training-login/`);
                    await page.waitForLoadState('networkidle');
                    
                    // Attempt login
                    await page.fill('input[name="log"]', userConfig.username);
                    await page.fill('input[name="pwd"]', userConfig.password);
                    await page.click('input[type="submit"]');
                    await page.waitForLoadState('networkidle');
                    
                    // Check for successful login
                    const loginError = await page.locator('.login_error, .error').count();
                    if (loginError > 0) {
                        throw new Error(`Login failed for ${userType}`);
                    }
                    
                    // Verify dashboard access
                    const dashboardUrl = userType === 'masterTrainer' ? '/master-trainer/master-dashboard/' : '/trainer/dashboard/';
                    await page.goto(`${this.baseUrl}${dashboardUrl}`);
                    await page.waitForTimeout(2000);
                    
                    const dashboardTitle = await page.title();
                    if (!dashboardTitle.includes('Dashboard')) {
                        throw new Error(`Dashboard not accessible for ${userType}`);
                    }
                    
                    console.log(`   ✅ ${userType}: Login successful, dashboard accessible`);
                    
                } catch (error) {
                    console.log(`   ❌ ${userType}: ${error.message}`);
                    throw new Error(`Test user verification failed for ${userType}: ${error.message}`);
                }
            }
            
        } finally {
            await browser.close();
        }
    }
    
    /**
     * Prepare test media assets
     */
    async prepareTestMedia() {
        console.log('🖼️ Preparing test media assets...');
        
        const mediaAssets = [
            {
                name: 'test-hvac-workshop.jpg',
                type: 'image/jpeg',
                size: '1920x1080',
                description: 'HVAC workshop test image'
            },
            {
                name: 'test-training-center.jpg',
                type: 'image/jpeg',
                size: '1200x800',
                description: 'Training center test image'
            },
            {
                name: 'test-equipment.jpg',
                type: 'image/jpeg',
                size: '800x600',
                description: 'HVAC equipment test image'
            }
        ];
        
        for (const asset of mediaAssets) {
            const assetPath = path.join(TEST_DATA_CONFIG.storage.mediaDir, asset.name);
            
            if (!fs.existsSync(assetPath)) {
                // Create a simple test image (placeholder)
                const svgContent = this.generateTestImage(asset.size, asset.description);
                fs.writeFileSync(assetPath.replace('.jpg', '.svg'), svgContent);
                console.log(`   📁 Created test asset: ${asset.name}`);
            } else {
                console.log(`   ✅ Test asset exists: ${asset.name}`);
            }
        }
    }
    
    /**
     * Clean up old test data
     */
    async cleanupOldTestData() {
        console.log('🧹 Cleaning up old test data...');
        
        if (!TEST_DATA_CONFIG.cleanup.deleteTestEvents) {
            console.log('   ⚠️ Test event cleanup disabled in config');
            return;
        }
        
        const browser = await chromium.launch({ headless: true });
        const context = await browser.newContext();
        const page = await context.newPage();
        
        try {
            // Login as test user
            await this.loginAsTestUser(page, 'trainer');
            
            // Navigate to events management
            await page.goto(`${this.baseUrl}/trainer/dashboard/`);
            await page.waitForTimeout(2000);
            
            // Look for test events to clean up
            // This would need to be implemented based on how events are managed
            console.log('   ℹ️ Test event cleanup - implementation needed based on event management UI');
            
        } finally {
            await browser.close();
        }
    }
    
    /**
     * Create test data sets
     */
    async createTestDataSets() {
        console.log('📝 Creating test data sets...');
        
        // Save test data sets to files for reference
        const dataSetsFile = path.join(TEST_DATA_CONFIG.storage.dataDir, 'test-data-sets.json');
        fs.writeFileSync(dataSetsFile, JSON.stringify(TEST_DATA_SETS, null, 2));
        
        console.log(`   💾 Test data sets saved to: ${dataSetsFile}`);
        
        // Create field mapping reference
        const fieldMappingFile = path.join(TEST_DATA_CONFIG.storage.dataDir, 'field-mapping.json');
        const fieldMapping = this.generateFieldMapping();
        fs.writeFileSync(fieldMappingFile, JSON.stringify(fieldMapping, null, 2));
        
        console.log(`   🗺️ Field mapping saved to: ${fieldMappingFile}`);
    }
    
    /**
     * Get test data by type
     */
    getTestData(dataType) {
        if (!TEST_DATA_SETS[dataType]) {
            throw new Error(`Test data type '${dataType}' not found`);
        }
        
        return JSON.parse(JSON.stringify(TEST_DATA_SETS[dataType])); // Deep clone
    }
    
    /**
     * Create random test event data
     */
    generateRandomEventData() {
        const eventTypes = ['Workshop', 'Seminar', 'Training', 'Certification', 'Conference'];
        const topics = ['HVAC Diagnostics', 'Energy Efficiency', 'Smart Technology', 'Electrical Systems', 'Refrigeration'];
        const levels = ['Basic', 'Intermediate', 'Advanced', 'Expert'];
        
        const randomType = eventTypes[Math.floor(Math.random() * eventTypes.length)];
        const randomTopic = topics[Math.floor(Math.random() * topics.length)];
        const randomLevel = levels[Math.floor(Math.random() * levels.length)];
        
        const randomId = Math.floor(Math.random() * 1000000);
        
        return {
            title: `${randomLevel} ${randomTopic} ${randomType} - Test ${randomId}`,
            content: `This is a randomly generated test event for ${randomTopic.toLowerCase()} training. Content ID: ${randomId}`,
            excerpt: `${randomLevel} ${randomTopic.toLowerCase()} ${randomType.toLowerCase()} for testing purposes.`,
            startDate: this.getRandomFutureDate(),
            endDate: this.getRandomFutureDate(1),
            startTime: this.getRandomTime(),
            endTime: this.getRandomTime(true),
            cost: Math.floor(Math.random() * 500 + 100).toString(),
            categories: [randomTopic],
            tags: ['test', randomLevel.toLowerCase(), randomTopic.toLowerCase().replace(' ', '-')]
        };
    }
    
    /**
     * Login as test user
     */
    async loginAsTestUser(page, userType = 'trainer') {
        const userConfig = TEST_DATA_CONFIG.testUsers[userType];
        if (!userConfig) {
            throw new Error(`Test user type '${userType}' not found`);
        }
        
        await page.goto(`${this.baseUrl}/training-login/`);
        await page.waitForLoadState('networkidle');
        
        await page.fill('input[name="log"]', userConfig.username);
        await page.fill('input[name="pwd"]', userConfig.password);
        await page.click('input[type="submit"]');
        await page.waitForLoadState('networkidle');
        
        // Verify login success
        const loginError = await page.locator('.login_error, .error').count();
        if (loginError > 0) {
            throw new Error(`Login failed for test user: ${userType}`);
        }
    }
    
    /**
     * Cleanup test environment
     */
    async cleanupTestEnvironment() {
        console.log('🧹 CLEANING UP TEST ENVIRONMENT');
        console.log('===============================');
        
        try {
            // Clean up created events
            if (TEST_DATA_CONFIG.cleanup.deleteTestEvents && this.createdEvents.length > 0) {
                await this.deleteCreatedEvents();
            }
            
            // Clean up uploaded media
            if (TEST_DATA_CONFIG.cleanup.cleanupMedia && this.uploadedMedia.length > 0) {
                await this.deleteUploadedMedia();
            }
            
            // Save session data for reference
            await this.saveSessionData();
            
            console.log('✅ Test environment cleanup complete');
            
        } catch (error) {
            console.error('❌ Test environment cleanup failed:', error.message);
        }
    }
    
    /**
     * Generate test image SVG
     */
    generateTestImage(size, description) {
        const [width, height] = size.split('x').map(Number);
        
        return `
            <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
                <rect width="100%" height="100%" fill="#e0e0e0"/>
                <text x="50%" y="40%" dominant-baseline="middle" text-anchor="middle" font-family="Arial" font-size="24" fill="#666">
                    TEST IMAGE
                </text>
                <text x="50%" y="60%" dominant-baseline="middle" text-anchor="middle" font-family="Arial" font-size="16" fill="#888">
                    ${description}
                </text>
                <text x="50%" y="75%" dominant-baseline="middle" text-anchor="middle" font-family="Arial" font-size="14" fill="#aaa">
                    ${size}
                </text>
            </svg>
        `;
    }
    
    /**
     * Generate field mapping reference
     */
    generateFieldMapping() {
        return {
            wordpress_core: {
                title: { selector: '#title, input[name="post_title"]', type: 'text' },
                content: { selector: '#content, #tcepostcontent', type: 'tinymce' },
                excerpt: { selector: '#hvac_post_excerpt', type: 'textarea' },
                featured_image: { selector: '#hvac_featured_image_id', type: 'hidden' }
            },
            taxonomies: {
                categories: { selector: 'input[name="tax_input[tribe_events_cat][]"]', type: 'checkbox' },
                tags: { selector: '#hvac_tags_input', type: 'tags' }
            },
            tec_core: {
                start_date: { selector: '#EventStartDate', type: 'date' },
                end_date: { selector: '#EventEndDate', type: 'date' },
                start_time: { selector: '#EventStartTime', type: 'time' },
                end_time: { selector: '#EventEndTime', type: 'time' },
                cost: { selector: '#EventCost', type: 'number' },
                url: { selector: '#EventURL', type: 'url' }
            },
            venue: {
                name: { selector: '#VenueVenue', type: 'text' },
                address: { selector: '#VenueAddress', type: 'text' },
                city: { selector: '#VenueCity', type: 'text' },
                state: { selector: '#VenueStateProvince', type: 'text' },
                zip: { selector: '#VenueZip', type: 'text' },
                phone: { selector: '#VenuePhone', type: 'tel' },
                url: { selector: '#VenueURL', type: 'url' }
            },
            organizer: {
                name: { selector: '#OrganizerOrganizer', type: 'text' },
                email: { selector: '#OrganizerEmail', type: 'email' },
                phone: { selector: '#OrganizerPhone', type: 'tel' },
                website: { selector: '#OrganizerWebsite', type: 'url' }
            }
        };
    }
    
    /**
     * Generate large content for performance testing
     */
    static generateLargeContent() {
        return `
            <h1>Comprehensive HVAC Performance and Diagnostics Training Program</h1>
            
            <h2>Executive Summary</h2>
            <p>This intensive training program is designed to provide HVAC professionals with comprehensive knowledge and practical skills in advanced diagnostics, performance optimization, and cutting-edge technology integration. The curriculum covers everything from fundamental principles to advanced troubleshooting techniques.</p>
            
            <h2>Program Overview</h2>
            <p>Our comprehensive HVAC training program spans multiple days and covers an extensive range of topics essential for modern HVAC professionals. Participants will gain hands-on experience with the latest diagnostic equipment, learn advanced troubleshooting methodologies, and understand the integration of smart technology in HVAC systems.</p>
            
            <h3>Day 1: Fundamentals and Diagnostics</h3>
            <h4>Morning Session (8:30 AM - 12:00 PM)</h4>
            <ul>
                <li>HVAC system fundamentals review</li>
                <li>Refrigeration cycle analysis and optimization</li>
                <li>Psychrometrics and comfort principles</li>
                <li>Load calculation methodologies</li>
                <li>System design considerations</li>
            </ul>
            
            <h4>Afternoon Session (1:00 PM - 5:30 PM)</h4>
            <ul>
                <li>Advanced diagnostic equipment operation</li>
                <li>Manifold gauge set techniques</li>
                <li>Digital multimeter applications</li>
                <li>Refrigerant leak detection methods</li>
                <li>Superheat and subcooling calculations</li>
            </ul>
            
            <h3>Day 2: Electrical Systems and Troubleshooting</h3>
            <h4>Morning Session (8:30 AM - 12:00 PM)</h4>
            <ul>
                <li>Electrical fundamentals for HVAC</li>
                <li>Motor analysis and testing procedures</li>
                <li>Capacitor testing and replacement</li>
                <li>Relay and contactor troubleshooting</li>
                <li>Control circuit analysis</li>
            </ul>
            
            <h4>Afternoon Session (1:00 PM - 5:30 PM)</h4>
            <ul>
                <li>Advanced electrical troubleshooting</li>
                <li>Variable frequency drive (VFD) operation</li>
                <li>Electronic expansion valve diagnostics</li>
                <li>Thermostat and sensor calibration</li>
                <li>Wiring diagram interpretation</li>
            </ul>
            
            <h3>Day 3: Performance Optimization and Smart Technology</h3>
            <h4>Morning Session (8:30 AM - 12:00 PM)</h4>
            <ul>
                <li>Energy efficiency assessment techniques</li>
                <li>Performance benchmarking and optimization</li>
                <li>Airflow measurement and balancing</li>
                <li>Duct system evaluation and sealing</li>
                <li>Filter selection and maintenance strategies</li>
            </ul>
            
            <h4>Afternoon Session (1:00 PM - 5:30 PM)</h4>
            <ul>
                <li>Smart thermostat installation and configuration</li>
                <li>IoT device integration in HVAC systems</li>
                <li>Remote monitoring and diagnostics</li>
                <li>Predictive maintenance technologies</li>
                <li>Data analysis and reporting techniques</li>
            </ul>
            
            <h2>Learning Objectives</h2>
            <p>Upon completion of this comprehensive training program, participants will be able to:</p>
            
            <ol>
                <li><strong>Perform Advanced Diagnostics:</strong> Utilize sophisticated diagnostic equipment to identify and resolve complex HVAC system issues efficiently and accurately.</li>
                <li><strong>Analyze Electrical Systems:</strong> Diagnose and repair electrical components, including motors, capacitors, relays, and advanced control systems.</li>
                <li><strong>Optimize System Performance:</strong> Implement energy efficiency measures and performance optimization strategies to maximize system effectiveness.</li>
                <li><strong>Integrate Smart Technology:</strong> Install, configure, and maintain smart HVAC components and IoT devices for enhanced system control and monitoring.</li>
                <li><strong>Conduct Energy Assessments:</strong> Perform comprehensive energy audits and recommend improvements for residential and commercial HVAC systems.</li>
                <li><strong>Interpret Complex Data:</strong> Analyze system performance data, identify trends, and make informed recommendations for system improvements.</li>
                <li><strong>Implement Preventive Maintenance:</strong> Develop and execute comprehensive maintenance programs to ensure optimal system performance and longevity.</li>
                <li><strong>Communicate Effectively:</strong> Present findings and recommendations to customers in a clear, professional manner that builds trust and confidence.</li>
            </ol>
            
            <h2>Prerequisites and Requirements</h2>
            <h3>Educational Background</h3>
            <p>Participants should have a solid foundation in HVAC principles and at least 2 years of hands-on experience in the field. Basic understanding of electrical circuits and mechanical systems is essential.</p>
            
            <h3>Required Equipment</h3>
            <p>Each participant should bring the following equipment:</p>
            <ul>
                <li>Laptop computer with WiFi capability</li>
                <li>Basic hand tools (screwdrivers, pliers, wire strippers)</li>
                <li>Digital multimeter</li>
                <li>Safety equipment (safety glasses, work gloves)</li>
                <li>Calculator</li>
                <li>Notebook and writing materials</li>
            </ul>
            
            <h3>Safety Requirements</h3>
            <p>All participants must adhere to strict safety protocols throughout the training. Personal protective equipment is mandatory during hands-on sessions.</p>
            
            <h2>Certification and Continuing Education</h2>
            <p>Upon successful completion of the program, participants will receive:</p>
            <ul>
                <li>Certificate of completion from HVAC Training Excellence</li>
                <li>20 hours of continuing education credit</li>
                <li>Access to online resources and follow-up materials</li>
                <li>Invitation to advanced specialist training programs</li>
                <li>One year of email support for technical questions</li>
            </ul>
            
            <h2>Instructor Information</h2>
            <p>This program is led by industry-recognized experts with decades of combined experience in HVAC design, installation, and service. Our instructors hold multiple industry certifications and stay current with the latest technology and best practices.</p>
            
            <h2>Registration and Logistics</h2>
            <h3>Training Facility</h3>
            <p>The training takes place at our state-of-the-art facility equipped with the latest HVAC equipment and diagnostic tools. The facility features comfortable classroom spaces, hands-on training labs, and all necessary safety equipment.</p>
            
            <h3>Meals and Refreshments</h3>
            <p>Continental breakfast, lunch, and afternoon refreshments are provided each day. Special dietary requirements can be accommodated with advance notice.</p>
            
            <h3>Parking and Transportation</h3>
            <p>Free parking is available on-site. The facility is easily accessible by public transportation, and detailed directions will be provided upon registration.</p>
            
            <h2>Follow-up and Support</h2>
            <p>Our commitment to your success doesn't end when the training concludes. We provide ongoing support through:</p>
            <ul>
                <li>Online resource portal with downloadable materials</li>
                <li>Monthly webinars on advanced topics</li>
                <li>Technical support hotline</li>
                <li>Access to equipment manufacturer representatives</li>
                <li>Networking opportunities with other professionals</li>
            </ul>
            
            <blockquote>
                <p><strong>Note:</strong> This comprehensive content is designed to test template performance with large, complex HTML content including multiple headings, lists, and formatted text sections.</p>
            </blockquote>
        `;
    }
    
    /**
     * Get random future date
     */
    getRandomFutureDate(daysOffset = 0) {
        const today = new Date();
        const futureDate = new Date(today);
        futureDate.setDate(today.getDate() + Math.floor(Math.random() * 90) + 30 + daysOffset); // 30-120 days in future
        return futureDate.toISOString().split('T')[0];
    }
    
    /**
     * Get random time
     */
    getRandomTime(isEndTime = false) {
        const startHour = isEndTime ? 14 : 8; // End times start from 2 PM, start times from 8 AM
        const endHour = isEndTime ? 20 : 13;  // End times until 8 PM, start times until 1 PM
        const hour = Math.floor(Math.random() * (endHour - startHour)) + startHour;
        const minute = Math.random() < 0.5 ? '00' : '30';
        return `${hour.toString().padStart(2, '0')}:${minute}`;
    }
    
    /**
     * Ensure required directories exist
     */
    ensureDirectories() {
        Object.values(TEST_DATA_CONFIG.storage).forEach(dir => {
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
        });
    }
    
    /**
     * Save session data
     */
    async saveSessionData() {
        const sessionData = {
            timestamp: new Date().toISOString(),
            environment: this.environment,
            createdEvents: this.createdEvents,
            uploadedMedia: this.uploadedMedia,
            testSessions: this.testSessions
        };
        
        const sessionFile = path.join(TEST_DATA_CONFIG.storage.dataDir, 'last-session.json');
        fs.writeFileSync(sessionFile, JSON.stringify(sessionData, null, 2));
    }
    
    /**
     * Delete created events (placeholder)
     */
    async deleteCreatedEvents() {
        console.log(`   🗑️ Cleaning up ${this.createdEvents.length} created events...`);
        // Implementation would depend on WordPress/TEC API or admin interface
        console.log('   ℹ️ Event deletion - implementation needed based on WordPress admin interface');
    }
    
    /**
     * Delete uploaded media (placeholder)
     */
    async deleteUploadedMedia() {
        console.log(`   🗑️ Cleaning up ${this.uploadedMedia.length} uploaded media files...`);
        // Implementation would depend on WordPress media library API
        console.log('   ℹ️ Media cleanup - implementation needed based on WordPress media library');
    }
}

/**
 * Run test data setup
 */
async function setupTestData(environment = 'staging') {
    const dataManager = new TestDataManager(environment);
    
    try {
        await dataManager.setupTestEnvironment();
        console.log('\n✅ Test data setup completed successfully');
        return dataManager;
    } catch (error) {
        console.error('\n❌ Test data setup failed:', error.message);
        throw error;
    }
}

/**
 * Run test data cleanup
 */
async function cleanupTestData(dataManager) {
    try {
        await dataManager.cleanupTestEnvironment();
        console.log('\n✅ Test data cleanup completed successfully');
    } catch (error) {
        console.error('\n❌ Test data cleanup failed:', error.message);
    }
}

// Export for module usage
module.exports = { 
    TestDataManager, 
    setupTestData, 
    cleanupTestData, 
    TEST_DATA_CONFIG, 
    TEST_DATA_SETS 
};

// Run if called directly
if (require.main === module) {
    const command = process.argv[2];
    const environment = process.argv[3] || 'staging';
    
    if (command === 'setup') {
        setupTestData(environment);
    } else if (command === 'cleanup') {
        const dataManager = new TestDataManager(environment);
        cleanupTestData(dataManager);
    } else {
        console.log('Usage: node test-data-manager.js [setup|cleanup] [staging|production]');
    }
}