import { ConfigManager } from "@/config/manager";
import { showProviderConfig } from "./provider-config";
import { setApiKeyCommand } from "./api-key-config";
import { addProviderCommand, removeProviderCommand } from "./provider-management";
import { statusCommand } from "./status";
import { showInteractiveConfig } from "./interactive";
import type { ConfigOptions } from "./types";

export async function configCommand(
  options: ConfigOptions = {},
): Promise<void> {
  try {
    if (options.init) {
      await ConfigManager.init();
      console.log("✓ Config initialized with defaults at ~/.agi/config.json");
      return;
    }

    if (options.list) {
      const config = await ConfigManager.load();
      console.log(JSON.stringify(config, null, 2));
      return;
    }

    if (options.get) {
      const config = await ConfigManager.load();
      const keys = options.get.split(".");
      let value: any = config;

      for (const key of keys) {
        if (value && typeof value === "object" && key in value) {
          value = value[key];
        } else {
          console.error(`Config key '${options.get}' not found`);
          process.exit(1);
        }
      }

      console.log(
        typeof value === "object" ? JSON.stringify(value, null, 2) : value,
      );
      return;
    }

    if (options.set) {
      console.error("Usage: agi config --set <key> <value>");
      console.error(
        "Example: agi config --set providers.gemini.apiKey your-api-key",
      );
      process.exit(1);
    }

    if (options.provider) {
      await showProviderConfig();
      return;
    }

    await showInteractiveConfig();
  } catch (error) {
    console.error(
      "Failed to manage config:",
      error instanceof Error ? error.message : error,
    );
    process.exit(1);
  }
}

export async function setConfigValue(
  key: string,
  value: string,
): Promise<void> {
  try {
    const keys = key.split(".");
    const config = await ConfigManager.load();

    let current: any = config;
    for (let i = 0; i < keys.length - 1; i++) {
      const currentKey = keys[i];
      if (currentKey && !(currentKey in current)) {
        current[currentKey] = {};
      }
      if (currentKey) {
        current = current[currentKey];
      }
    }

    const lastKey = keys[keys.length - 1];
    if (lastKey) {
      const parsedValue = parseValue(value);
      current[lastKey] = parsedValue;

      await ConfigManager.save();
      console.log(`✓ Set ${key} = ${value}`);
    }
  } catch (error) {
    console.error(
      "Failed to set config value:",
      error instanceof Error ? error.message : error,
    );
    process.exit(1);
  }
}

function parseValue(value: string): any {
  try {
    return JSON.parse(value);
  } catch {
    return value;
  }
}

export { setApiKeyCommand, statusCommand, addProviderCommand, removeProviderCommand };