"use strict";
/**
 * Retry Logic for AI API Calls
 *
 * Implements exponential backoff for rate limit handling.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeAnthropicRequestWithRetry = makeAnthropicRequestWithRetry;
exports.makeOpenAIRequestWithRetry = makeOpenAIRequestWithRetry;
/**
 * Helper function to make Anthropic API calls with retry logic for rate limiting
 * Implements exponential backoff for 429 (rate limit) errors
 */
async function makeAnthropicRequestWithRetry(requestFn, maxRetries = 3, initialDelayMs = 1000) {
    let lastError = null;
    for (let attempt = 0; attempt <= maxRetries; attempt++) {
        try {
            return await requestFn();
        }
        catch (error) {
            lastError = error;
            // Check if it's a rate limit error (429)
            const isRateLimit = error?.status === 429 || error?.message?.includes('rate limit');
            if (isRateLimit && attempt < maxRetries) {
                // Exponential backoff: 1s, 2s, 4s
                const delayMs = initialDelayMs * Math.pow(2, attempt);
                console.log(`[AI Validation] Rate limit hit, retrying in ${delayMs}ms (attempt ${attempt + 1}/${maxRetries})`);
                await new Promise(resolve => setTimeout(resolve, delayMs));
                continue;
            }
            // If not rate limit or max retries reached, throw
            throw error;
        }
    }
    throw lastError || new Error('Max retries exceeded');
}
/**
 * Helper to make OpenAI requests with retry logic for rate limits
 */
async function makeOpenAIRequestWithRetry(requestFn, maxRetries = 3, initialDelayMs = 1000) {
    let lastError = null;
    for (let attempt = 0; attempt <= maxRetries; attempt++) {
        try {
            return await requestFn();
        }
        catch (error) {
            lastError = error;
            // Check if it's a rate limit error (429) - but NOT insufficient_quota
            const isRateLimit = error?.status === 429 && error?.code !== 'insufficient_quota';
            if (isRateLimit && attempt < maxRetries) {
                const delayMs = initialDelayMs * Math.pow(2, attempt);
                console.log(`[OpenAI Validation] Rate limit hit, retrying in ${delayMs}ms (attempt ${attempt + 1}/${maxRetries})`);
                await new Promise(resolve => setTimeout(resolve, delayMs));
                continue;
            }
            // If it's a quota error or max retries reached, throw
            throw error;
        }
    }
    throw lastError || new Error('Max retries exceeded');
}
//# sourceMappingURL=retry.js.map