import { fileURLToPath } from 'node:url';
import a from './index5.mjs';
import { d as dayjs } from '../shared/ccjk.RyizuzOI.mjs';
import { i as inquirer } from './index6.mjs';
import { readFileSync } from 'node:fs';
import { CLAUDE_VSC_CONFIG_FILE, AI_OUTPUT_LANGUAGES, SETTINGS_FILE } from './constants.mjs';
import { ensureI18nInitialized, i18n } from './index2.mjs';
import { h as setPrimaryApiKey, i as addCompletedOnboarding, e as deepMerge } from './claude-config.mjs';
import { r as resolveClaudeFamilySettingsTarget, n as normalizeClaudeFamilySettings } from '../shared/ccjk.DDL-4C-k.mjs';
import { exists, ensureDir, copyDir, writeFileAtomic, copyFile } from './fs-operations.mjs';
import { readJsonConfig, writeJsonConfig } from './json-config.mjs';
import { j as join, d as dirname } from '../shared/ccjk.bQ7Dh1g4.mjs';

const MODEL_ENV_KEYS = [
  "ANTHROPIC_MODEL",
  "ANTHROPIC_DEFAULT_HAIKU_MODEL",
  "ANTHROPIC_DEFAULT_SONNET_MODEL",
  "ANTHROPIC_DEFAULT_OPUS_MODEL",
  // Deprecated but still cleaned to avoid stale values
  "ANTHROPIC_SMALL_FAST_MODEL"
];
function clearModelEnv(env, mode = "reset") {
  for (const key of MODEL_ENV_KEYS) {
    if (mode === "reset" && key === "ANTHROPIC_MODEL") {
      env[key] = "";
    } else {
      delete env[key];
    }
  }
}

const INVALID_PERMISSION_NAMES = /* @__PURE__ */ new Set([
  "AllowEdit",
  "AllowWrite",
  "AllowRead",
  "AllowExec",
  "AllowCreateProcess",
  "AllowKillProcess",
  "AllowNetworkAccess",
  "AllowFileSystemAccess",
  "AllowShellAccess",
  "AllowHttpAccess"
]);
function isValidPermission(perm) {
  if (INVALID_PERMISSION_NAMES.has(perm)) {
    return false;
  }
  if (["mcp__.*", "mcp__*", "mcp__(*)"].includes(perm)) {
    return false;
  }
  if (/^[a-z]/.test(perm) && !perm.startsWith("mcp__")) {
    return false;
  }
  return true;
}
function isCoveredByWildcard(perm, wildcardPerm) {
  const wildcardMatch = wildcardPerm.match(/^(\w+)\((.+)\)$/);
  if (!wildcardMatch)
    return false;
  const [, tool, wildcardArg] = wildcardMatch;
  if (!wildcardArg.includes("*"))
    return false;
  const permMatch = perm.match(/^(\w+)\((.+)\)$/);
  if (!permMatch)
    return false;
  const [, permTool, permArg] = permMatch;
  if (tool !== permTool)
    return false;
  const regexStr = wildcardArg.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".+");
  return new RegExp(`^${regexStr}$`).test(permArg);
}
function mergeAndCleanPermissions(templatePermissions, userPermissions) {
  const template = templatePermissions || [];
  const user = userPermissions || [];
  const result = [...template];
  for (const perm of user) {
    if (result.includes(perm)) {
      continue;
    }
    if (!isValidPermission(perm)) {
      continue;
    }
    let isRedundant = false;
    for (const templatePerm of template) {
      if (perm.startsWith(`${templatePerm}(`)) {
        isRedundant = true;
        break;
      }
      if (isCoveredByWildcard(perm, templatePerm)) {
        isRedundant = true;
        break;
      }
    }
    if (!isRedundant) {
      result.push(perm);
    }
  }
  return result;
}

