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 showApiKeyConfig(): Promise<void> {
  try {
    // 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("🔑 API Key Configuration", "cyan"));
    console.log(color("─".repeat(40), "gray"));

    const providerChoices = configuredProviders.map((provider) => {
      const info = ProviderRegistry.getProviderInfo(provider);
      return {
        name: info!.name, // We know info exists because getValidConfiguredProviders filtered it
        value: provider,
      };
    });

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

    const currentKey = await ConfigManager.getApiKey(selectedProvider);
    const hasKey = currentKey
      ? color("(configured)", "green")
      : color("(not set)", "yellow");

    console.log(`\nCurrent API key status: ${hasKey}`);

    if (currentKey) {
      const { replaceKey } = await inquirer.prompt([
        {
          type: "confirm",
          name: "replaceKey",
          message: "Replace existing API key?",
          default: false,
        },
      ]);

      if (!replaceKey) return;
    }

    const { newKey } = await inquirer.prompt([
      {
        type: "password",
        name: "newKey",
        message: "Enter API key:",
        mask: "*",
      },
    ]);

    if (newKey) {
      try {
        await ConfigManager.setApiKey(selectedProvider, newKey);
        console.log(color("✓ API key configured", "green"));
      } catch (error) {
        console.log(
          color(
            `Failed to set API key: ${error instanceof Error ? error.message : error}`,
            "red",
          ),
        );
      }
    }
  } catch (error) {
    console.error(
      color("Failed to configure API key:", "red"),
      error instanceof Error ? error.message : error,
    );
  }
}

export async function setApiKeyCommand(
  provider: string,
  apiKey: string,
): Promise<void> {
  try {
    await ConfigManager.setApiKey(provider, apiKey);
    console.log(color(`✓ API key configured for ${provider}`, "green"));
  } catch (error) {
    console.error(
      color("Failed to set API key:", "red"),
      error instanceof Error ? error.message : error,
    );
    process.exit(1);
  }
}