/**
 * Fallback chain utility.
 *
 * Wraps an ordered list of LLMProviders into a single LLMProvider that
 * tries each in sequence, skipping unconfigured ones, and moves to the
 * next on any error. Throws only when all providers are exhausted.
 */

import type { ChatCompletionRequest, ChatCompletionResponse, LLMProvider } from './types.js';

export function createFallbackChain(providers: LLMProvider[]): LLMProvider {
  return {
    isConfigured(): boolean {
      return providers.some(p => p.isConfigured());
    },

    async chatCompletion(req: ChatCompletionRequest): Promise<ChatCompletionResponse> {
      const errors: string[] = [];

      for (const provider of providers) {
        if (!provider.isConfigured()) continue;
        try {
          return await provider.chatCompletion(req);
        } catch (err) {
          errors.push(err instanceof Error ? err.message : String(err));
        }
      }

      throw new Error(
        errors.length > 0
          ? `All providers failed: ${errors.join(' | ')}`
          : 'No providers configured'
      );
    },
  };
}
