import { chmodSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { ZCF_CONFIG_FILE, ZCF_CONFIG_DIR, CLAVUE_CONFIG_FILE, CLAVUE_CREDENTIALS_FILE, CLAVUE_SETTINGS_FILE, CLAVUE_DIR } from './constants.mjs';
import { d as dayjs } from '../shared/ccjk.RyizuzOI.mjs';
import { readDefaultTomlConfig, createDefaultTomlConfig, writeTomlConfig } from './ccjk-config.mjs';
import { r as resolveClaudeFamilySettingsTarget, n as normalizeClaudeFamilySettings } from '../shared/ccjk.DDL-4C-k.mjs';
import { h as clearLegacyTopLevelRuntimeSettings, o as overwriteModelSettings } from './config.mjs';
import { ensureDir, exists, copyFile } from './fs-operations.mjs';
import { readJsonConfig, writeJsonConfig } from './json-config.mjs';
import { j as join, d as dirname } from '../shared/ccjk.bQ7Dh1g4.mjs';

class ClaudeCodeConfigManager {
  static CONFIG_FILE = ZCF_CONFIG_FILE;
  static LEGACY_CONFIG_FILE = join(ZCF_CONFIG_DIR, "claude-code-configs.json");
  /**
   * Ensure configuration directory exists
   */
  static ensureConfigDir() {
    ensureDir(ZCF_CONFIG_DIR);
  }
  /**
   * Read TOML configuration
   */
  static readTomlConfig() {
    return readDefaultTomlConfig();
  }
  /**
   * Load TOML configuration, falling back to default when missing
   */
  static loadTomlConfig() {
    const existingConfig = this.readTomlConfig();
    if (existingConfig) {
      return existingConfig;
    }
    return createDefaultTomlConfig();
  }
  /**
   * Migrate legacy JSON-based configuration into TOML storage
   */
  static migrateFromLegacyConfig() {
    if (!exists(this.LEGACY_CONFIG_FILE)) {
      return null;
    }
    try {
      const legacyConfig = readJsonConfig(this.LEGACY_CONFIG_FILE);
      if (!legacyConfig) {
        return null;
      }
      const normalizedProfiles = {};
      const existingKeys = /* @__PURE__ */ new Set();
      let migratedCurrentKey = "";
      Object.entries(legacyConfig.profiles || {}).forEach(([legacyKey, profile]) => {
        const sourceProfile = profile;
        const name = sourceProfile.name?.trim() || legacyKey;
        const baseKey = this.generateProfileId(name);
        let uniqueKey = baseKey || legacyKey;
        let suffix = 2;
        while (existingKeys.has(uniqueKey)) {
          uniqueKey = `${baseKey || legacyKey}-${suffix++}`;
        }
        existingKeys.add(uniqueKey);
        const sanitizedProfile = this.sanitizeProfile({
          ...sourceProfile,
          name
        });
        normalizedProfiles[uniqueKey] = {
          ...sanitizedProfile,
          id: uniqueKey
        };
        if (legacyConfig.currentProfileId === legacyKey || legacyConfig.currentProfileId === sourceProfile.id) {
          migratedCurrentKey = uniqueKey;
        }
      });
      if (!migratedCurrentKey && legacyConfig.currentProfileId) {
        const fallbackKey = this.generateProfileId(legacyConfig.currentProfileId);
        if (existingKeys.has(fallbackKey)) {
          migratedCurrentKey = fallbackKey;
        }
      }
      if (!migratedCurrentKey && existingKeys.size > 0) {
        migratedCurrentKey = Array.from(existingKeys)[0];
      }
      const migratedConfig = {
        currentProfileId: migratedCurrentKey,
        profiles: normalizedProfiles
      };
      this.writeConfig(migratedConfig);
      return migratedConfig;
    } catch (error) {
      console.error("Failed to migrate legacy Claude Code config:", error);
      return null;
    }
  }
  /**
   * Read configuration
   */
  static readConfig() {
    try {
      const tomlConfig = readDefaultTomlConfig();
      if (!tomlConfig || !tomlConfig.claudeCode) {
        return this.migrateFromLegacyConfig();
      }
      const { claudeCode } = tomlConfig;
      const rawProfiles = claudeCode.profiles || {};
      const sanitizedProfiles = Object.fromEntries(
        Object.entries(rawProfiles).map(([key, profile]) => {
          const storedProfile = this.sanitizeProfile({
            ...profile,
            name: profile.name || key
          });
          return [key, { ...storedProfile, id: key }];
        })
      );
      const configData = {
        currentProfileId: claudeCode.currentProfile || "",
        profiles: sanitizedProfiles
      };
      if (Object.keys(configData.profiles).length === 0) {
        const migrated = this.migrateFromLegacyConfig();
        if (migrated) {
          return migrated;
        }
      }
      return configData;
    } catch (error) {
      console.error("Failed to read Claude Code config:", error);
      return null;
    }
  }
  /**
   * Write configuration
   */
  static writeConfig(config) {
    try {
      this.ensureConfigDir();
      const keyMap = /* @__PURE__ */ new Map();
      const sanitizedProfiles = Object.fromEntries(
        Object.entries(config.profiles).map(([key, profile]) => {
          const normalizedName = profile.name?.trim() || key;
          const profileKey = this.generateProfileId(normalizedName);
          keyMap.set(key, profileKey);
          const sanitizedProfile = this.sanitizeProfile({
            ...profile,
            name: normalizedName
          });
          return [profileKey, sanitizedProfile];
        })
      );
      const tomlConfig = this.loadTomlConfig();
      const nextTomlConfig = {
        ...tomlConfig,
        claudeCode: {
          ...tomlConfig.claudeCode,
          currentProfile: keyMap.get(config.currentProfileId) || config.currentProfileId,
          profiles: sanitizedProfiles
        }
      };
      writeTomlConfig(this.CONFIG_FILE, nextTomlConfig);
    } catch (error) {
      console.error("Failed to write Claude Code config:", error);
      throw new Error(`Failed to write config: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  /**
   * Create empty configuration
   */
  static createEmptyConfig() {
    return {
      currentProfileId: "",
      profiles: {}
    };
  }
  static settingsMatchProfile(settings, profile) {
    const env = settings?.env || {};
    if (!profile) {
      return !settings?.model && !env.ANTHROPIC_MODEL && !env.ANTHROPIC_DEFAULT_HAIKU_MODEL && !env.ANTHROPIC_DEFAULT_SONNET_MODEL && !env.ANTHROPIC_DEFAULT_OPUS_MODEL;
    }
    const expectedPrimary = profile.primaryModel?.trim();
    const expectedHaiku = profile.defaultHaikuModel?.trim();
    const expectedSonnet = profile.defaultSonnetModel?.trim();
    const expectedOpus = profile.defaultOpusModel?.trim();
    const hasExplicitModelConfig = Boolean(expectedPrimary || expectedHaiku || expectedSonnet || expectedOpus);
    if (!hasExplicitModelConfig) {
      return !settings?.model && (env.ANTHROPIC_MODEL === "" || env.ANTHROPIC_MODEL === void 0) && env.ANTHROPIC_DEFAULT_HAIKU_MODEL === void 0 && env.ANTHROPIC_DEFAULT_SONNET_MODEL === void 0 && env.ANTHROPIC_DEFAULT_OPUS_MODEL === void 0;
    }
    const hasAdaptiveRouting = Boolean(expectedHaiku || expectedSonnet || expectedOpus);
    if (hasAdaptiveRouting) {
      return !settings?.model && env.ANTHROPIC_MODEL === void 0 && env.ANTHROPIC_DEFAULT_HAIKU_MODEL === expectedHaiku && env.ANTHROPIC_SMALL_FAST_MODEL === expectedHaiku && env.ANTHROPIC_DEFAULT_SONNET_MODEL === expectedSonnet && env.ANTHROPIC_DEFAULT_OPUS_MODEL === expectedOpus;
    }
    return settings?.model === expectedPrimary && env.ANTHROPIC_MODEL === void 0 && env.ANTHROPIC_DEFAULT_HAIKU_MODEL === expectedHaiku && env.ANTHROPIC_SMALL_FAST_MODEL === expectedHaiku && env.ANTHROPIC_DEFAULT_SONNET_MODEL === expectedSonnet && env.ANTHROPIC_DEFAULT_OPUS_MODEL === expectedOpus;
  }
  static async syncCurrentProfileToSettings() {
    const currentProfile = this.getCurrentProfile();
    await this.applyProfileSettings(currentProfile);
  }
  /**
   * Apply profile settings to Claude Code runtime
   */
  static async applyProfileSettings(profile) {
    const { ensureI18nInitialized, i18n } = await import('./index2.mjs');
    ensureI18nInitialized();
    const target = resolveClaudeFamilySettingsTarget();
    try {
      if (!profile) {
        const { switchToOfficialLogin } = await import('./config.mjs').then(function (n) { return n.k; });
        switchToOfficialLogin(target.codeTool);
        return;
      }
      const { readJsonConfig: readJsonConfig2, writeJsonConfig } = await import('./json-config.mjs');
      const settings = readJsonConfig2(target.settingsFile) || {};
      clearLegacyTopLevelRuntimeSettings(settings);
      if (!settings.env)
        settings.env = {};
      let shouldRestartCcr = false;
      if (profile.authType === "api_key") {
        settings.env.ANTHROPIC_API_KEY = profile.apiKey;
        delete settings.env.ANTHROPIC_AUTH_TOKEN;
      } else if (profile.authType === "auth_token") {
        settings.env.ANTHROPIC_AUTH_TOKEN = profile.apiKey;
        delete settings.env.ANTHROPIC_API_KEY;
      } else if (profile.authType === "ccr_proxy") {
        const { readCcrConfig } = await import('./config2.mjs');
        const ccrConfig = readCcrConfig();
        if (!ccrConfig) {
          throw new Error(i18n.t("ccr:ccrNotConfigured") || "CCR proxy configuration not found");
        }
        const host = ccrConfig.HOST || "127.0.0.1";
        const port = ccrConfig.PORT || 3456;
        const apiKey = ccrConfig.APIKEY || "sk-ccjk-x-ccr";
        settings.env.ANTHROPIC_BASE_URL = `http://${host}:${port}`;
        settings.env.ANTHROPIC_API_KEY = apiKey;
        delete settings.env.ANTHROPIC_AUTH_TOKEN;
        shouldRestartCcr = true;
      }
      if (profile.authType !== "ccr_proxy") {
        if (profile.baseUrl)
          settings.env.ANTHROPIC_BASE_URL = profile.baseUrl;
        else
          delete settings.env.ANTHROPIC_BASE_URL;
      }
      const hasModelConfig = Boolean(
        profile.primaryModel || profile.defaultHaikuModel || profile.defaultSonnetModel || profile.defaultOpusModel
      );
      const modelMode = hasModelConfig ? "override" : "reset";
      overwriteModelSettings(settings, {
        primaryModel: profile.primaryModel,
        haikuModel: profile.defaultHaikuModel,
        sonnetModel: profile.defaultSonnetModel,
        opusModel: profile.defaultOpusModel
      }, modelMode);
      normalizeClaudeFamilySettings(settings);
      writeJsonConfig(target.settingsFile, settings);
      const { setPrimaryApiKey, addCompletedOnboarding } = await import('./claude-config.mjs').then(function (n) { return n.n; });
      setPrimaryApiKey(target.codeTool);
      addCompletedOnboarding(target.codeTool);
      let verifiedSettings = readJsonConfig2(target.settingsFile) || {};
      if (!this.settingsMatchProfile(verifiedSettings, profile)) {
        const repairedSettings = readJsonConfig2(target.settingsFile) || {};
        clearLegacyTopLevelRuntimeSettings(repairedSettings);
        repairedSettings.env = repairedSettings.env || {};
        if (profile?.authType === "api_key") {
          repairedSettings.env.ANTHROPIC_API_KEY = profile.apiKey;
          delete repairedSettings.env.ANTHROPIC_AUTH_TOKEN;
        } else if (profile?.authType === "auth_token") {
          repairedSettings.env.ANTHROPIC_AUTH_TOKEN = profile.apiKey;
          delete repairedSettings.env.ANTHROPIC_API_KEY;
        }
        if (profile?.authType !== "ccr_proxy") {
          if (profile?.baseUrl)
            repairedSettings.env.ANTHROPIC_BASE_URL = profile.baseUrl;
          else
            delete repairedSettings.env.ANTHROPIC_BASE_URL;
        }
        overwriteModelSettings(repairedSettings, {
          primaryModel: profile?.primaryModel,
          haikuModel: profile?.defaultHaikuModel,
          sonnetModel: profile?.defaultSonnetModel,
          opusModel: profile?.defaultOpusModel
        }, profile ? modelMode : "reset");
        normalizeClaudeFamilySettings(repairedSettings);
        writeJsonConfig(target.settingsFile, repairedSettings);
        verifiedSettings = readJsonConfig2(target.settingsFile) || {};
      }
      if (!this.settingsMatchProfile(verifiedSettings, profile)) {
        throw new Error("settings.json verification failed after applying current profile");
      }
      if (shouldRestartCcr) {
        const { runCcrRestart } = await import('./commands.mjs');
        await runCcrRestart();
      }
    } catch (error) {
      const reason = error instanceof Error ? error.message : String(error);
      throw new Error(`${i18n.t("multi-config:failedToApplySettings")}: ${reason}`);
    }
  }
  static async applyCurrentProfile() {
    await this.syncCurrentProfileToSettings();
  }
  /**
   * Remove unsupported fields from profile payload
   */
  static sanitizeProfile(profile) {
    const sanitized = {
      name: profile.name,
      authType: profile.authType
    };
    if (profile.provider)
      sanitized.provider = profile.provider;
    if (profile.apiKey)
      sanitized.apiKey = profile.apiKey;
    if (profile.baseUrl)
      sanitized.baseUrl = profile.baseUrl;
    if (profile.primaryModel)
      sanitized.primaryModel = profile.primaryModel;
    if (profile.defaultHaikuModel)
      sanitized.defaultHaikuModel = profile.defaultHaikuModel;
    if (profile.defaultSonnetModel)
      sanitized.defaultSonnetModel = profile.defaultSonnetModel;
    if (profile.defaultOpusModel)
      sanitized.defaultOpusModel = profile.defaultOpusModel;
    return sanitized;
  }
  /**
   * Backup configuration
   */
  static backupConfig() {
    try {
      if (!exists(this.CONFIG_FILE)) {
        return null;
      }
      const timestamp = dayjs().format("YYYY-MM-DD_HH-mm-ss");
      const backupPath = join(ZCF_CONFIG_DIR, `config.backup.${timestamp}.toml`);
      copyFile(this.CONFIG_FILE, backupPath);
      return backupPath;
    } catch (error) {
      console.error("Failed to backup Claude Code config:", error);
      return null;
    }
  }
  /**
   * Add configuration
   */
  static async addProfile(profile) {
    try {
      const validationErrors = this.validateProfile(profile);
      if (validationErrors.length > 0) {
        return {
          success: false,
          error: `Validation failed: ${validationErrors.join(", ")}`
        };
      }
      const backupPath = this.backupConfig();
      let config = this.readConfig();
      if (!config) {
        config = this.createEmptyConfig();
      }
      if (profile.id && config.profiles[profile.id]) {
        return {
          success: false,
          error: `Profile with ID "${profile.id}" already exists`,
          backupPath: backupPath || void 0
        };
      }
      const normalizedName = profile.name.trim();
      const profileKey = this.generateProfileId(normalizedName);
      const existingNames = Object.values(config.profiles).map((p) => p.name || "");
      if (config.profiles[profileKey] || existingNames.some((name) => name.toLowerCase() === normalizedName.toLowerCase())) {
        return {
          success: false,
          error: `Profile with name "${profile.name}" already exists`,
          backupPath: backupPath || void 0
        };
      }
      const sanitizedProfile = this.sanitizeProfile({
        ...profile,
        name: normalizedName
      });
      const runtimeProfile = {
        ...sanitizedProfile,
        id: profileKey
      };
      config.profiles[profileKey] = runtimeProfile;
      if (!config.currentProfileId) {
        config.currentProfileId = profileKey;
      }
      this.writeConfig(config);
      if (config.currentProfileId === profileKey) {
        await this.syncCurrentProfileToSettings();
      }
      return {
        success: true,
        backupPath: backupPath || void 0,
        addedProfile: runtimeProfile
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * Update configuration
   */
  static async updateProfile(id, data) {
    try {
      const validationErrors = this.validateProfile(data, true);
      if (validationErrors.length > 0) {
        return {
          success: false,
          error: `Validation failed: ${validationErrors.join(", ")}`
        };
      }
      const backupPath = this.backupConfig();
      const config = this.readConfig();
      if (!config || !config.profiles[id]) {
        return {
          success: false,
          error: `Profile with ID "${id}" not found`,
          backupPath: backupPath || void 0
        };
      }
      const existingProfile = config.profiles[id];
      const nextName = data.name !== void 0 ? data.name.trim() : existingProfile.name;
      const nextKey = this.generateProfileId(nextName);
      const nameChanged = nextKey !== id;
      if (nameChanged) {
        const duplicateName = Object.entries(config.profiles).some(([key, profile]) => key !== id && (profile.name || "").toLowerCase() === nextName.toLowerCase());
        if (duplicateName || config.profiles[nextKey]) {
          return {
            success: false,
            error: `Profile with name "${data.name}" already exists`,
            backupPath: backupPath || void 0
          };
        }
      }
      const mergedProfile = this.sanitizeProfile({
        ...existingProfile,
        ...data,
        name: nextName
      });
      if (nameChanged) {
        delete config.profiles[id];
        config.profiles[nextKey] = {
          ...mergedProfile,
          id: nextKey
        };
        if (config.currentProfileId === id) {
          config.currentProfileId = nextKey;
        }
      } else {
        config.profiles[id] = {
          ...mergedProfile,
          id
        };
      }
      this.writeConfig(config);
      if (config.currentProfileId === (nameChanged ? nextKey : id)) {
        await this.syncCurrentProfileToSettings();
      }
      return {
        success: true,
        backupPath: backupPath || void 0,
        updatedProfile: {
          ...mergedProfile,
          id: nameChanged ? nextKey : id
        }
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * Delete configuration
   */
  static async deleteProfile(id) {
    try {
      const backupPath = this.backupConfig();
      const config = this.readConfig();
      if (!config || !config.profiles[id]) {
        return {
          success: false,
          error: `Profile with ID "${id}" not found`,
          backupPath: backupPath || void 0
        };
      }
      const profileCount = Object.keys(config.profiles).length;
      if (profileCount === 1) {
        return {
          success: false,
          error: "Cannot delete the last profile. At least one profile must remain.",
          backupPath: backupPath || void 0
        };
      }
      delete config.profiles[id];
      if (config.currentProfileId === id) {
        const remainingIds = Object.keys(config.profiles);
        config.currentProfileId = remainingIds[0];
      }
      this.writeConfig(config);
      if (config.currentProfileId) {
        await this.syncCurrentProfileToSettings();
      }
      return {
        success: true,
        backupPath: backupPath || void 0,
        remainingProfiles: Object.entries(config.profiles).map(([key, profile]) => ({
          ...profile,
          id: key
        }))
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * Delete multiple configurations
   */
  static async deleteProfiles(ids) {
    try {
      const backupPath = this.backupConfig();
      const config = this.readConfig();
      if (!config) {
        return {
          success: false,
          error: "No configuration found",
          backupPath: backupPath || void 0
        };
      }
      const missingIds = ids.filter((id) => !config.profiles[id]);
      if (missingIds.length > 0) {
        return {
          success: false,
          error: `Profiles not found: ${missingIds.join(", ")}`,
          backupPath: backupPath || void 0
        };
      }
      const remainingCount = Object.keys(config.profiles).length - ids.length;
      if (remainingCount === 0) {
        return {
          success: false,
          error: "Cannot delete all profiles. At least one profile must remain.",
          backupPath: backupPath || void 0
        };
      }
      let newCurrentProfileId;
      ids.forEach((id) => {
        delete config.profiles[id];
      });
      if (ids.includes(config.currentProfileId)) {
        const remainingIds = Object.keys(config.profiles);
        config.currentProfileId = remainingIds[0];
        newCurrentProfileId = config.currentProfileId;
      }
      this.writeConfig(config);
      if (config.currentProfileId) {
        await this.syncCurrentProfileToSettings();
      }
      return {
        success: true,
        backupPath: backupPath || void 0,
        newCurrentProfileId,
        deletedProfiles: ids,
        remainingProfiles: Object.entries(config.profiles).map(([key, profile]) => ({
          ...profile,
          id: key
        }))
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * Generate profile ID from name
   */
  static generateProfileId(name) {
    return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "profile";
  }
  /**
   * Switch configuration
   */
  static async switchProfile(id) {
    try {
      const config = this.readConfig();
      if (!config || !config.profiles[id]) {
        return {
          success: false,
          error: "Profile not found"
        };
      }
      if (config.currentProfileId === id) {
        return { success: true };
      }
      config.currentProfileId = id;
      this.writeConfig(config);
      await this.syncCurrentProfileToSettings();
      return { success: true };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * List all configurations
   */
  static listProfiles() {
    const config = this.readConfig();
    if (!config) {
      return [];
    }
    return Object.values(config.profiles);
  }
  /**
   * Get current configuration
   */
  static getCurrentProfile() {
    const config = this.readConfig();
    if (!config || !config.currentProfileId) {
      return null;
    }
    return config.profiles[config.currentProfileId] || null;
  }
  /**
   * Get configuration by ID
   */
  static getProfileById(id) {
    const config = this.readConfig();
    if (!config) {
      return null;
    }
    return config.profiles[id] || null;
  }
  /**
   * Get configuration by name
   */
  static getProfileByName(name) {
    const config = this.readConfig();
    if (!config) {
      return null;
    }
    return Object.values(config.profiles).find((p) => p.name === name) || null;
  }
  /**
   * Sync CCR configuration
   */
  static async syncCcrProfile() {
    try {
      const { readCcrConfig } = await import('./config2.mjs');
      const ccrConfig = readCcrConfig();
      if (!ccrConfig) {
        await this.ensureCcrProfileExists(ccrConfig);
        return;
      }
      await this.ensureCcrProfileExists(ccrConfig);
    } catch (error) {
      console.error("Failed to sync CCR profile:", error);
    }
  }
  /**
   * 确保CCR配置文件存在
   */
  static async ensureCcrProfileExists(ccrConfig) {
    const config = this.readConfig() || this.createEmptyConfig();
    const ccrProfileId = "ccr-proxy";
    const existingCcrProfile = config.profiles[ccrProfileId];
    if (!ccrConfig) {
      if (existingCcrProfile) {
        delete config.profiles[ccrProfileId];
        if (config.currentProfileId === ccrProfileId) {
          const remainingIds = Object.keys(config.profiles);
          config.currentProfileId = remainingIds[0] || "";
        }
        this.writeConfig(config);
      }
      return;
    }
    const host = ccrConfig.HOST || "127.0.0.1";
    const port = ccrConfig.PORT || 3456;
    const apiKey = ccrConfig.APIKEY || "sk-ccjk-x-ccr";
    const baseUrl = `http://${host}:${port}`;
    const ccrProfile = {
      name: "CCR Proxy",
      authType: "ccr_proxy",
      baseUrl,
      apiKey
    };
    config.profiles[ccrProfileId] = {
      ...ccrProfile,
      id: ccrProfileId
    };
    if (!config.currentProfileId) {
      config.currentProfileId = ccrProfileId;
    }
    this.writeConfig(config);
  }
  /**
   * Switch to official login
   */
  static async switchToOfficial() {
    try {
      const config = this.readConfig();
      if (!config) {
        return { success: true };
      }
      config.currentProfileId = "";
      this.writeConfig(config);
      await this.applyProfileSettings(null);
      return { success: true };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * Switch to CCR proxy
   */
  static async switchToCcr() {
    try {
      await this.syncCcrProfile();
      const config = this.readConfig();
      if (!config || !config.profiles["ccr-proxy"]) {
        return {
          success: false,
          error: "CCR proxy configuration not found. Please configure CCR first."
        };
      }
      return await this.switchProfile("ccr-proxy");
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * Validate configuration
   */
  static validateProfile(profile, isUpdate = false) {
    const errors = [];
    if (!isUpdate && (!profile.name || typeof profile.name !== "string" || profile.name.trim() === "")) {
      errors.push("Profile name is required");
    }
    if (profile.name && typeof profile.name !== "string") {
      errors.push("Profile name must be a string");
    }
    if (profile.authType && !["api_key", "auth_token", "ccr_proxy"].includes(profile.authType)) {
      errors.push("Invalid auth type. Must be one of: api_key, auth_token, ccr_proxy");
    }
    if (profile.authType === "api_key" || profile.authType === "auth_token") {
      if (!profile.apiKey || typeof profile.apiKey !== "string" || profile.apiKey.trim() === "") {
        errors.push("API key is required for api_key and auth_token types");
      }
    }
    if (profile.baseUrl) {
      try {
        new URL(profile.baseUrl);
      } catch {
        errors.push("Invalid base URL format");
      }
    }
    return errors;
  }
  /**
   * 检查是否为最后一个配置
   */
  static isLastProfile(id) {
    const config = this.readConfig();
    if (!config || !config.profiles[id]) {
      return false;
    }
    return Object.keys(config.profiles).length === 1;
  }
}

const claudeCodeConfigManager = {
  __proto__: null,
  ClaudeCodeConfigManager: ClaudeCodeConfigManager
};

function readClavueConfig() {
  return readJsonConfig(CLAVUE_CONFIG_FILE);
}
function writeClavueConfig(config) {
  writeJsonConfig(CLAVUE_CONFIG_FILE, config);
}
function normalizeMyclaudeProviderProfile(profile) {
  return {
    ...profile,
    ...describeMyclaudeProviderProfile(profile)
  };
}
function normalizeClavueBaseUrl(url) {
  if (typeof url !== "string") {
    return void 0;
  }
  const normalized = url.trim().replace(/\/v1(?:\/messages|\/responses)?\/?$/i, "").replace(/\/+$/, "");
  return normalized || void 0;
}
function normalizeClavueAuthType(authType) {
  return authType === "auth_token" ? "auth_token" : "api_key";
}
function inferClavueProviderId(provider, baseUrl) {
  const providerId = typeof provider === "string" ? provider.trim() : "";
  if (providerId && providerId !== "ccr_proxy") {
    return providerId;
  }
  if (baseUrl === "https://api.anthropic.com") {
    return "anthropic";
  }
  return "custom";
}
function isOpenAiFamilyModel(model) {
  return /^(?:gpt-|o\d|codex|kimi|glm|moonshot|deepseek|qwen|doubao|yi-|minimax)/i.test(model.trim());
}
function inferClavueModelMode(profile) {
  if (profile.authType === "ccr_proxy" || profile.mode === "ccr-proxy") {
    return "hybrid_compatible";
  }
  const routedModels = [
    profile.primaryModel,
    profile.model,
    profile.defaultHaikuModel,
    profile.fastModel,
    profile.defaultSonnetModel,
    profile.defaultOpusModel
  ].filter((model) => typeof model === "string" && model.trim().length > 0);
  if (routedModels.length > 0 && routedModels.every(isOpenAiFamilyModel)) {
    return "openai_native";
  }
  if (routedModels.length > 0 && !routedModels.some(isOpenAiFamilyModel)) {
    return "anthropic_native";
  }
  if (routedModels.length > 0) {
    return "hybrid_compatible";
  }
  if (profile.mode === "openai-native") {
    return "openai_native";
  }
  if (!profile.baseUrl || profile.provider === "anthropic" || profile.mode === "official") {
    return "anthropic_native";
  }
  return routedModels.some(isOpenAiFamilyModel) ? "hybrid_compatible" : "anthropic_native";
}
function getClavueRoutingPresetId(profile) {
  const mode = inferClavueModelMode(profile);
  if (mode === "openai_native") {
    return "gpt_5_4_codex";
  }
  if (mode === "anthropic_native") {
    return "claude_code_heritage";
  }
  return "custom";
}
function isCcjkClavueProfile(profile) {
  return profile.provenance?.kind === "imported" && profile.provenance.sourceId === "ccjk";
}
const CCJK_CLAVUE_PROFILE_ID_PREFIX = "ccjk-";
function getSourceProfileId(profile) {
  const id = typeof profile.id === "string" ? profile.id.trim() : "";
  if (id) {
    return id;
  }
  const name = typeof profile.name === "string" ? profile.name.trim() : "";
  return name || "profile";
}
function getCcjkExternalProfileId(profile) {
  const externalProfileId = profile.provenance?.externalProfileId;
  if (typeof externalProfileId === "string" && externalProfileId.trim()) {
    return externalProfileId.trim();
  }
  const profileId = typeof profile.id === "string" ? profile.id.trim() : "";
  if (profileId.startsWith(CCJK_CLAVUE_PROFILE_ID_PREFIX) && profileId.length > CCJK_CLAVUE_PROFILE_ID_PREFIX.length) {
    return profileId.slice(CCJK_CLAVUE_PROFILE_ID_PREFIX.length);
  }
  return profileId || "profile";
}
function getCcjkClavueProfileId(externalProfileId) {
  const cleanExternalId = externalProfileId.trim() || "profile";
  return cleanExternalId.startsWith(CCJK_CLAVUE_PROFILE_ID_PREFIX) ? cleanExternalId : `${CCJK_CLAVUE_PROFILE_ID_PREFIX}${cleanExternalId}`;
}
function getUniqueClavueProfileId(baseProfileId, reservedProfileIds) {
  if (!reservedProfileIds.has(baseProfileId)) {
    return baseProfileId;
  }
  let index = 2;
  let candidate = `${baseProfileId}-${index}`;
  while (reservedProfileIds.has(candidate)) {
    index += 1;
    candidate = `${baseProfileId}-${index}`;
  }
  return candidate;
}
function buildExistingCcjkProfileByExternalId(existingProfiles) {
  const existingByExternalId = /* @__PURE__ */ new Map();
  for (const profile of existingProfiles) {
    if (!isCcjkClavueProfile(profile)) {
      continue;
    }
    const externalProfileId = getCcjkExternalProfileId(profile);
    const current = existingByExternalId.get(externalProfileId);
    if (!current || profile.id.startsWith(CCJK_CLAVUE_PROFILE_ID_PREFIX)) {
      existingByExternalId.set(externalProfileId, profile);
    }
  }
  return existingByExternalId;
}
function resolveClavueProviderProfiles(profiles, existingProfiles) {
  const existingCcjkByExternalId = buildExistingCcjkProfileByExternalId(existingProfiles);
  const reservedProfileIds = new Set(existingProfiles.filter((profile) => !isCcjkClavueProfile(profile)).map((profile) => profile.id));
  return profiles.map((profile) => {
    const externalProfileId = getSourceProfileId(profile);
    const existing = existingCcjkByExternalId.get(externalProfileId);
    const canReuseExistingManagedId = Boolean(
      existing && existing.id.startsWith(CCJK_CLAVUE_PROFILE_ID_PREFIX) && !reservedProfileIds.has(existing.id)
    );
    const clavueProfileId = canReuseExistingManagedId ? existing.id : getUniqueClavueProfileId(getCcjkClavueProfileId(externalProfileId), reservedProfileIds);
    reservedProfileIds.add(clavueProfileId);
    return {
      source: profile,
      clavueProfileId,
      existing
    };
  });
}
function findResolvedClavueProfile(profiles, profileId) {
  const requestedProfileId = typeof profileId === "string" ? profileId.trim() : "";
  if (!requestedProfileId) {
    return void 0;
  }
  return profiles.find((profile) => {
    return profile.clavueProfileId === requestedProfileId || getSourceProfileId(profile.source) === requestedProfileId;
  });
}
function resolveClavueActiveProviderProfileId(config, activeProfileId) {
  const requestedProfileId = typeof activeProfileId === "string" ? activeProfileId.trim() : "";
  if (!requestedProfileId) {
    return void 0;
  }
  const existingProfiles = getClavueProviderProfiles(config);
  if (existingProfiles.some((profile) => profile.id === requestedProfileId)) {
    return requestedProfileId;
  }
  return existingProfiles.find((profile) => {
    return isCcjkClavueProfile(profile) && getCcjkExternalProfileId(profile) === requestedProfileId;
  })?.id || requestedProfileId;
}
function createClavueModelRouting(profile) {
  const primaryModel = (profile.primaryModel || profile.model || "").trim();
  const haikuModel = (profile.defaultHaikuModel || profile.fastModel || "").trim();
  const sonnetModel = (profile.defaultSonnetModel || primaryModel).trim();
  const opusModel = (profile.defaultOpusModel || primaryModel).trim();
  const executionModel = sonnetModel || primaryModel;
  return {
    presetId: getClavueRoutingPresetId(profile),
    primaryModel,
    subagentModel: executionModel && executionModel !== primaryModel ? executionModel : "",
    smallFastModel: haikuModel,
    planModel: opusModel || primaryModel,
    exploreModel: executionModel,
    generalModel: executionModel,
    teamModel: executionModel,
    guideModel: opusModel || primaryModel
  };
}
function toClavueProviderProfile(profile, clavueProfileId, existing) {
  const now = Date.now();
  const normalizedBaseUrl = normalizeClavueBaseUrl(profile.baseUrl);
  const createdAt = typeof existing?.createdAt === "number" ? existing.createdAt : now;
  return {
    id: clavueProfileId,
    name: profile.name,
    providerId: inferClavueProviderId(profile.provider, normalizedBaseUrl),
    modelMode: inferClavueModelMode(profile),
    ...normalizedBaseUrl ? { baseUrl: normalizedBaseUrl } : {},
    authType: normalizeClavueAuthType(profile.authType),
    modelRouting: createClavueModelRouting(profile),
    provenance: {
      kind: "imported",
      sourceId: "ccjk",
      importedAt: typeof existing?.provenance?.importedAt === "number" ? existing.provenance.importedAt : createdAt,
      externalProfileId: getSourceProfileId(profile)
    },
    createdAt,
    updatedAt: now
  };
}
function readClavueCredentialsConfig() {
  return readJsonConfig(CLAVUE_CREDENTIALS_FILE) || {};
}
function writeClavueCredentialsConfig(config) {
  writeJsonConfig(CLAVUE_CREDENTIALS_FILE, config);
  try {
    chmodSync(CLAVUE_CREDENTIALS_FILE, 384);
  } catch {
  }
}
function syncClavueProviderCredentials(profiles, replaceProfileIds = /* @__PURE__ */ new Set()) {
  const existingCredentials = readClavueCredentialsConfig();
  const providerProfiles = { ...existingCredentials.providerProfiles || {} };
  for (const profileId of replaceProfileIds) {
    delete providerProfiles[profileId];
  }
  for (const profile of profiles) {
    const credential = typeof profile.source.apiKey === "string" ? profile.source.apiKey.trim() : "";
    if (!profile.clavueProfileId || !credential) {
      continue;
    }
    providerProfiles[profile.clavueProfileId] = {
      credential,
      authType: normalizeClavueAuthType(profile.source.authType)
    };
  }
  writeClavueCredentialsConfig({
    ...existingCredentials,
    providerProfiles: Object.keys(providerProfiles).length > 0 ? providerProfiles : void 0
  });
}
function getClavueProviderProfiles(config) {
  return Array.isArray(config?.clavueProviderProfiles) ? config.clavueProviderProfiles : [];
}
function getLegacyMyclaudeProviderProfiles(config) {
  return Array.isArray(config?.myclaudeProviderProfiles) ? config.myclaudeProviderProfiles : [];
}
function toLegacyProviderProfile(profile) {
  const routing = profile.modelRouting || createClavueModelRouting({ id: profile.id, name: profile.name, provider: profile.providerId });
  return {
    id: isCcjkClavueProfile(profile) ? getCcjkExternalProfileId(profile) : profile.id,
    name: profile.name,
    provider: profile.providerId || "custom",
    baseUrl: profile.baseUrl,
    model: routing.primaryModel,
    fastModel: routing.smallFastModel,
    authType: profile.authType,
    primaryModel: routing.primaryModel,
    defaultHaikuModel: routing.smallFastModel,
    defaultSonnetModel: routing.generalModel || routing.subagentModel,
    defaultOpusModel: routing.planModel,
    ...describeMyclaudeProviderProfile({
      authType: profile.authType,
      baseUrl: profile.baseUrl,
      mode: profile.modelMode === "openai_native" ? "openai-native" : profile.modelMode === "hybrid_compatible" ? "ccr-proxy" : "official"
    })
  };
}
function normalizeModelSlot(model) {
  return typeof model === "string" && model.trim() ? model.trim() : void 0;
}
function resolveClavueModelSelectionSlots(options) {
  if (options.reset) {
    return {};
  }
  const selectedModel = normalizeModelSlot(options.selectedModel);
  if (selectedModel) {
    return {
      primaryModel: selectedModel,
      haikuModel: selectedModel,
      sonnetModel: selectedModel,
      opusModel: selectedModel
    };
  }
  const primaryModel = normalizeModelSlot(options.primaryModel);
  const haikuModel = normalizeModelSlot(options.haikuModel);
  const sonnetModel = normalizeModelSlot(options.sonnetModel);
  const opusModel = normalizeModelSlot(options.opusModel);
  if (primaryModel) {
    return {
      primaryModel,
      haikuModel: haikuModel || primaryModel,
      sonnetModel: sonnetModel || primaryModel,
      opusModel: opusModel || primaryModel
    };
  }
  return {
    haikuModel,
    sonnetModel,
    opusModel
  };
}
function getClavueActiveProfile(config) {
  const activeId = config?.clavueActiveProviderProfileId || config?.myclaudeActiveProviderProfileId || "";
  const legacyProfiles = getLegacyMyclaudeProviderProfiles(config);
  const activeLegacyProfile = legacyProfiles.find((profile) => profile.id === activeId);
  if (activeLegacyProfile) {
    return activeLegacyProfile;
  }
  const nativeProfiles = getClavueProviderProfiles(config);
  const activeNativeProfile = nativeProfiles.find((profile) => profile.id === activeId);
  if (activeNativeProfile) {
    return toLegacyProviderProfile(activeNativeProfile);
  }
  return nativeProfiles.map(toLegacyProviderProfile).find((profile) => profile.id === activeId) || null;
}
function syncClavueActiveProviderModelSelection(options) {
  const config = readClavueConfig();
  const activeId = config?.clavueActiveProviderProfileId || config?.myclaudeActiveProviderProfileId || "";
  if (!config || !activeId) {
    return false;
  }
  const slots = resolveClavueModelSelectionSlots(options);
  const nativeProfiles = getClavueProviderProfiles(config);
  const nativeProfileIndex = nativeProfiles.findIndex((profile) => profile.id === activeId);
  if (nativeProfileIndex >= 0) {
    const currentProfile = nativeProfiles[nativeProfileIndex];
    const routingProfile = {
      id: currentProfile.id,
      name: currentProfile.name,
      provider: currentProfile.providerId,
      baseUrl: currentProfile.baseUrl,
      authType: currentProfile.authType,
      model: slots.primaryModel,
      fastModel: slots.haikuModel,
      primaryModel: slots.primaryModel,
      defaultHaikuModel: slots.haikuModel,
      defaultSonnetModel: slots.sonnetModel,
      defaultOpusModel: slots.opusModel,
      mode: currentProfile.modelMode === "openai_native" ? "openai-native" : currentProfile.modelMode === "hybrid_compatible" ? "ccr-proxy" : "official"
    };
    const nextProfile = {
      ...currentProfile,
      modelMode: options.reset ? currentProfile.modelMode : inferClavueModelMode(routingProfile),
      modelRouting: createClavueModelRouting(routingProfile),
      updatedAt: Date.now()
    };
    config.clavueProviderProfiles = nativeProfiles.map((profile, index) => index === nativeProfileIndex ? nextProfile : profile);
    delete config.myclaudeProviderProfiles;
    delete config.myclaudeActiveProviderProfileId;
    writeClavueConfig(config);
    syncMyclaudeActiveProfileToSettings(toLegacyProviderProfile(nextProfile));
    return true;
  }
  const legacyProfiles = getLegacyMyclaudeProviderProfiles(config);
  const legacyProfileIndex = legacyProfiles.findIndex((profile) => profile.id === activeId);
  if (legacyProfileIndex < 0) {
    return false;
  }
  const updatedProfiles = legacyProfiles.map((profile, index) => {
    if (index !== legacyProfileIndex) {
      return profile;
    }
    return {
      ...profile,
      model: slots.primaryModel,
      fastModel: slots.haikuModel,
      primaryModel: slots.primaryModel,
      defaultHaikuModel: slots.haikuModel,
      defaultSonnetModel: slots.sonnetModel,
      defaultOpusModel: slots.opusModel
    };
  });
  setMyclaudeProviderProfiles(updatedProfiles, activeId);
  return true;
}
function setMyclaudeProviderProfiles(profiles, activeProfileId) {
  const config = readClavueConfig() || { mcpServers: {} };
  const normalizedProfiles = profiles.map(normalizeMyclaudeProviderProfile);
  const existingProfiles = getClavueProviderProfiles(config);
  const resolvedProfiles = resolveClavueProviderProfiles(normalizedProfiles, existingProfiles);
  const selectedProfile = findResolvedClavueProfile(
    resolvedProfiles,
    activeProfileId ?? (normalizedProfiles[0] ? getSourceProfileId(normalizedProfiles[0]) : void 0)
  );
  const nextActiveProfileId = selectedProfile?.clavueProfileId;
  const existingCcjkProfileIds = new Set(existingProfiles.filter(isCcjkClavueProfile).map((profile) => profile.id));
  const preservedProfiles = existingProfiles.filter((profile) => !isCcjkClavueProfile(profile));
  const preservedProfileIds = new Set(preservedProfiles.map((profile) => profile.id));
  const replacedCredentialIds = new Set([...existingCcjkProfileIds].filter((profileId) => !preservedProfileIds.has(profileId)));
  const clavueProfiles = resolvedProfiles.map((profile) => toClavueProviderProfile(
    profile.source,
    profile.clavueProfileId,
    profile.existing
  ));
  config.clavueProviderProfiles = [...preservedProfiles, ...clavueProfiles];
  if (nextActiveProfileId) {
    config.clavueActiveProviderProfileId = nextActiveProfileId;
  } else {
    delete config.clavueActiveProviderProfileId;
  }
  delete config.myclaudeProviderProfiles;
  delete config.myclaudeActiveProviderProfileId;
  writeClavueConfig(config);
  syncClavueProviderCredentials(resolvedProfiles, replacedCredentialIds);
  const activeProfile = selectedProfile?.source || null;
  syncMyclaudeActiveProfileToSettings(activeProfile);
  return nextActiveProfileId;
}
function setMyclaudeActiveProviderProfile(activeProfileId) {
  const config = readClavueConfig() || { mcpServers: {} };
  const nextActiveProfileId = resolveClavueActiveProviderProfileId(config, activeProfileId);
  if (nextActiveProfileId) {
    config.clavueActiveProviderProfileId = nextActiveProfileId;
  } else {
    delete config.clavueActiveProviderProfileId;
  }
  delete config.myclaudeActiveProviderProfileId;
  writeClavueConfig(config);
  syncMyclaudeActiveProfileToSettings(getClavueActiveProfile(config));
}
function detectMyclaudeProviderMode(profile) {
  if (profile.authType === "ccr_proxy") {
    return "ccr-proxy";
  }
  if (profile.baseUrl) {
    return "openai-native";
  }
  return "official";
}
function describeMyclaudeProviderProfile(profile) {
  const mode = profile.mode || detectMyclaudeProviderMode({
    authType: profile.authType,
    baseUrl: profile.baseUrl
  });
  return { mode };
}
function buildMyclaudeProviderPresentation(profile) {
  const mode = profile.mode || detectMyclaudeProviderMode({
    authType: profile.authType,
    baseUrl: profile.baseUrl
  });
  const hasAdaptiveRouting = Boolean(profile.defaultHaikuModel || profile.defaultSonnetModel || profile.defaultOpusModel);
  const hasPrimaryModel = Boolean(profile.primaryModel || profile.model);
  const modeLabel = mode === "ccr-proxy" ? "CCR-proxy" : mode === "openai-native" ? "OpenAI-native" : "Anthropic-native";
  const routeLabel = mode === "ccr-proxy" ? profile.baseUrl ? `Claude-family route through CCR \xB7 ${profile.baseUrl}` : "Claude-family route through CCR" : mode === "openai-native" ? profile.baseUrl ? `OpenAI-family route through a compatible gateway \xB7 ${profile.baseUrl}` : "OpenAI-family route through a compatible gateway" : "Official Anthropic route";
  const strategyLabel = hasAdaptiveRouting ? "Custom routing \xB7 Advanced custom routing. Validate carefully when mixing model families." : hasPrimaryModel ? "Single-model override \xB7 Primary model is pinned for the active profile." : "Native runtime default \xB7 Runtime follows the official provider defaults.";
  return {
    modeLabel,
    sourceLabel: "Imported from ccjk \xB7 Reusable profile imported from the compatible ccjk configuration.",
    routeLabel,
    strategyLabel
  };
}
function toMyclaudeProviderProfile(profile, existing) {
  return {
    id: profile.id || existing?.id || profile.name,
    name: profile.name,
    provider: profile.provider || existing?.provider || "custom",
    apiKey: profile.apiKey,
    baseUrl: profile.baseUrl,
    model: profile.primaryModel,
    fastModel: profile.defaultHaikuModel,
    authType: profile.authType,
    primaryModel: profile.primaryModel,
    defaultHaikuModel: profile.defaultHaikuModel,
    defaultSonnetModel: profile.defaultSonnetModel,
    defaultOpusModel: profile.defaultOpusModel,
    ...describeMyclaudeProviderProfile({
      authType: profile.authType,
      baseUrl: profile.baseUrl,
      mode: existing?.mode
    })
  };
}
function syncMyclaudeActiveProfileToSettings(profile) {
  const settings = readJsonConfig(CLAVUE_SETTINGS_FILE) || {};
  settings.env = settings.env || {};
  clearLegacyTopLevelRuntimeSettings(settings);
  delete settings.env.ANTHROPIC_API_KEY;
  delete settings.env.ANTHROPIC_AUTH_TOKEN;
  if (profile?.baseUrl) {
    settings.env.ANTHROPIC_BASE_URL = normalizeClavueBaseUrl(profile.baseUrl);
  } else {
    delete settings.env.ANTHROPIC_BASE_URL;
  }
  overwriteModelSettings(settings, {
    primaryModel: typeof profile?.primaryModel === "string" ? profile.primaryModel : typeof profile?.model === "string" ? profile.model : void 0,
    haikuModel: typeof profile?.defaultHaikuModel === "string" ? profile.defaultHaikuModel : typeof profile?.fastModel === "string" ? profile.fastModel : void 0,
    sonnetModel: typeof profile?.defaultSonnetModel === "string" ? profile.defaultSonnetModel : void 0,
    opusModel: typeof profile?.defaultOpusModel === "string" ? profile.defaultOpusModel : void 0
  }, profile ? "override" : "reset");
  const primaryModel = typeof profile?.primaryModel === "string" ? profile.primaryModel.trim() : typeof profile?.model === "string" ? profile.model.trim() : "";
  const subagentModel = typeof profile?.defaultSonnetModel === "string" ? profile.defaultSonnetModel.trim() : "";
  const hasAdaptiveRouting = Boolean(
    typeof profile?.defaultHaikuModel === "string" && profile.defaultHaikuModel.trim() || typeof profile?.defaultSonnetModel === "string" && profile.defaultSonnetModel.trim() || typeof profile?.defaultOpusModel === "string" && profile.defaultOpusModel.trim()
  );
  if (primaryModel && !hasAdaptiveRouting) {
    settings.env.ANTHROPIC_MODEL = primaryModel;
    settings.env.ANTHROPIC_CUSTOM_MODEL_OPTION = primaryModel;
    settings.model = primaryModel;
  } else if (primaryModel) {
    settings.env.ANTHROPIC_CUSTOM_MODEL_OPTION = primaryModel;
    delete settings.env.ANTHROPIC_MODEL;
    delete settings.model;
  } else if (profile) {
    delete settings.env.ANTHROPIC_MODEL;
    delete settings.env.ANTHROPIC_CUSTOM_MODEL_OPTION;
    delete settings.model;
  } else {
    delete settings.env.ANTHROPIC_CUSTOM_MODEL_OPTION;
    delete settings.model;
  }
  if (subagentModel) {
    settings.env.CLAUDE_CODE_SUBAGENT_MODEL = subagentModel;
  } else {
    delete settings.env.CLAUDE_CODE_SUBAGENT_MODEL;
  }
  applyAutoOutputStyle(settings, profile);
  normalizeClaudeFamilySettings(settings);
  writeJsonConfig(CLAVUE_SETTINGS_FILE, settings);
}
function applyAutoOutputStyle(settings, profile) {
  const ccjkMeta = settings.__ccjk && typeof settings.__ccjk === "object" ? settings.__ccjk : {};
  const isCcjkManaged = ccjkMeta.autoOutputStyle === true;
  const currentStyle = typeof settings.outputStyle === "string" ? settings.outputStyle : "";
  if (currentStyle && !isCcjkManaged) {
    return;
  }
  const desired = pickAutoOutputStyle(profile);
  if (desired) {
    ensureOutputStyleTemplate(desired);
    settings.outputStyle = desired;
    settings.__ccjk = { ...ccjkMeta, autoOutputStyle: true };
  } else if (isCcjkManaged) {
    delete settings.outputStyle;
    const { autoOutputStyle: _drop, ...restMeta } = ccjkMeta;
    if (Object.keys(restMeta).length === 0) {
      delete settings.__ccjk;
    } else {
      settings.__ccjk = restMeta;
    }
  }
}
function pickAutoOutputStyle(profile) {
  if (!profile) {
    return null;
  }
  const candidates = [
    profile.primaryModel,
    profile.model,
    profile.defaultSonnetModel,
    profile.defaultOpusModel,
    profile.defaultHaikuModel
  ].filter((m) => typeof m === "string" && m.trim().length > 0);
  if (candidates.length === 0) {
    return null;
  }
  const isCodexFamily = candidates.some((m) => /^(?:gpt-5|codex|gpt-6)/i.test(m.trim()));
  return isCodexFamily ? "codex-rigor-mode" : null;
}
function ensureOutputStyleTemplate(styleId) {
  try {
    const targetDir = join(CLAVUE_DIR, "output-styles");
    const targetFile = join(targetDir, `${styleId}.md`);
    if (exists(targetFile)) {
      return;
    }
    const currentFilePath = fileURLToPath(import.meta.url);
    const distDir = dirname(dirname(currentFilePath));
    const rootDir = dirname(distDir);
    const candidates = [
      join(rootDir, "templates", "common", "output-styles", "zh-CN", `${styleId}.md`),
      join(rootDir, "templates", "common", "output-styles", "en", `${styleId}.md`)
    ];
    const sourcePath = candidates.find(exists);
    if (!sourcePath) {
      return;
    }
    ensureDir(targetDir);
    copyFile(sourcePath, targetFile);
  } catch {
  }
}
function syncMyclaudeProviderProfilesFromClaudeConfig(configData) {
  if (!configData) {
    clearMyclaudeProviderProfiles();
    return {
      activeProfileId: "",
      activeProfile: null,
      profiles: []
    };
  }
  const existingConfig = readClavueConfig();
  const existingProfiles = getLegacyMyclaudeProviderProfiles(existingConfig).length > 0 ? getLegacyMyclaudeProviderProfiles(existingConfig) : getClavueProviderProfiles(existingConfig).map(toLegacyProviderProfile);
  const existingById = new Map(existingProfiles.map((profile) => [String(profile.id), profile]));
  const profiles = Object.entries(configData.profiles).map(([id, profile]) => toMyclaudeProviderProfile({ ...profile, id }, existingById.get(id)));
  const activeProfileId = configData.currentProfileId ?? "";
  const activeProfile = profiles.find((profile) => profile.id === activeProfileId) || null;
  const activeClavueProfileId = setMyclaudeProviderProfiles(profiles, activeProfileId);
  return {
    activeProfileId: activeClavueProfileId || "",
    activeProfile,
    profiles
  };
}
function syncMyclaudeProviderProfilesFromCurrentClaudeConfig() {
  const configData = ClaudeCodeConfigManager.readConfig();
  return syncMyclaudeProviderProfilesFromClaudeConfig(configData);
}
function clearMyclaudeProviderProfiles() {
  const config = readClavueConfig();
  let preservedActiveProfile = null;
  if (config) {
    const existingProfiles = getClavueProviderProfiles(config);
    const removedIds = /* @__PURE__ */ new Set([
      ...existingProfiles.filter(isCcjkClavueProfile).map((profile) => profile.id),
      ...getLegacyMyclaudeProviderProfiles(config).map((profile) => profile.id)
    ]);
    const preservedProfiles = existingProfiles.filter((profile) => !removedIds.has(profile.id));
    const currentActiveId = config.clavueActiveProviderProfileId || config.myclaudeActiveProviderProfileId;
    const nextActiveId = preservedProfiles.some((profile) => profile.id === currentActiveId) ? currentActiveId : preservedProfiles[0]?.id;
    if (preservedProfiles.length > 0) {
      config.clavueProviderProfiles = preservedProfiles;
      config.clavueActiveProviderProfileId = nextActiveId;
      preservedActiveProfile = preservedProfiles.find((profile) => profile.id === nextActiveId) ? toLegacyProviderProfile(preservedProfiles.find((profile) => profile.id === nextActiveId)) : null;
    } else {
      delete config.clavueProviderProfiles;
      delete config.clavueActiveProviderProfileId;
    }
    delete config.myclaudeProviderProfiles;
    delete config.myclaudeActiveProviderProfileId;
    writeClavueConfig(config);
    if (removedIds.size > 0) {
      const credentials = readClavueCredentialsConfig();
      if (credentials.providerProfiles) {
        const nextProviderProfiles = { ...credentials.providerProfiles };
        for (const profileId of removedIds) {
          delete nextProviderProfiles[profileId];
        }
        writeClavueCredentialsConfig({
          ...credentials,
          providerProfiles: Object.keys(nextProviderProfiles).length > 0 ? nextProviderProfiles : void 0
        });
      }
    }
  }
  syncMyclaudeActiveProfileToSettings(preservedActiveProfile);
}

const clavueConfig = {
  __proto__: null,
  buildMyclaudeProviderPresentation: buildMyclaudeProviderPresentation,
  clearMyclaudeProviderProfiles: clearMyclaudeProviderProfiles,
  describeMyclaudeProviderProfile: describeMyclaudeProviderProfile,
  readClavueConfig: readClavueConfig,
  setMyclaudeActiveProviderProfile: setMyclaudeActiveProviderProfile,
  setMyclaudeProviderProfiles: setMyclaudeProviderProfiles,
  syncClavueActiveProviderModelSelection: syncClavueActiveProviderModelSelection,
  syncMyclaudeProviderProfilesFromClaudeConfig: syncMyclaudeProviderProfilesFromClaudeConfig,
  syncMyclaudeProviderProfilesFromCurrentClaudeConfig: syncMyclaudeProviderProfilesFromCurrentClaudeConfig,
  writeClavueConfig: writeClavueConfig
};

export { ClaudeCodeConfigManager as C, setMyclaudeActiveProviderProfile as a, syncMyclaudeProviderProfilesFromClaudeConfig as b, setMyclaudeProviderProfiles as c, clearMyclaudeProviderProfiles as d, buildMyclaudeProviderPresentation as e, claudeCodeConfigManager as f, clavueConfig as g, syncClavueActiveProviderModelSelection as s };
