import { ConfigManager } from "@/config/manager";
import { color } from "@/utils/formatter";
import { ProviderRegistry } from "@/utils/provider-registry";

/**
 * Get configured providers from the user's config
 * @returns Array of configured provider names
 */
export async function getConfiguredProviders(): Promise<string[]> {
  const config = await ConfigManager.load();
  return Object.keys(config.providers).filter(
    provider => config.providers[provider as keyof typeof config.providers]
  );
}

/**
 * Get and validate configured providers
 * Displays a warning if no providers are configured
 * @returns Array of configured provider names or null if none
 */
export async function getAndValidateConfiguredProviders(): Promise<string[] | null> {
  const configuredProviders = await getConfiguredProviders();
  
  if (configuredProviders.length === 0) {
    console.log(color("No providers configured. Please add a provider first.", "yellow"));
    console.log(color("Run: agi config add-provider <provider-name>", "gray"));
    return null;
  }
  
  return configuredProviders;
}

/**
 * Check if a provider is configured
 * @param providerName The provider to check
 * @returns true if the provider is configured
 */
export async function isProviderConfigured(providerName: string): Promise<boolean> {
  const configuredProviders = await getConfiguredProviders();
  return configuredProviders.includes(providerName);
}

/**
 * Get the configuration for a specific provider
 * @param providerName The provider name
 * @returns The provider configuration or undefined
 */
export async function getProviderConfig(providerName: string): Promise<any | undefined> {
  const config = await ConfigManager.load();
  return config.providers[providerName as keyof typeof config.providers];
}

/**
 * Get configured providers that are also registered in ProviderRegistry
 * Filters out any configured providers that don't exist in the registry
 * @returns Array of valid configured provider names
 */
export async function getValidConfiguredProviders(): Promise<string[]> {
  const configuredProviders = await getConfiguredProviders();
  
  return configuredProviders.filter(provider => {
    const info = ProviderRegistry.getProviderInfo(provider);
    if (!info) {
      console.warn(color(`Warning: Configured provider '${provider}' not found in registry. Skipping.`, 'yellow'));
      return false;
    }
    return true;
  });
}