/**
 * Performance monitoring utilities for measuring and analyzing operation metrics
 */
/**
 * Monitor performance of operations with percentile tracking
 */
export class PerformanceMonitor {
    metrics = new Map();
    maxSamples;
    constructor(options) {
        this.maxSamples = options?.maxSamples ?? 1000;
    }
    /**
     * Measure and record duration of an async operation
     */
    async measure(name, fn) {
        const start = performance.now();
        try {
            return await fn();
        }
        finally {
            const duration = performance.now() - start;
            this.record(name, duration);
        }
    }
    /**
     * Record a metric directly
     */
    record(metric, duration) {
        const entries = this.metrics.get(metric) || [];
        entries.push(duration);
        // Keep last N samples
        if (entries.length > this.maxSamples) {
            entries.shift();
        }
        this.metrics.set(metric, entries);
    }
    /**
     * Get statistics for a metric
     */
    getStats(metric) {
        const entries = this.metrics.get(metric);
        if (!entries || entries.length === 0)
            return null;
        const sorted = [...entries].sort((a, b) => a - b);
        const count = sorted.length;
        return {
            avg: sorted.reduce((a, b) => a + b, 0) / count,
            p50: sorted[Math.floor(count * 0.5)] ?? 0,
            p95: sorted[Math.floor(count * 0.95)] ?? 0,
            p99: sorted[Math.floor(count * 0.99)] ?? 0,
            min: sorted[0] ?? 0,
            max: sorted[count - 1] ?? 0,
            count,
        };
    }
    /**
     * Get all metric names
     */
    getMetrics() {
        return [...this.metrics.keys()];
    }
    /**
     * Clear all metrics
     */
    clear() {
        this.metrics.clear();
    }
    /**
     * Export metrics as JSON
     */
    exportMetrics() {
        const result = {};
        for (const metric of this.metrics.keys()) {
            const stats = this.getStats(metric);
            if (stats) {
                result[metric] = stats;
            }
        }
        return result;
    }
}
/**
 * Global performance monitor instance
 */
let globalMonitor = null;
export function getPerformanceMonitor() {
    if (!globalMonitor) {
        globalMonitor = new PerformanceMonitor();
    }
    return globalMonitor;
}
/**
 * Helper to wrap any function with performance monitoring
 */
export function monitorFunction(fn, name) {
    const monitor = getPerformanceMonitor();
    const metricName = (name ?? fn.name) || 'anonymous';
    return (async (...args) => {
        return monitor.measure(metricName, async () => await fn(...args));
    });
}
//# sourceMappingURL=performance-monitor.js.map