import { ConfigManager } from "@/config/manager";
import { color } from "@/utils/formatter";
import inquirer from "inquirer";
import { showProviderConfig } from "./provider-config";
import { showApiKeyConfig } from "./api-key-config";
import { addProvider, removeProvider, enableDisableProvider } from "./provider-management";
import { testProviderConnection } from "./status";

export async function showInteractiveConfig(): Promise<void> {
  try {
    const config = await ConfigManager.load();
    console.log(color("📋 AGI Configuration", "cyan"));
    console.log(color("─".repeat(40), "gray"));
    console.log(`Config file: ${color("~/.agi/config.json", "yellow")}`);
    console.log(`Default provider: ${color(config.defaultProvider, "green")}`);

    const apiKey = await ConfigManager.getApiKey(config.defaultProvider);
    const status = apiKey
      ? color("configured ✓", "green")
      : color("missing ⚠", "yellow");
    console.log(`API key: ${status}`);

    if (!apiKey) {
      console.log(
        color(
          `  Set with: agi config key ${config.defaultProvider} <your-key>`,
          "gray",
        ),
      );
    }

    const { action } = await inquirer.prompt([
      {
        type: "list",
        name: "action",
        message: "What would you like to do?",
        choices: [
          { name: "Change default provider", value: "provider" },
          { name: "Set API key", value: "apikey" },
          { name: "Add provider", value: "add-provider" },
          { name: "Remove provider", value: "remove-provider" },
          { name: "Enable/Disable provider", value: "toggle-provider" },
          { name: "Test provider connection", value: "test" },
          { name: "View current configuration", value: "view" },
          { name: "Exit", value: "exit" },
        ],
      },
    ]);

    switch (action) {
      case "provider":
        await showProviderConfig();
        break;
      case "apikey":
        await showApiKeyConfig();
        break;
      case "add-provider":
        await addProvider();
        break;
      case "remove-provider":
        await removeProvider();
        break;
      case "toggle-provider":
        await enableDisableProvider();
        break;
      case "test":
        await testProviderConnection();
        break;
      case "view":
        console.log(JSON.stringify(config, null, 2));
        break;
      case "exit":
        return;
    }
  } catch (error) {
    console.log(color("No config found. Run: agi config --init", "yellow"));
  }
}