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

export async function showProviderConfig(): Promise<void> {
  const config = await ConfigManager.load();
  
  // Get configured providers that are valid in the registry
  const configuredProviders = await getValidConfiguredProviders();
  
  if (configuredProviders.length === 0) {
    console.log(color("No valid providers configured. Please add a provider first.", "yellow"));
    console.log(color("Run: agi config add-provider <provider-name>", "gray"));
    return;
  }

  console.log("\n" + color("🔌 Provider Configuration", "cyan"));
  console.log(color("─".repeat(40), "gray"));

  const providerChoices = configuredProviders.map((provider) => {
    const info = ProviderRegistry.getProviderInfo(provider);
    const isCurrent =
      provider === config.defaultProvider ? color(" (current)", "green") : "";
    return {
      name: `${info!.name}${isCurrent}`, // We know info exists because getValidConfiguredProviders filtered it
      value: provider,
    };
  });

  const { selectedProvider } = await inquirer.prompt([
    {
      type: "list",
      name: "selectedProvider",
      message: "Select default provider:",
      choices: providerChoices,
    },
  ]);

  if (selectedProvider !== config.defaultProvider) {
    await ConfigManager.set("defaultProvider", selectedProvider);
    console.log(
      color(`✓ Default provider changed to ${selectedProvider}`, "green"),
    );
    await showModelConfig(selectedProvider);
  }
}

export async function showModelConfig(provider: string): Promise<void> {
  const models = ProviderRegistry.getModelsForProvider(provider);
  const modelEntries = Object.entries(models);

  if (modelEntries.length === 0) {
    console.log(color("No models available for this provider.", "yellow"));
    return;
  }

  console.log("\n" + color("🤖 Model Configuration", "cyan"));
  console.log(color("─".repeat(40), "gray"));

  const modelChoices = modelEntries.map(([key, model]: [string, any]) => ({
    name: `${model.name}${model.reasoning ? color(" (reasoning)", "blue") : ""}`,
    value: key,
  }));

  const { selectedModel } = await inquirer.prompt([
    {
      type: "list",
      name: "selectedModel",
      message: "Select model:",
      choices: modelChoices,
    },
  ]);

  const config = await ConfigManager.load();
  const providerConfig =
    config.providers[provider as keyof typeof config.providers];

  if (providerConfig) {
    (providerConfig as any).model = selectedModel;
    await ConfigManager.save();
    console.log(color(`✓ Model set to ${selectedModel}`, "green"));
  }
}