/**
 * Performance Monitor
 * Tracks and reports extension performance metrics
 */

class PerformanceMonitor {
    constructor() {
        this._metrics = new Map();
        this._isRunning = false;
        this._startTime = null;
    }

    /**
     * Start monitoring
     */
    start() {
        this._isRunning = true;
        this._startTime = Date.now();
        console.log('📊 Performance Monitor started');
    }

    /**
     * Stop monitoring
     */
    stop() {
        this._isRunning = false;
        console.log('Performance Monitor stopped');
    }

    /**
     * Record a metric
     */
    recordMetric(name, value) {
        if (!this._metrics.has(name)) {
            this._metrics.set(name, []);
        }
        this._metrics.get(name).push({
            value,
            timestamp: Date.now()
        });
    }

    /**
     * Start timing an operation
     */
    startTimer(operationName) {
        return {
            name: operationName,
            start: Date.now()
        };
    }

    /**
     * End timing and record
     */
    endTimer(timer) {
        const duration = Date.now() - timer.start;
        this.recordMetric(`timer_${timer.name}`, duration);
        return duration;
    }

    /**
     * Get metrics summary
     */
    getMetrics() {
        const summary = {};
        for (const [name, values] of this._metrics.entries()) {
            const nums = values.map(v => v.value);
            summary[name] = {
                count: nums.length,
                avg: nums.reduce((a, b) => a + b, 0) / nums.length,
                min: Math.min(...nums),
                max: Math.max(...nums)
            };
        }
        return summary;
    }

    /**
     * Get uptime
     */
    getUptime() {
        if (!this._startTime) return 0;
        return Date.now() - this._startTime;
    }

    /**
     * Clear all metrics
     */
    clearMetrics() {
        this._metrics.clear();
    }
}

module.exports = { PerformanceMonitor };