const BUILTIN_MODEL_VALUES = ["opus", "sonnet", "sonnet[1m]"];
function clearLegacyTopLevelRuntimeSettings(settings) {
  delete settings.baseUrl;
  delete settings.apiProvider;
  delete settings.apiUrl;
  delete settings.apiKey;
  delete settings.authToken;
  delete settings.defaultModel;
  delete settings.preferredModel;
}
function hasAdaptiveRoutingEnv(settings) {
  return Boolean(
    settings.env?.ANTHROPIC_DEFAULT_HAIKU_MODEL || settings.env?.ANTHROPIC_DEFAULT_SONNET_MODEL || settings.env?.ANTHROPIC_DEFAULT_OPUS_MODEL
  );
}
function ensureClaudeDir(codeTool) {
  ensureDir(resolveClaudeFamilySettingsTarget(codeTool).configDir);
}
function backupExistingConfig(codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  if (!exists(target.configDir)) {
    return null;
  }
  const timestamp = dayjs().format("YYYY-MM-DD_HH-mm-ss");
  const backupBaseDir = join(target.configDir, target.runtimeBackupDirName);
  const backupDir = join(backupBaseDir, `backup_${timestamp}`);
  ensureDir(backupDir);
  const filter = (path) => {
    return !path.includes("/backup") && !path.includes("/backups");
  };
  copyDir(target.configDir, backupDir, { filter });
  return backupDir;
}
function copyConfigFiles(onlyMd = false, codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const currentFilePath = fileURLToPath(import.meta.url);
  const distDir = dirname(dirname(currentFilePath));
  const rootDir = dirname(distDir);
  const baseTemplateDir = join(rootDir, "templates", "claude-code");
  if (!onlyMd) {
    const baseSettingsPath = join(baseTemplateDir, "common", "settings.json");
    const destSettingsPath = target.settingsFile;
    if (exists(baseSettingsPath)) {
      mergeSettingsFile(baseSettingsPath, destSettingsPath);
    }
  }
}
function getDefaultSettings() {
  try {
    const currentFilePath = fileURLToPath(import.meta.url);
    const distDir = dirname(dirname(currentFilePath));
    const rootDir = dirname(distDir);
    const templateSettingsPath = join(rootDir, "templates", "claude-code", "common", "settings.json");
    return readJsonConfig(templateSettingsPath) || {};
  } catch (error) {
    console.error("Failed to read template settings", error);
    return {};
  }
}
function configureApi(apiConfig, codeTool) {
  if (!apiConfig)
    return null;
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const existingSettings = readJsonConfig(target.settingsFile);
  let settings;
  if (existingSettings) {
    settings = existingSettings;
  } else {
    settings = getDefaultSettings();
  }
  if (!settings.env) {
    settings.env = {};
  }
  clearLegacyTopLevelRuntimeSettings(settings);
  if (apiConfig.authType === "api_key") {
    settings.env.ANTHROPIC_API_KEY = apiConfig.key;
    delete settings.env.ANTHROPIC_AUTH_TOKEN;
  } else if (apiConfig.authType === "auth_token") {
    settings.env.ANTHROPIC_AUTH_TOKEN = apiConfig.key;
    delete settings.env.ANTHROPIC_API_KEY;
  }
  if (apiConfig.url) {
    settings.env.ANTHROPIC_BASE_URL = apiConfig.url;
  }
  normalizeClaudeFamilySettings(settings);
  writeJsonConfig(target.settingsFile, settings);
  if (apiConfig.authType && target.codeTool === "claude-code") {
    try {
      setPrimaryApiKey(target.codeTool);
    } catch (error) {
      ensureI18nInitialized();
      console.error(i18n.t("mcp:primaryApiKeySetFailed"), error);
    }
  }
  try {
    addCompletedOnboarding(target.codeTool);
  } catch (error) {
    console.error("Failed to set onboarding flag", error);
  }
  const verification = readJsonConfig(target.settingsFile);
  if (verification?.env) {
    const envKey = apiConfig.authType === "api_key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN";
    if (verification.env[envKey] !== apiConfig.key) {
      console.error(a.red("\u26A0 API config write verification failed \u2014 retrying..."));
      const freshSettings = readJsonConfig(target.settingsFile) || settings;
      clearLegacyTopLevelRuntimeSettings(freshSettings);
      if (!freshSettings.env)
        freshSettings.env = {};
      if (apiConfig.authType === "api_key") {
        freshSettings.env.ANTHROPIC_API_KEY = apiConfig.key;
        delete freshSettings.env.ANTHROPIC_AUTH_TOKEN;
      } else if (apiConfig.authType === "auth_token") {
        freshSettings.env.ANTHROPIC_AUTH_TOKEN = apiConfig.key;
        delete freshSettings.env.ANTHROPIC_API_KEY;
      }
      if (apiConfig.url) {
        freshSettings.env.ANTHROPIC_BASE_URL = apiConfig.url;
      }
      normalizeClaudeFamilySettings(freshSettings);
      writeJsonConfig(target.settingsFile, freshSettings);
    }
  }
  return apiConfig;
}
function configureHooks(hooks) {
  let settings = getDefaultSettings();
  const existingSettings = readJsonConfig(SETTINGS_FILE);
  if (existingSettings) {
    settings = existingSettings;
  }
  settings.hooks = {
    ...settings.hooks || {},
    ...hooks
  };
  normalizeClaudeFamilySettings(settings);
  writeJsonConfig(SETTINGS_FILE, settings);
}
function mergeConfigs(sourceFile, targetFile) {
  if (!exists(sourceFile))
    return;
  const target = readJsonConfig(targetFile) || {};
  const source = readJsonConfig(sourceFile) || {};
  const merged = deepMerge(target, source);
  normalizeClaudeFamilySettings(merged);
  writeJsonConfig(targetFile, merged);
}
function overwriteModelSettings(settings, {
  primaryModel,
  haikuModel,
  sonnetModel,
  opusModel
}, mode = "override") {
  settings.env = settings.env || {};
  clearModelEnv(settings.env, mode);
  delete settings.model;
  const hasAdaptiveRouting = Boolean(haikuModel?.trim() || sonnetModel?.trim() || opusModel?.trim());
  if (primaryModel?.trim() && !hasAdaptiveRouting) {
    settings.model = primaryModel.trim();
  }
  if (haikuModel?.trim()) {
    settings.env.ANTHROPIC_SMALL_FAST_MODEL = haikuModel.trim();
    settings.env.ANTHROPIC_DEFAULT_HAIKU_MODEL = haikuModel.trim();
  }
  if (sonnetModel?.trim()) {
    settings.env.ANTHROPIC_DEFAULT_SONNET_MODEL = sonnetModel.trim();
  }
  if (opusModel?.trim()) {
    settings.env.ANTHROPIC_DEFAULT_OPUS_MODEL = opusModel.trim();
  }
  return settings;
}
function updateCustomModel(primaryModel, haikuModel, sonnetModel, opusModel, codeTool) {
  if (!primaryModel?.trim() && !haikuModel?.trim() && !sonnetModel?.trim() && !opusModel?.trim()) {
    return;
  }
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  let settings = getDefaultSettings();
  const existingSettings = readJsonConfig(target.settingsFile);
  if (existingSettings) {
    settings = existingSettings;
  }
  clearLegacyTopLevelRuntimeSettings(settings);
  overwriteModelSettings(settings, {
    primaryModel,
    haikuModel,
    sonnetModel,
    opusModel
  }, "override");
  normalizeClaudeFamilySettings(settings);
  writeJsonConfig(target.settingsFile, settings);
}
function updateDefaultModel(model, codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  let settings = getDefaultSettings();
  const existingSettings = readJsonConfig(target.settingsFile);
  if (existingSettings) {
    settings = existingSettings;
  }
  clearLegacyTopLevelRuntimeSettings(settings);
  if (!settings.env) {
    settings.env = {};
  }
  if (model !== "custom") {
    clearModelEnv(settings.env);
  }
  if (model === "default" || model === "custom") {
    delete settings.model;
  } else {
    settings.model = model;
  }
  normalizeClaudeFamilySettings(settings);
  writeJsonConfig(target.settingsFile, settings);
}
function mergeSettingsFile(templatePath, targetPath) {
  try {
    const templateSettings = readJsonConfig(templatePath);
    if (!templateSettings) {
      console.error("Failed to read template settings");
      return;
    }
    if (!exists(targetPath)) {
      copyFile(templatePath, targetPath);
      return;
    }
    const existingSettings = readJsonConfig(targetPath) || {};
    const mergedEnv = {
      ...templateSettings.env || {},
      // Template env vars first
      ...existingSettings.env || {}
      // User's env vars override (preserving API keys, etc.)
    };
    const mergedSettings = { ...templateSettings };
    const schemaCriticalFields = [
      "$schema",
      "attribution",
      "fileSuggestion",
      "permissions"
    ];
    const removeNullFields = [
      "plansDirectory",
      "contextFiles"
    ];
    for (const [key, value] of Object.entries(existingSettings)) {
      if (!schemaCriticalFields.includes(key)) {
        if (removeNullFields.includes(key) && value === null) {
          continue;
        }
        mergedSettings[key] = value;
      }
    }
    mergedSettings.env = mergedEnv;
    if (mergedSettings.model === "default") {
      delete mergedSettings.model;
    }
    if (mergedSettings.model && hasAdaptiveRoutingEnv(mergedSettings)) {
      delete mergedSettings.model;
    }
    if (mergedSettings.permissions && mergedSettings.permissions.allow) {
      mergedSettings.permissions.allow = mergeAndCleanPermissions(
        templateSettings.permissions?.allow,
        existingSettings.permissions?.allow
      );
    }
    if (mergedSettings.plansDirectory === null) {
      delete mergedSettings.plansDirectory;
    }
    normalizeClaudeFamilySettings(mergedSettings);
    writeJsonConfig(targetPath, mergedSettings);
  } catch (error) {
    console.error("Failed to merge settings", error);
    if (exists(targetPath)) {
      console.log("Preserving existing settings");
    } else {
      copyFile(templatePath, targetPath);
    }
  }
}
function getExistingModelConfig(codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const settings = readJsonConfig(target.settingsFile);
  if (!settings) {
    return null;
  }
  const hasModelEnv = MODEL_ENV_KEYS.filter((key) => key !== "ANTHROPIC_MODEL").some((key) => {
    const value = settings.env?.[key];
    return value !== void 0 && value !== null && value !== "";
  });
  if (hasModelEnv) {
    return "custom";
  }
  if (!settings.model || settings.model === "default") {
    return "default";
  }
  if (BUILTIN_MODEL_VALUES.includes(settings.model)) {
    return settings.model;
  }
  return "custom";
}
function getExistingCustomModelConfig(codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const settings = readJsonConfig(target.settingsFile);
  if (!settings) {
    return null;
  }
  const {
    ANTHROPIC_SMALL_FAST_MODEL,
    ANTHROPIC_DEFAULT_HAIKU_MODEL,
    ANTHROPIC_DEFAULT_SONNET_MODEL,
    ANTHROPIC_DEFAULT_OPUS_MODEL
  } = settings.env || {};
  const primaryModel = settings.model && settings.model !== "default" && !BUILTIN_MODEL_VALUES.includes(settings.model) ? settings.model : settings.env?.ANTHROPIC_MODEL;
  if (!primaryModel && !ANTHROPIC_DEFAULT_HAIKU_MODEL && !ANTHROPIC_DEFAULT_SONNET_MODEL && !ANTHROPIC_DEFAULT_OPUS_MODEL) {
    return null;
  }
  return {
    primaryModel,
    haikuModel: ANTHROPIC_DEFAULT_HAIKU_MODEL || ANTHROPIC_SMALL_FAST_MODEL,
    sonnetModel: ANTHROPIC_DEFAULT_SONNET_MODEL,
    opusModel: ANTHROPIC_DEFAULT_OPUS_MODEL
  };
}
function getExistingApiConfig(codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const settings = readJsonConfig(target.settingsFile);
  if (!settings || !settings.env) {
    return null;
  }
  const { ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL } = settings.env;
  if (!ANTHROPIC_BASE_URL && !ANTHROPIC_API_KEY && !ANTHROPIC_AUTH_TOKEN) {
    return null;
  }
  let authType;
  let key;
  if (ANTHROPIC_AUTH_TOKEN) {
    authType = "auth_token";
    key = ANTHROPIC_AUTH_TOKEN;
  } else if (ANTHROPIC_API_KEY) {
    authType = "api_key";
    key = ANTHROPIC_API_KEY;
  }
  return {
    url: ANTHROPIC_BASE_URL || "",
    key: key || "",
    authType
  };
}
function applyAiLanguageDirective(aiOutputLang, codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const instructionsFile = target.instructionsFile;
  let directive = "";
  if (aiOutputLang === "custom") {
    return;
  } else if (AI_OUTPUT_LANGUAGES[aiOutputLang]) {
    directive = AI_OUTPUT_LANGUAGES[aiOutputLang].directive;
  } else {
    directive = `Always respond in ${aiOutputLang}`;
  }
  let baseline = "";
  try {
    const currentFilePath = fileURLToPath(import.meta.url);
    const distDir = dirname(dirname(currentFilePath));
    const rootDir = dirname(distDir);
    const baselinePath = join(rootDir, "templates", "common", "karpathy-baseline.md");
    if (exists(baselinePath)) {
      baseline = readFileSync(baselinePath, "utf-8").trim();
    }
  } catch {
  }
  const frontmatter = target.codeTool === "clavue" ? "" : "---\nscope: user\n---\n\n";
  const body = baseline ? `${directive}

${baseline}
` : directive;
  writeFileAtomic(instructionsFile, `${frontmatter}${body}`);
}
function switchToOfficialLogin(codeTool) {
  try {
    ensureI18nInitialized();
    const target = resolveClaudeFamilySettingsTarget(codeTool);
    const settings = readJsonConfig(target.settingsFile) || {};
    if (settings.env) {
      delete settings.env.ANTHROPIC_BASE_URL;
      delete settings.env.ANTHROPIC_AUTH_TOKEN;
      delete settings.env.ANTHROPIC_API_KEY;
    }
    normalizeClaudeFamilySettings(settings);
    writeJsonConfig(target.settingsFile, settings);
    if (target.codeTool === "claude-code") {
      const vscConfig = readJsonConfig(CLAUDE_VSC_CONFIG_FILE);
      if (vscConfig) {
        delete vscConfig.primaryApiKey;
        writeJsonConfig(CLAUDE_VSC_CONFIG_FILE, vscConfig);
      }
    }
    console.log(i18n.t("api:officialLoginConfigured"));
    return true;
  } catch (error) {
    ensureI18nInitialized();
    console.error(i18n.t("api:officialLoginFailed"), error);
    return false;
  }
}
async function promptApiConfigurationAction() {
  ensureI18nInitialized();
  const existingConfig = getExistingApiConfig();
  if (!existingConfig) {
    return null;
  }
  console.log(`
${a.green(`\u2139 ${i18n.t("api:existingApiConfig")}`)}`);
  console.log(a.gray(`  ${i18n.t("api:apiConfigUrl")}: ${existingConfig.url || "N/A"}`));
  console.log(a.gray(`  ${i18n.t("api:apiConfigKey")}: ${existingConfig.key ? `***${existingConfig.key.slice(-4)}` : "N/A"}`));
  console.log(a.gray(`  ${i18n.t("api:apiConfigAuthType")}: ${existingConfig.authType || "N/A"}
`));
  const { choice } = await inquirer.prompt({
    type: "list",
    name: "choice",
    message: i18n.t("api:selectCustomConfigAction"),
    choices: [
      {
        name: i18n.t("api:modifyPartialConfig"),
        value: "modify-partial"
      },
      {
        name: i18n.t("api:modifyAllConfig"),
        value: "modify-all"
      },
      {
        name: i18n.t("api:keepExistingConfig"),
        value: "keep-existing"
      }
    ]
  });
  return choice || null;
}

