"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateCorrelationId = generateCorrelationId;
exports.generateRunId = generateRunId;
exports.generateAgentId = generateAgentId;
exports.hashContent = hashContent;
exports.formatSSEEvent = formatSSEEvent;
exports.parseSSEEvent = parseSSEEvent;
exports.calculateMetrics = calculateMetrics;
exports.isValidEmail = isValidEmail;
exports.sanitizeForLogging = sanitizeForLogging;
exports.deepClone = deepClone;
exports.retry = retry;
exports.debounce = debounce;
exports.throttle = throttle;
const crypto_1 = __importDefault(require("crypto"));
function generateCorrelationId() {
    return crypto_1.default.randomUUID();
}
function generateRunId() {
    return crypto_1.default.randomUUID();
}
function generateAgentId() {
    return crypto_1.default.randomUUID();
}
function hashContent(content) {
    return crypto_1.default.createHash('sha256').update(content).digest('hex');
}
function formatSSEEvent(event, data, id) {
    let sse = `event: ${event}\n`;
    sse += `data: ${JSON.stringify(data)}\n`;
    if (id) {
        sse += `id: ${id}\n`;
    }
    sse += '\n';
    return sse;
}
function parseSSEEvent(eventString) {
    const lines = eventString.trim().split('\n');
    const result = {};
    for (const line of lines) {
        if (line.startsWith('event: ')) {
            result.event = line.slice(7);
        }
        else if (line.startsWith('data: ')) {
            try {
                result.data = JSON.parse(line.slice(6));
            }
            catch {
                result.data = line.slice(6);
            }
        }
        else if (line.startsWith('id: ')) {
            result.id = line.slice(4);
        }
    }
    return result.event && result.data ? result : null;
}
function calculateMetrics(values) {
    if (values.length === 0) {
        return { mean: 0, min: 0, max: 0, median: 0, p95: 0, p99: 0 };
    }
    const sorted = [...values].sort((a, b) => a - b);
    const mean = values.reduce((a, b) => a + b, 0) / values.length;
    const min = sorted[0];
    const max = sorted[sorted.length - 1];
    const median = sorted[Math.floor(sorted.length / 2)];
    const p95 = sorted[Math.floor(sorted.length * 0.95)];
    const p99 = sorted[Math.floor(sorted.length * 0.99)];
    return {
        mean: mean || 0,
        min: min || 0,
        max: max || 0,
        median: median || 0,
        p95: p95 || 0,
        p99: p99 || 0
    };
}
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}
function sanitizeForLogging(input) {
    return input
        .replace(/(password|token|secret|key|authorization)\s*[:=]\s*[^\s,}]+/gi, '$1: ***REDACTED***')
        .replace(/([0-9]{4}[-\s]?){4}/g, '****-****-****-****')
        .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, '***@***.***');
}
function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    if (obj instanceof Date) {
        return new Date(obj.getTime());
    }
    if (obj instanceof Array) {
        return obj.map(item => deepClone(item));
    }
    if (typeof obj === 'object') {
        const cloned = {};
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                cloned[key] = deepClone(obj[key]);
            }
        }
        return cloned;
    }
    return obj;
}
async function retry(fn, maxRetries = 3, baseDelay = 1000) {
    let lastError;
    for (let attempt = 0; attempt <= maxRetries; attempt++) {
        try {
            return await fn();
        }
        catch (error) {
            lastError = error;
            if (attempt === maxRetries) {
                throw lastError;
            }
            const delay = baseDelay * Math.pow(2, attempt);
            await new Promise(resolve => setTimeout(resolve, delay));
        }
    }
    throw lastError;
}
function debounce(func, wait) {
    let timeout;
    return (...args) => {
        clearTimeout(timeout);
        timeout = setTimeout(() => func(...args), wait);
    };
}
function throttle(func, limit) {
    let inThrottle;
    return (...args) => {
        if (!inThrottle) {
            func(...args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}
//# sourceMappingURL=utils.js.map