/**
 * Agent Provider Registry
 *
 * In-memory registry of agent provider configurations.
 * Pre-populated with built-in presets, extensible via registerProvider()
 * or loadProvidersFromFile() for custom/override configs.
 */

import { readFileSync } from 'node:fs';
import type { AgentProviderConfig } from './types.js';
import { PROVIDER_PRESETS } from './presets.js';

const providers = new Map<string, AgentProviderConfig>(
  Object.entries(PROVIDER_PRESETS),
);

/**
 * Get a provider configuration by name.
 * Returns null if the provider is not registered.
 */
export function getProvider(name: string): AgentProviderConfig | null {
  return providers.get(name) ?? null;
}

/**
 * List all registered provider names.
 */
export function listProviders(): string[] {
  return Array.from(providers.keys());
}

/**
 * Register or override a provider configuration.
 */
export function registerProvider(config: AgentProviderConfig): void {
  providers.set(config.name, config);
}

/**
 * Load provider configurations from a JSON file and merge into the registry.
 * File should contain a JSON object mapping provider names to AgentProviderConfig objects.
 * Existing providers with matching names will be overridden.
 */
export function loadProvidersFromFile(path: string): void {
  const raw = readFileSync(path, 'utf-8');
  const parsed = JSON.parse(raw) as Record<string, AgentProviderConfig>;
  for (const [name, config] of Object.entries(parsed)) {
    providers.set(name, { ...config, name });
  }
}