const config = {
  __proto__: null,
  applyAiLanguageDirective: applyAiLanguageDirective,
  backupExistingConfig: backupExistingConfig,
  clearLegacyTopLevelRuntimeSettings: clearLegacyTopLevelRuntimeSettings,
  configureApi: configureApi,
  configureHooks: configureHooks,
  copyConfigFiles: copyConfigFiles,
  ensureClaudeDir: ensureClaudeDir,
  getExistingApiConfig: getExistingApiConfig,
  getExistingCustomModelConfig: getExistingCustomModelConfig,
  getExistingModelConfig: getExistingModelConfig,
  mergeConfigs: mergeConfigs,
  mergeSettingsFile: mergeSettingsFile,
  overwriteModelSettings: overwriteModelSettings,
  promptApiConfigurationAction: promptApiConfigurationAction,
  switchToOfficialLogin: switchToOfficialLogin,
  updateCustomModel: updateCustomModel,
  updateDefaultModel: updateDefaultModel
};

export { getExistingCustomModelConfig as a, backupExistingConfig as b, copyConfigFiles as c, updateDefaultModel as d, getExistingApiConfig as e, configureApi as f, getExistingModelConfig as g, clearLegacyTopLevelRuntimeSettings as h, applyAiLanguageDirective as i, ensureClaudeDir as j, config as k, mergeAndCleanPermissions as m, overwriteModelSettings as o, promptApiConfigurationAction as p, switchToOfficialLogin as s, updateCustomModel as u };
