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

export async function addProvider(): Promise<void> {
  const config = await ConfigManager.load();
  const modelsData = await import("../../models.json");
  const availableProviders = Object.keys(modelsData.providers);
  const enabledProviders = Object.keys(config.providers);
  const disabledProviders = availableProviders.filter(
    (p) => !enabledProviders.includes(p),
  );

  if (disabledProviders.length === 0) {
    console.log(
      color("All available providers are already enabled!", "yellow"),
    );
    return;
  }

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

  const { selectedProvider } = await inquirer.prompt([
    {
      type: "list",
      name: "selectedProvider",
      message: "Select provider to add:",
      choices: disabledProviders.map((provider) => ({
        name: modelsData.providers[
          provider as keyof typeof modelsData.providers
        ].name,
        value: provider,
      })),
    },
  ]);

  const providerInfo =
    modelsData.providers[selectedProvider as keyof typeof modelsData.providers];
  const defaultModel = providerInfo.defaultModel;

  config.providers[selectedProvider as keyof typeof config.providers] = {
    enabled: true,
    model: defaultModel,
    maxTokens: 4096,
    temperature: 0.7,
  } as any;

  await ConfigManager.save();
  console.log(
    color(`✓ Provider ${selectedProvider} added successfully!`, "green"),
  );
}

export async function removeProvider(): Promise<void> {
  const config = await ConfigManager.load();
  const enabledProviders = Object.keys(config.providers);

  if (enabledProviders.length <= 1) {
    console.log(color("Cannot remove the last provider!", "red"));
    return;
  }

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

  const removableProviders = enabledProviders.filter(
    (p) => p !== config.defaultProvider
  );

  const { selectedProvider } = await inquirer.prompt([
    {
      type: "list",
      name: "selectedProvider",
      message: "Select provider to remove:",
      choices: removableProviders.map((provider) => {
        const info = ProviderRegistry.getProviderInfo(provider);
        return {
          name: info?.name || provider,
          value: provider,
        };
      }),
    },
  ]);

  const { confirmRemove } = await inquirer.prompt([
    {
      type: "confirm",
      name: "confirmRemove",
      message: `Are you sure you want to remove ${selectedProvider}?`,
      default: false,
    },
  ]);

  if (confirmRemove) {
    delete (config.providers as any)[selectedProvider];
    await ConfigManager.save();
    console.log(
      color(`✓ Provider ${selectedProvider} removed successfully!`, "green"),
    );
  }
}

export async function enableDisableProvider(): Promise<void> {
  const config = await ConfigManager.load();
  const providers = Object.entries(config.providers);

  if (providers.length === 0) {
    console.log(color("No providers configured!", "red"));
    return;
  }

  console.log("\n" + color("🔄 Enable/Disable Provider", "cyan"));
  console.log(color("─".repeat(40), "gray"));

  const { selectedProvider } = await inquirer.prompt([
    {
      type: "list",
      name: "selectedProvider",
      message: "Select provider:",
      choices: providers.map(([provider, config]: [string, any]) => {
        const info = ProviderRegistry.getProviderInfo(provider);
        const status = config.enabled
          ? color("(enabled)", "green")
          : color("(disabled)", "red");
        return {
          name: `${info?.name || provider} ${status}`,
          value: provider,
        };
      }),
    },
  ]);

  const providerConfig = config.providers[
    selectedProvider as keyof typeof config.providers
  ] as any;
  const currentStatus = providerConfig.enabled;

  const { newStatus } = await inquirer.prompt([
    {
      type: "confirm",
      name: "newStatus",
      message: `${currentStatus ? "Disable" : "Enable"} ${selectedProvider}?`,
      default: !currentStatus,
    },
  ]);

  providerConfig.enabled = newStatus;
  await ConfigManager.save();

  const action = newStatus ? "enabled" : "disabled";
  console.log(color(`✓ Provider ${selectedProvider} ${action}!`, "green"));
}

export async function addProviderCommand(providerName: string): Promise<void> {
  try {
    const config = await ConfigManager.load();
    const modelsData = await import("../../models.json");

    if (config.providers[providerName as keyof typeof config.providers]) {
      console.log(
        color(`Provider ${providerName} is already configured!`, "yellow"),
      );
      return;
    }

    if (
      !modelsData.providers[providerName as keyof typeof modelsData.providers]
    ) {
      console.log(color(`Unknown provider: ${providerName}`, "red"));
      console.log(color("Available providers:", "gray"));
      Object.keys(modelsData.providers).forEach((provider) => {
        console.log(`  - ${provider}`);
      });
      return;
    }

    const providerInfo =
      modelsData.providers[providerName as keyof typeof modelsData.providers];
    const defaultModel = providerInfo.defaultModel;

    config.providers[providerName as keyof typeof config.providers] = {
      enabled: true,
      model: defaultModel,
      maxTokens: 4096,
      temperature: 0.7,
    } as any;

    await ConfigManager.save();
    console.log(
      color(`✓ Provider ${providerName} added successfully!`, "green"),
    );
    console.log(
      color(
        `Set API key with: agi config key ${providerName} <your-key>`,
        "gray",
      ),
    );
  } catch (error) {
    console.log(color(`Failed to add provider: ${error}`, "red"));
  }
}

export async function removeProviderCommand(
  providerName: string,
): Promise<void> {
  try {
    const config = await ConfigManager.load();

    if (!config.providers[providerName as keyof typeof config.providers]) {
      console.log(
        color(`Provider ${providerName} is not configured!`, "yellow"),
      );
      return;
    }

    if (config.defaultProvider === providerName) {
      console.log(
        color(
          `Cannot remove default provider! Change default provider first.`,
          "red",
        ),
      );
      return;
    }

    if (Object.keys(config.providers).length <= 1) {
      console.log(color("Cannot remove the last provider!", "red"));
      return;
    }

    delete (config.providers as any)[providerName];
    await ConfigManager.save();
    console.log(
      color(`✓ Provider ${providerName} removed successfully!`, "green"),
    );
  } catch (error) {
    console.log(color(`Failed to remove provider: ${error}`, "red"));
  }
}