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

export async function statusCommand(): Promise<void> {
  try {
    const config = await ConfigManager.load();
    const defaultProvider = config.defaultProvider;
    const providerConfig =
      config.providers[defaultProvider as keyof typeof config.providers];

    if (!providerConfig) {
      console.log(
        color(`No configuration found for provider: ${defaultProvider}`, "red"),
      );
      return;
    }

    const providerInfo = ProviderRegistry.getProviderInfo(defaultProvider);
    const providerName = providerInfo?.name || defaultProvider;
    const model = (providerConfig as any).model || "unknown";

    const models = ProviderRegistry.getModelsForProvider(defaultProvider);
    const modelInfo = Object.entries(models).find(([key, _]) => key === model);
    const modelName = modelInfo ? (modelInfo[1] as any).name || model : model;

    const apiKey = await ConfigManager.getApiKey(defaultProvider);
    const keyStatus = apiKey ? color("✓", "green") : color("✗", "red");

    console.log(
      `${color(providerName, "cyan")}/${color(modelName, "yellow")} ${keyStatus}`,
    );
  } catch (error) {
    console.error(
      color("Failed to get status:", "red"),
      error instanceof Error ? error.message : error,
    );
    process.exit(1);
  }
}

export async function testProviderConnection(): Promise<void> {
  // Get configured providers using utility function
  const configuredProviders = await getValidConfiguredProviders();
  
  if (configuredProviders.length === 0) {
    console.log(color("No configured providers found.", "yellow"));
    console.log("Run 'agi config setup' to configure a provider.");
    return;
  }

  console.log("\n" + color("🔬 Test Provider Connection", "cyan"));
  console.log(color("─".repeat(40), "gray"));

  const inquirer = await import("inquirer");
  const { selectedProvider } = await inquirer.default.prompt([
    {
      type: "list",
      name: "selectedProvider",
      message: "Select provider to test:",
      choices: configuredProviders
        .map((provider: string) => {
          const info = ProviderRegistry.getProviderInfo(provider);
          return {
            name: info!.name, // We know info exists because getValidConfiguredProviders ensures it
            value: provider,
          };
        }),
    },
  ]);

  console.log(`Testing ${selectedProvider}...`);

  try {
    const isValid = await ProviderRegistry.validateProvider(selectedProvider);
    if (isValid) {
      console.log(color("✓ Connection successful!", "green"));
    } else {
      console.log(
        color(
          "✗ Connection failed. Check your API key and configuration.",
          "red",
        ),
      );
    }
  } catch (error) {
    console.log(
      color("✗ Connection failed:", "red"),
      error instanceof Error ? error.message : error,
    );
  }
}