// engine/llm-providers/rate-limiter.ts — Rate limiting awareness.
// SPEC-083 AC-10
/** In-memory rate limit tracking per provider. */
const rateLimitStates = new Map();
/** Threshold percentage at which a provider is considered degraded. */
const DEGRADED_THRESHOLD = 0.8;
/**
 * Record a request against a provider's rate limit window.
 */
export function trackRequest(providerId, tokensUsed, limits) {
    const now = new Date();
    const existing = rateLimitStates.get(providerId);
    // Reset window if older than 1 minute
    const windowStart = existing?.windowStart ?? now.toISOString();
    const windowAge = now.getTime() - new Date(windowStart).getTime();
    const shouldReset = windowAge > 60_000;
    const state = {
        providerId,
        requestsUsed: shouldReset ? 1 : (existing?.requestsUsed ?? 0) + 1,
        tokensUsed: shouldReset ? tokensUsed : (existing?.tokensUsed ?? 0) + tokensUsed,
        windowStart: shouldReset ? now.toISOString() : windowStart,
        capacityPercent: 0,
    };
    // Calculate capacity as the max of request% and token%
    const requestPercent = limits.requestsPerMinute > 0 ? state.requestsUsed / limits.requestsPerMinute : 0;
    const tokenPercent = limits.tokensPerMinute > 0 ? state.tokensUsed / limits.tokensPerMinute : 0;
    state.capacityPercent = Math.max(requestPercent, tokenPercent);
    rateLimitStates.set(providerId, state);
    return state;
}
/**
 * Get the current rate limit state for a provider.
 */
export function getRateLimitState(providerId) {
    return rateLimitStates.get(providerId);
}
/**
 * Check if a provider is near its rate limit (>80% capacity).
 */
export function isNearRateLimit(providerId) {
    const state = rateLimitStates.get(providerId);
    if (!state) {
        return false;
    }
    return state.capacityPercent >= DEGRADED_THRESHOLD;
}
/**
 * Get health status adjustment based on rate limiting.
 */
export function getRateLimitHealthStatus(providerId) {
    if (isNearRateLimit(providerId)) {
        return 'degraded';
    }
    return 'healthy';
}
/**
 * Get suggested alternative providers when one is near its rate limit.
 */
export function suggestAlternatives(currentProvider, allProviders) {
    return allProviders
        .filter((p) => p.id !== currentProvider && !isNearRateLimit(p.id))
        .map((p) => p.id);
}
/**
 * Reset all rate limit state (for testing).
 */
export function resetRateLimits() {
    rateLimitStates.clear();
}
//# sourceMappingURL=rate-limiter.js.map