import type { AgentRuntimeProvider } from '@mosaicstack/types';

/**
 * Registry for runtime providers. Registration is explicit and replacement is
 * forbidden so a provider identity cannot be silently hijacked at runtime.
 */
export class AgentRuntimeProviderRegistry {
  private readonly providers = new Map<string, AgentRuntimeProvider>();

  register(provider: AgentRuntimeProvider): void {
    const providerId = provider.id.trim();
    if (providerId.length === 0) {
      throw new Error('Runtime provider ID is required');
    }
    if (this.providers.has(providerId)) {
      throw new Error(`Runtime provider is already registered: ${providerId}`);
    }
    this.providers.set(providerId, provider);
  }

  get(providerId: string): AgentRuntimeProvider | undefined {
    return this.providers.get(providerId);
  }

  require(providerId: string): AgentRuntimeProvider {
    const normalizedProviderId = providerId.trim();
    if (normalizedProviderId.length === 0) {
      throw new Error('Runtime provider ID is required');
    }
    const provider = this.providers.get(normalizedProviderId);
    if (!provider) {
      throw new Error(`Runtime provider is not registered: ${normalizedProviderId}`);
    }
    return provider;
  }

  list(): AgentRuntimeProvider[] {
    return Array.from(this.providers.values());
  }
}
