import type { ProviderProtocol } from "./protocol";

/**
 * Provider Registry
 *
 * Singleton registry for provider implementations.
 * Providers register themselves at module load time.
 */
class ProviderRegistryImpl {
  private providers: ProviderProtocol[] = [];

  /**
   * Register a provider with the registry.
   * @param provider - Provider implementation to register
   */
  register(provider: ProviderProtocol): void {
    this.providers.push(provider);
  }

  /**
   * Find the first provider that matches the given model.
   * @param model - Model name to match
   * @returns Matching provider or null if none found
   */
  findProvider(model: string): ProviderProtocol | null {
    let fallback: ProviderProtocol | null = null;

    for (const provider of this.providers) {
      if (provider.matches(model)) {
        // Non-anthropic providers win immediately (explicit match)
        if (provider.name !== "anthropic") {
          return provider;
        }
        // Anthropic is the fallback — only use if nothing else matches
        fallback = provider;
      }
    }
    return fallback;
  }

  /**
   * Get all registered providers.
   * @returns Array of all registered providers
   */
  getAll(): ProviderProtocol[] {
    return [...this.providers];
  }
}

/** Global registry instance */
export const registry = new ProviderRegistryImpl();
