/**
 * Galaxy Strike Online - Debug Logger
 * Enhanced debugging that integrates with existing Logger system
 */

class DebugLogger {
    constructor() {
        this.debugEnabled = true; // Always enabled
        this.startTime = performance.now();
        this.stepTimers = new Map();
        this.debugLogs = []; // Store logs in memory
        this.maxLogs = 1000; // Limit memory usage
        
        // Use the existing logger if available
        this.logger = window.logger || null;
        
        // Log initialization
        this.log('=== DEBUG SESSION STARTED ===');
    }
    
    async log(message, data = null) {
        const timestamp = new Date().toISOString();
        const stackTrace = new Error().stack;
        
        // Build performance object
        const performanceData = {
            elapsed: `${(performance.now() - this.startTime).toFixed(2)}ms`,
            memory: performance.memory ? {
                used: `${(performance.memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}MB`,
                total: `${(performance.memory.totalJSHeapSize / 1024 / 1024).toFixed(2)}MB`
            } : null
        };
        
        // Create single formatted log message
        let logMessage = `[DEBUG] ${message}`;
        if (data) {
            logMessage += `\n${JSON.stringify(data, null, 2)}`;
        }
        if (performanceData) {
            logMessage += `\n[PERF] ${performanceData.elapsed} | Memory: ${performanceData.memory?.used || 'N/A'}/${performanceData.memory?.total || 'N/A'}`;
        }
        
        // Add to memory logs
        const logEntry = {
            timestamp: timestamp,
            message: message,
            data: data ? JSON.stringify(data, null, 2) : '',
            stackTrace: stackTrace ? stackTrace.split('\n').slice(0, 3).join('\n') : '',
            performance: performanceData
        };
        this.debugLogs.push(logEntry);
        
        // Limit memory usage
        if (this.debugLogs.length > this.maxLogs) {
            this.debugLogs.shift();
        }
        
        // Always log to console
        console.log(`[DEBUG] ${message}`, data || '');
        
        // Log performance data to console
        if (performanceData.memory) {
            console.log(`[PERF] ${performanceData.elapsed} | Memory: ${performanceData.memory.used}/${performanceData.memory.total}`);
        }
        
        // Use existing logger if available
        if (this.logger) {
            try {
                await this.logger.debug(logMessage);
            } catch (error) {
                console.error('[DEBUG LOGGER] Failed to log via existing logger:', error);
            }
        } else {
            // Fallback to electronAPI log
            if (window.electronAPI && window.electronAPI.log) {
                window.electronAPI.log('debug', logMessage);
            }
        }
    }
    
    async startStep(stepName) {
        this.stepTimers.set(stepName, performance.now());
        await this.log(`STEP START: ${stepName}`, {
            type: 'step_start',
            step: stepName,
            elapsed: '0ms'
        });
    }
    
    async endStep(stepName, data = null) {
        const startTime = this.stepTimers.get(stepName);
        const duration = startTime ? (performance.now() - startTime).toFixed(2) : 'N/A';
        
        this.stepTimers.delete(stepName);
        await this.log(`STEP END: ${stepName}`, {
            type: 'step_end',
            step: stepName,
            duration: `${duration}ms`,
            data
        });
    }
    
    async logStep(stepName, data = null) {
        await this.log(`STEP: ${stepName}`, {
            type: 'step',
            step: stepName,
            data
        });
    }
    
    getLogs() {
        return this.debugLogs;
    }
    
    exportLogs() {
        const logText = this.debugLogs.map(entry => 
            `[${entry.timestamp}] ${entry.message}${entry.data ? '\n' + entry.data : ''}${entry.performance ? '\nPerf: ' + entry.performance.elapsed : ''}`
        ).join('\n\n');
        
        return logText;
    }
    
    clearLogs() {
        this.debugLogs = [];
        this.log('=== LOGS CLEARED ===');
    }
    
    async shutdown() {
        await this.log('=== DEBUG SESSION ENDING ===');
        await this.log('SESSION SUMMARY', {
            totalLogs: this.debugLogs.length,
            sessionDuration: `${(performance.now() - this.startTime).toFixed(2)}ms`
        });
        
        // No need to finalize files - the existing Logger handles that
        console.log('[DEBUG LOGGER] Session ended cleanly');
    }
    
    // Convenience methods for specific logging types
    async info(message, data = null) {
        await this.log(`[INFO] ${message}`, data);
    }
    
    async error(message, data = null) {
        await this.log(`[ERROR] ${message}`, data);
    }
    
    async warn(message, data = null) {
        await this.log(`[WARN] ${message}`, data);
    }
    
    async errorEvent(error, context = 'Unknown') {
        await this.error(`Error in ${context}`, {
            name: error.name,
            message: error.message,
            stack: error.stack,
            timestamp: new Date().toISOString()
        });
    }
}

// Global debug logger instance
window.debugLogger = new DebugLogger();
