import a from '../chunks/index5.mjs';
import { i as inquirer } from '../chunks/index6.mjs';
import { ensureI18nInitialized, i18n } from '../chunks/index2.mjs';
import { e as getExistingApiConfig, f as configureApi, s as switchToOfficialLogin, b as backupExistingConfig, i as applyAiLanguageDirective } from '../chunks/config.mjs';
import { a as configureOutputStyle } from './ccjk.C0WLUnFV.mjs';
import { a as addNumbersToChoices } from './ccjk.BFQ7yr5S.mjs';
import { r as resolveClaudeFamilySettingsTarget } from './ccjk.DDL-4C-k.mjs';

function validateApiKey(apiKey) {
  if (!apiKey || apiKey.trim() === "") {
    return {
      isValid: false,
      // Note: This should use i18next, but due to sync constraint in inquirer validate,
      // we temporarily use a generic message. This will be fixed when we refactor to async validation.
      error: "API key cannot be empty"
    };
  }
  return { isValid: true };
}
function formatApiKeyDisplay(apiKey) {
  if (!apiKey || apiKey.length < 12) {
    return apiKey;
  }
  return `${apiKey.substring(0, 8)}...${apiKey.substring(apiKey.length - 4)}`;
}

async function configureApiCompletely(preselectedAuthType) {
  ensureI18nInitialized();
  let authType = preselectedAuthType;
  if (!authType) {
    const { authType: selectedAuthType } = await inquirer.prompt({
      type: "list",
      name: "authType",
      message: i18n.t("api:configureApi"),
      choices: addNumbersToChoices([
        {
          name: i18n.t("api:useOfficialLogin"),
          value: "official",
          short: i18n.t("api:useOfficialLogin")
        },
        {
          name: `${i18n.t("api:useAuthToken")} - ${a.gray(i18n.t("api:authTokenDesc"))}`,
          value: "auth_token",
          short: i18n.t("api:useAuthToken")
        },
        {
          name: `${i18n.t("api:useApiKey")} - ${a.gray(i18n.t("api:apiKeyDesc"))}`,
          value: "api_key",
          short: i18n.t("api:useApiKey")
        }
      ])
    });
    if (!selectedAuthType) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return null;
    }
    authType = selectedAuthType;
  }
  if (authType === "official") {
    const success = switchToOfficialLogin();
    if (success) {
      return null;
    } else {
      console.log(a.red(i18n.t("api:officialLoginFailed")));
      return null;
    }
  }
  const { url } = await inquirer.prompt({
    type: "input",
    name: "url",
    message: i18n.t("api:enterApiUrl"),
    validate: async (value) => {
      if (!value)
        return i18n.t("api:urlRequired");
      try {
        void new URL(value);
        return true;
      } catch {
        return i18n.t("api:invalidUrl");
      }
    }
  });
  if (url === void 0) {
    console.log(a.yellow(i18n.t("common:cancelled")));
    return null;
  }
  const keyMessage = authType === "auth_token" ? i18n.t("api:enterAuthToken") : i18n.t("api:enterApiKey");
  const { key } = await inquirer.prompt({
    type: "input",
    name: "key",
    message: keyMessage,
    validate: async (value) => {
      if (!value) {
        return i18n.t("api:keyRequired");
      }
      const validation = validateApiKey(value);
      if (!validation.isValid) {
        return validation.error || i18n.t("api:invalidKeyFormat");
      }
      return true;
    }
  });
  if (key === void 0) {
    console.log(a.yellow(i18n.t("common:cancelled")));
    return null;
  }
  console.log(a.gray(`  API Key: ${formatApiKeyDisplay(key)}`));
  return { url, key, authType };
}
async function modifyApiConfigPartially(existingConfig) {
  ensureI18nInitialized();
  let currentConfig = { ...existingConfig };
  const latestConfig = getExistingApiConfig();
  if (latestConfig) {
    currentConfig = latestConfig;
  }
  const { item } = await inquirer.prompt({
    type: "list",
    name: "item",
    message: i18n.t("api:selectModifyItems"),
    choices: addNumbersToChoices([
      { name: i18n.t("api:modifyApiUrl"), value: "url" },
      { name: i18n.t("api:modifyApiKey"), value: "key" },
      { name: i18n.t("api:modifyAuthType"), value: "authType" }
    ])
  });
  if (!item) {
    console.log(a.yellow(i18n.t("common:cancelled")));
    return;
  }
  if (item === "url") {
    const { url } = await inquirer.prompt({
      type: "input",
      name: "url",
      message: i18n.t("api:enterNewApiUrl").replace("{url}", currentConfig.url || i18n.t("common:none")),
      default: currentConfig.url,
      validate: async (value) => {
        if (!value)
          return i18n.t("api:urlRequired");
        try {
          void new URL(value);
          return true;
        } catch {
          return i18n.t("api:invalidUrl");
        }
      }
    });
    if (url === void 0) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return;
    }
    currentConfig.url = url;
    const savedConfig = configureApi(currentConfig);
    if (savedConfig) {
      console.log(a.green(`\u2714 ${i18n.t("api:modificationSaved")}`));
      console.log(a.gray(`  ${i18n.t("api:apiConfigUrl")}: ${savedConfig.url}`));
    }
  } else if (item === "key") {
    const authType = currentConfig.authType || "auth_token";
    const keyMessage = authType === "auth_token" ? i18n.t("api:enterNewApiKey").replace("{key}", currentConfig.key ? formatApiKeyDisplay(currentConfig.key) : i18n.t("common:none")) : i18n.t("api:enterNewApiKey").replace("{key}", currentConfig.key ? formatApiKeyDisplay(currentConfig.key) : i18n.t("common:none"));
    const { key } = await inquirer.prompt({
      type: "input",
      name: "key",
      message: keyMessage,
      validate: async (value) => {
        if (!value) {
          return i18n.t("api:keyRequired");
        }
        const validation = validateApiKey(value);
        if (!validation.isValid) {
          return validation.error || i18n.t("api:invalidKeyFormat");
        }
        return true;
      }
    });
    if (key === void 0) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return;
    }
    currentConfig.key = key;
    const savedConfig = configureApi(currentConfig);
    if (savedConfig) {
      console.log(a.green(`\u2714 ${i18n.t("api:modificationSaved")}`));
      console.log(a.gray(`  ${i18n.t("api:apiConfigKey")}: ${formatApiKeyDisplay(savedConfig.key)}`));
    }
  } else if (item === "authType") {
    const { authType } = await inquirer.prompt({
      type: "list",
      name: "authType",
      message: i18n.t("api:selectNewAuthType").replace("{type}", currentConfig.authType || i18n.t("common:none")),
      choices: addNumbersToChoices([
        { name: "Auth Token (OAuth)", value: "auth_token" },
        { name: "API Key", value: "api_key" }
      ]),
      default: currentConfig.authType === "api_key" ? 1 : 0
    });
    if (authType === void 0) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return;
    }
    currentConfig.authType = authType;
    const savedConfig = configureApi(currentConfig);
    if (savedConfig) {
      console.log(a.green(`\u2714 ${i18n.t("api:modificationSaved")}`));
      console.log(a.gray(`  ${i18n.t("api:apiConfigAuthType")}: ${savedConfig.authType}`));
    }
  }
}
async function updatePromptOnly(aiOutputLang, codeTool) {
  ensureI18nInitialized();
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const backupDir = backupExistingConfig(target.codeTool);
  if (backupDir) {
    console.log(a.gray(`\u2714 ${i18n.t("configuration:backupSuccess")}: ${backupDir}`));
  }
  if (aiOutputLang) {
    applyAiLanguageDirective(aiOutputLang, target.codeTool);
  }
  await configureOutputStyle(void 0, void 0, target.codeTool);
  console.log(a.green(`\u2714 ${i18n.t("configuration:configSuccess")} ${target.configDir}`));
  console.log(`
${a.green(i18n.t("common:complete"))}`);
}

export { configureApiCompletely as c, formatApiKeyDisplay as f, modifyApiConfigPartially as m, updatePromptOnly as u, validateApiKey as v };
