/**
 * Provider Fallback Chain
 *
 * Implements automatic provider fallback when primary provider fails.
 * Features:
 * - Circuit breaker pattern for unhealthy provider detection
 * - Automatic provider promotion when primary fails
 * - Health tracking (failure rate, response time)
 * - Graceful fallback to alternatives
 * - Auto-recovery after cooldown period
 */
import { EventEmitter } from 'events';
import type { ProviderType } from './types.js';
/**
 * Configuration for the fallback chain behavior.
 */
export interface FallbackConfig {
    /** Maximum failures before marking provider as unhealthy (circuit breaker threshold). Default: 3 */
    maxFailures: number;
    /** Cooldown period in milliseconds before attempting recovery. Default: 60000 (1 minute) */
    cooldownMs: number;
    /** Time window in milliseconds for failure counting. Default: 300000 (5 minutes) */
    failureWindowMs: number;
    /** Response time threshold in ms - above this is considered slow. Default: 5000 */
    slowThresholdMs: number;
    /** Whether to auto-promote backup providers when primary fails. Default: true */
    autoPromote: boolean;
    /** Maximum number of consecutive slow responses before considering unhealthy. Default: 5 */
    maxSlowResponses: number;
}
/**
 * Health status for a single provider.
 */
export interface ProviderHealth {
    /** Provider identifier */
    provider: ProviderType;
    /** Whether the provider is currently healthy (circuit is closed) */
    healthy: boolean;
    /** Number of failures in the current window */
    failureCount: number;
    /** Number of successes in the current window */
    successCount: number;
    /** Total number of requests made */
    totalRequests: number;
    /** Average response time in milliseconds */
    avgResponseTimeMs: number;
    /** Timestamp of last successful request */
    lastSuccess: number | null;
    /** Timestamp of last failure */
    lastFailure: number | null;
    /** Timestamp when provider was marked unhealthy (circuit opened) */
    circuitOpenedAt: number | null;
    /** Failure rate (0-1) */
    failureRate: number;
    /** Number of consecutive slow responses */
    consecutiveSlowResponses: number;
}
/**
 * Events emitted by the fallback chain.
 */
export interface FallbackChainEvents {
    /** Emitted when switching to a fallback provider */
    'provider:fallback': {
        from: ProviderType;
        to: ProviderType;
        reason: string;
    };
    /** Emitted when a provider becomes unhealthy (circuit opens) */
    'provider:unhealthy': {
        provider: ProviderType;
        failureCount: number;
        reason: string;
    };
    /** Emitted when a provider recovers (circuit closes) */
    'provider:recovered': {
        provider: ProviderType;
    };
    /** Emitted when a provider is promoted to primary */
    'provider:promoted': {
        provider: ProviderType;
        previousPrimary: ProviderType;
    };
    /** Emitted on any failure */
    'provider:failure': {
        provider: ProviderType;
        error: string;
    };
    /** Emitted on any success */
    'provider:success': {
        provider: ProviderType;
        responseTimeMs: number;
    };
    /** Emitted when all providers are exhausted */
    'chain:exhausted': {
        attemptedProviders: ProviderType[];
    };
}
/**
 * Manages a fallback chain of AI providers with automatic failover,
 * health tracking, and circuit breaker functionality.
 */
export declare class ProviderFallbackChain extends EventEmitter {
    private chain;
    private config;
    private metrics;
    private currentIndex;
    constructor(config?: Partial<FallbackConfig>);
    /**
     * Sets the fallback chain order.
     * The first provider is the primary, subsequent providers are fallbacks.
     *
     * @param providers - Ordered list of providers (primary first)
     */
    setFallbackChain(providers: ProviderType[]): void;
    /**
     * Gets the current fallback chain.
     */
    getFallbackChain(): ProviderType[];
    /**
     * Gets the current primary provider.
     */
    getPrimaryProvider(): ProviderType | null;
    /**
     * Gets the next healthy provider in the chain.
     * Implements circuit breaker pattern - skips unhealthy providers.
     *
     * @param skipCurrent - Whether to skip the current provider
     * @returns The next available provider, or null if all are exhausted
     */
    getNextProvider(skipCurrent?: boolean): ProviderType | null;
    /**
     * Gets the current active provider (may be unhealthy).
     */
    getCurrentProvider(): ProviderType | null;
    /**
     * Records a successful request for a provider.
     *
     * @param provider - The provider that succeeded
     * @param responseTimeMs - Response time in milliseconds
     */
    recordSuccess(provider: ProviderType, responseTimeMs: number): void;
    /**
     * Records a failed request for a provider.
     *
     * @param provider - The provider that failed
     * @param error - Error message or description
     */
    recordFailure(provider: ProviderType, error: string): void;
    /**
     * Gets the health status for a specific provider.
     *
     * @param provider - The provider to check
     * @returns Health status object
     */
    getHealthStatus(provider: ProviderType): ProviderHealth;
    /**
     * Gets health status for all providers in the chain.
     */
    getAllHealthStatus(): ProviderHealth[];
    /**
     * Checks if a provider is currently healthy.
     * A provider is healthy if:
     * - Circuit is closed (not in cooldown)
     * - Not exceeding slow response threshold
     */
    isProviderHealthy(provider: ProviderType): boolean;
    /**
     * Checks if we should attempt recovery for an unhealthy provider.
     * Recovery is attempted after the cooldown period.
     */
    private shouldAttemptRecovery;
    /**
     * Manually reset a provider's health status.
     * Use with caution - bypasses the circuit breaker.
     */
    resetProvider(provider: ProviderType): void;
    /**
     * Manually mark a provider as unhealthy.
     * Opens the circuit breaker for this provider.
     */
    markUnhealthy(provider: ProviderType, reason: string): void;
    /**
     * Promotes a specific provider to primary position.
     */
    promoteProvider(provider: ProviderType): void;
    /**
     * Promotes the next healthy provider to primary position.
     */
    private promoteNextHealthyProvider;
    /**
     * Initializes metrics for a provider.
     */
    private initializeMetrics;
    /**
     * Gets or creates metrics for a provider.
     */
    private getOrCreateMetrics;
    /**
     * Cleans old entries outside the failure window.
     */
    private cleanOldEntries;
    /**
     * Updates the configuration.
     */
    updateConfig(config: Partial<FallbackConfig>): void;
    /**
     * Gets the current configuration.
     */
    getConfig(): FallbackConfig;
    /**
     * Resets all metrics and state.
     */
    reset(): void;
    /**
     * Disposes of the fallback chain and clears all listeners.
     */
    dispose(): void;
}
/**
 * Gets the singleton instance of the ProviderFallbackChain.
 */
export declare function getFallbackChain(): ProviderFallbackChain;
/**
 * Resets the singleton instance (useful for testing).
 */
export declare function resetFallbackChain(): void;
