import { existsSync, mkdirSync, renameSync, copyFileSync, rmSync } from 'node:fs';
import { p as parse } from '../shared/ccjk.BBtCGd_g.mjs';
import { stringify } from './index3.mjs';
import { DEFAULT_CODE_TOOL_TYPE, ZCF_CONFIG_FILE, LEGACY_ZCF_CONFIG_FILES, ZCF_CONFIG_DIR, isCodeToolType, SUPPORTED_LANGS } from './constants.mjs';
import { exists, readFile, ensureDir, writeFileAtomic } from './fs-operations.mjs';
import { readJsonConfig } from './json-config.mjs';
import { d as dirname } from '../shared/ccjk.bQ7Dh1g4.mjs';
import 'node:os';
import './index2.mjs';
import 'node:process';
import 'node:url';
import 'node:crypto';
import 'node:fs/promises';
import '../shared/ccjk.RyizuzOI.mjs';
import '../shared/ccjk.BAGoDD49.mjs';

function isSupportedLang(value) {
  return SUPPORTED_LANGS.includes(value);
}
function sanitizePreferredLang(lang) {
  return isSupportedLang(lang) ? lang : "en";
}
function sanitizeCodeToolType(codeTool) {
  return isCodeToolType(codeTool) ? codeTool : DEFAULT_CODE_TOOL_TYPE;
}
function normalizeTomlConfig(config) {
  const legacyConfig = config;
  const rawGeneral = config?.general || {};
  const preferredLang = sanitizePreferredLang(rawGeneral.preferredLang ?? legacyConfig?.preferredLang);
  const defaultConfig = createDefaultTomlConfig(preferredLang);
  const codeToolType = sanitizeCodeToolType(rawGeneral.currentTool ?? legacyConfig?.codeToolType);
  const rawClaudeCode = config?.claudeCode || {};
  const rawCodex = config?.codex || {};
  const rawStorage = config?.storage || {};
  const rawAdaptation = config?.adaptation || {};
  const defaultAdaptation = defaultConfig.adaptation;
  const hasLegacyToolType = typeof legacyConfig?.codeToolType === "string";
  const templateLang = rawGeneral.templateLang ?? legacyConfig?.templateLang;
  return {
    version: typeof config?.version === "string" ? config.version : defaultConfig.version,
    lastUpdated: typeof config?.lastUpdated === "string" ? config.lastUpdated : (/* @__PURE__ */ new Date()).toISOString(),
    general: {
      preferredLang,
      templateLang: templateLang ? sanitizePreferredLang(templateLang) : defaultConfig.general.templateLang,
      aiOutputLang: rawGeneral.aiOutputLang ?? legacyConfig?.aiOutputLang ?? defaultConfig.general.aiOutputLang,
      currentTool: codeToolType
    },
    claudeCode: {
      enabled: typeof rawClaudeCode.enabled === "boolean" ? rawClaudeCode.enabled : hasLegacyToolType ? codeToolType === "claude-code" : defaultConfig.claudeCode.enabled,
      outputStyles: Array.isArray(rawClaudeCode.outputStyles) ? rawClaudeCode.outputStyles : Array.isArray(legacyConfig?.outputStyles) ? legacyConfig.outputStyles : defaultConfig.claudeCode.outputStyles,
      defaultOutputStyle: typeof rawClaudeCode.defaultOutputStyle === "string" ? rawClaudeCode.defaultOutputStyle : typeof legacyConfig?.defaultOutputStyle === "string" ? legacyConfig.defaultOutputStyle : defaultConfig.claudeCode.defaultOutputStyle,
      installType: rawClaudeCode.installType === "local" || rawClaudeCode.installType === "global" ? rawClaudeCode.installType : defaultConfig.claudeCode.installType,
      installMethod: rawClaudeCode.installMethod,
      currentProfile: typeof rawClaudeCode.currentProfile === "string" ? rawClaudeCode.currentProfile : defaultConfig.claudeCode.currentProfile,
      profiles: rawClaudeCode.profiles && typeof rawClaudeCode.profiles === "object" ? rawClaudeCode.profiles : defaultConfig.claudeCode.profiles,
      version: rawClaudeCode.version
    },
    codex: {
      enabled: typeof rawCodex.enabled === "boolean" ? rawCodex.enabled : hasLegacyToolType ? codeToolType === "codex" : defaultConfig.codex.enabled,
      systemPromptStyle: typeof rawCodex.systemPromptStyle === "string" ? rawCodex.systemPromptStyle : typeof legacyConfig?.systemPromptStyle === "string" ? legacyConfig.systemPromptStyle : defaultConfig.codex.systemPromptStyle,
      installMethod: rawCodex.installMethod,
      envKeyMigrated: rawCodex.envKeyMigrated,
      goalsFeatureEnabled: rawCodex.goalsFeatureEnabled ?? defaultConfig.codex.goalsFeatureEnabled
    },
    storage: {
      ...defaultConfig.storage,
      ...rawStorage,
      memory: {
        ...defaultConfig.storage?.memory || {},
        ...rawStorage.memory || {}
      }
    },
    adaptation: {
      ...defaultAdaptation,
      ...rawAdaptation,
      runtimeProfile: {
        ...defaultAdaptation.runtimeProfile,
        ...rawAdaptation.runtimeProfile
      },
      archetypeProfile: {
        ...defaultAdaptation.archetypeProfile,
        ...rawAdaptation.archetypeProfile
      },
      capabilityProfile: {
        ...defaultAdaptation.capabilityProfile,
        ...rawAdaptation.capabilityProfile
      },
      policyProfile: {
        ...defaultAdaptation.policyProfile,
        ...rawAdaptation.policyProfile
      },
      contextProfile: {
        ...defaultAdaptation.contextProfile,
        ...rawAdaptation.contextProfile
      },
      profileSelection: {
        ...defaultAdaptation.profileSelection,
        ...rawAdaptation.profileSelection
      },
      uiProfile: {
        ...defaultAdaptation.uiProfile,
        ...rawAdaptation.uiProfile
      }
    }
  };
}
function readTomlConfig(configPath) {
  try {
    if (!exists(configPath)) {
      return null;
    }
    const content = readFile(configPath);
    const parsed = parse(content);
    return normalizeTomlConfig(parsed);
  } catch {
    return null;
  }
}
function writeTomlConfig(configPath, config) {
  try {
    const configDir = dirname(configPath);
    ensureDir(configDir);
    const tomlContent = stringify(config);
    writeFileAtomic(configPath, tomlContent);
  } catch {
  }
}
function createDefaultTomlConfig(preferredLang = "en", claudeCodeInstallType = "global") {
  return {
    version: "1.0.0",
    lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
    general: {
      preferredLang,
      templateLang: preferredLang,
      // Default templateLang to preferredLang for new installations
      aiOutputLang: preferredLang === "zh-CN" ? "zh-CN" : void 0,
      currentTool: DEFAULT_CODE_TOOL_TYPE
    },
    claudeCode: {
      enabled: true,
      outputStyles: ["speed-coder", "senior-architect", "pair-programmer"],
      defaultOutputStyle: "senior-architect",
      installType: claudeCodeInstallType,
      currentProfile: "",
      profiles: {}
    },
    codex: {
      enabled: false,
      systemPromptStyle: "senior-architect",
      goalsFeatureEnabled: true
    },
    storage: {
      memory: {}
    },
    adaptation: {
      runtimeProfile: {
        target: DEFAULT_CODE_TOOL_TYPE,
        distribution: "clavue",
        compatMode: "native" ,
        providerStrategy: "profile-based" 
      },
      archetypeProfile: {
        id: "pc-dev",
        name: "PC Software Development",
        goal: "Build, debug, test, and ship software efficiently"
      },
      capabilityProfile: {
        coding: true,
        planning: true,
        taskTracking: true,
        memory: true,
        browserAutomation: false,
        research: true,
        documentAuthoring: false,
        serviceOps: false,
        multiAgent: true
      },
      policyProfile: {
        permissionPreset: "dev",
        verificationMode: "required",
        destructiveActionPolicy: "confirm",
        workflowFallbackMode: "graceful"
      },
      contextProfile: {
        memoryMode: "project-aware",
        compressionMode: "runtime-native",
        instructionLayering: "runtime-first"
      },
      profileSelection: {
        workflowPack: "desktop-engineering",
        toolPack: "typescript-node-react"
      },
      uiProfile: {
        language: preferredLang,
        outputStyle: "concise",
        operatorMode: "execution-first"
      }
    }
  };
}
function migrateFromJsonConfig(jsonConfig) {
  const claudeCodeInstallType = jsonConfig.claudeCodeInstallation?.type || "global";
  const defaultConfig = createDefaultTomlConfig("en", claudeCodeInstallType);
  const tomlConfig = {
    version: jsonConfig.version || defaultConfig.version,
    lastUpdated: jsonConfig.lastUpdated || (/* @__PURE__ */ new Date()).toISOString(),
    general: {
      preferredLang: jsonConfig.preferredLang || defaultConfig.general.preferredLang,
      templateLang: jsonConfig.templateLang || jsonConfig.preferredLang || defaultConfig.general.preferredLang,
      // Backward compatibility: use preferredLang as default
      aiOutputLang: jsonConfig.aiOutputLang || defaultConfig.general.aiOutputLang,
      currentTool: jsonConfig.codeToolType || defaultConfig.general.currentTool
    },
    claudeCode: {
      enabled: jsonConfig.codeToolType === "claude-code",
      outputStyles: jsonConfig.outputStyles || defaultConfig.claudeCode.outputStyles,
      defaultOutputStyle: jsonConfig.defaultOutputStyle || defaultConfig.claudeCode.defaultOutputStyle,
      installType: claudeCodeInstallType,
      currentProfile: jsonConfig.currentProfileId || defaultConfig.claudeCode.currentProfile,
      profiles: jsonConfig.claudeCode?.profiles || {}
    },
    codex: {
      enabled: jsonConfig.codeToolType === "codex",
      systemPromptStyle: jsonConfig.systemPromptStyle || defaultConfig.codex.systemPromptStyle,
      goalsFeatureEnabled: true
    },
    storage: {
      memory: {}
    },
    adaptation: defaultConfig.adaptation
  };
  return tomlConfig;
}
function buildUpdatedTomlConfig(configPath, updates) {
  const existingConfig = readTomlConfig(configPath) || createDefaultTomlConfig();
  return {
    version: updates.version || existingConfig.version,
    lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
    general: {
      ...existingConfig.general,
      ...updates.general
    },
    claudeCode: {
      ...existingConfig.claudeCode,
      ...updates.claudeCode
    },
    codex: {
      ...existingConfig.codex,
      ...updates.codex
    },
    storage: {
      ...existingConfig.storage,
      ...updates.storage,
      memory: {
        ...existingConfig.storage?.memory || {},
        ...updates.storage?.memory || {}
      }
    },
    adaptation: {
      ...existingConfig.adaptation,
      ...updates.adaptation,
      runtimeProfile: updates.adaptation?.runtimeProfile ? {
        ...existingConfig.adaptation?.runtimeProfile,
        ...updates.adaptation.runtimeProfile
      } : existingConfig.adaptation?.runtimeProfile,
      archetypeProfile: updates.adaptation?.archetypeProfile ? {
        ...existingConfig.adaptation?.archetypeProfile,
        ...updates.adaptation.archetypeProfile
      } : existingConfig.adaptation?.archetypeProfile,
      capabilityProfile: updates.adaptation?.capabilityProfile ? {
        ...existingConfig.adaptation?.capabilityProfile,
        ...updates.adaptation.capabilityProfile
      } : existingConfig.adaptation?.capabilityProfile,
      policyProfile: updates.adaptation?.policyProfile ? {
        ...existingConfig.adaptation?.policyProfile,
        ...updates.adaptation.policyProfile
      } : existingConfig.adaptation?.policyProfile,
      contextProfile: updates.adaptation?.contextProfile ? {
        ...existingConfig.adaptation?.contextProfile,
        ...updates.adaptation.contextProfile
      } : existingConfig.adaptation?.contextProfile,
      profileSelection: updates.adaptation?.profileSelection ? {
        ...existingConfig.adaptation?.profileSelection,
        ...updates.adaptation.profileSelection
      } : existingConfig.adaptation?.profileSelection,
      uiProfile: updates.adaptation?.uiProfile ? {
        ...existingConfig.adaptation?.uiProfile,
        ...updates.adaptation.uiProfile
      } : existingConfig.adaptation?.uiProfile
    }
  };
}
function stringifyTomlConfig(config) {
  return stringify(config);
}
function updateTomlConfig(configPath, updates) {
  const updatedConfig = buildUpdatedTomlConfig(configPath, updates);
  writeTomlConfig(configPath, updatedConfig);
  return updatedConfig;
}
function convertTomlToLegacyConfig(tomlConfig) {
  const normalizedConfig = normalizeTomlConfig(tomlConfig);
  return {
    version: normalizedConfig.version,
    preferredLang: normalizedConfig.general.preferredLang,
    templateLang: normalizedConfig.general.templateLang,
    aiOutputLang: normalizedConfig.general.aiOutputLang,
    outputStyles: normalizedConfig.claudeCode.outputStyles,
    defaultOutputStyle: normalizedConfig.claudeCode.defaultOutputStyle,
    codeToolType: normalizedConfig.general.currentTool,
    lastUpdated: normalizedConfig.lastUpdated
  };
}
function convertLegacyToTomlConfig(legacyConfig) {
  return migrateFromJsonConfig(legacyConfig);
}
function normalizeZcfConfig(config) {
  if (!config) {
    return null;
  }
  return {
    version: typeof config.version === "string" ? config.version : "1.0.0",
    preferredLang: sanitizePreferredLang(config.preferredLang),
    templateLang: config.templateLang ? sanitizePreferredLang(config.templateLang) : void 0,
    aiOutputLang: config.aiOutputLang,
    outputStyles: Array.isArray(config.outputStyles) ? config.outputStyles : void 0,
    defaultOutputStyle: typeof config.defaultOutputStyle === "string" ? config.defaultOutputStyle : void 0,
    codeToolType: sanitizeCodeToolType(config.codeToolType),
    lastUpdated: typeof config.lastUpdated === "string" ? config.lastUpdated : (/* @__PURE__ */ new Date()).toISOString()
  };
}
function migrateZcfConfigIfNeeded() {
  const target = ZCF_CONFIG_FILE;
  const removed = [];
  const targetExists = existsSync(target);
  const legacySources = LEGACY_ZCF_CONFIG_FILES.filter((path) => existsSync(path));
  if (!targetExists && legacySources.length > 0) {
    const source = legacySources[0];
    if (!existsSync(ZCF_CONFIG_DIR)) {
      mkdirSync(ZCF_CONFIG_DIR, { recursive: true });
    }
    try {
      renameSync(source, target);
    } catch (error) {
      if (error?.code !== "EXDEV") {
        throw error;
      }
      copyFileSync(source, target);
      rmSync(source, { force: true });
    }
    for (const leftover of legacySources.slice(1)) {
      try {
        rmSync(leftover, { force: true });
        removed.push(leftover);
      } catch {
      }
    }
    return { migrated: true, source, target, removed };
  }
  if (targetExists && legacySources.length > 0) {
    for (const source of legacySources) {
      try {
        rmSync(source, { force: true });
        removed.push(source);
      } catch {
      }
    }
    return { migrated: false, target, removed };
  }
  return { migrated: false, target, removed };
}
function readZcfConfig() {
  migrateZcfConfigIfNeeded();
  const tomlConfig = readTomlConfig(ZCF_CONFIG_FILE);
  if (tomlConfig) {
    return convertTomlToLegacyConfig(tomlConfig);
  }
  const raw = readJsonConfig(ZCF_CONFIG_FILE.replace(".toml", ".json"));
  const normalized = normalizeZcfConfig(raw || null);
  if (normalized) {
    return normalized;
  }
  for (const legacyPath of LEGACY_ZCF_CONFIG_FILES) {
    if (existsSync(legacyPath)) {
      const legacyRaw = readJsonConfig(legacyPath);
      const legacyNormalized = normalizeZcfConfig(legacyRaw || null);
      if (legacyNormalized) {
        return legacyNormalized;
      }
    }
  }
  return null;
}
async function readZcfConfigAsync() {
  return readZcfConfig();
}
function writeZcfConfig(config) {
  try {
    const sanitizedConfig = {
      ...config,
      codeToolType: sanitizeCodeToolType(config.codeToolType)
    };
    const existingTomlConfig = readTomlConfig(ZCF_CONFIG_FILE);
    const tomlConfig = convertLegacyToTomlConfig(sanitizedConfig);
    const nextSystemPromptStyle = sanitizedConfig.systemPromptStyle || existingTomlConfig?.codex?.systemPromptStyle;
    if (nextSystemPromptStyle) {
      tomlConfig.codex.systemPromptStyle = nextSystemPromptStyle;
    }
    if (existingTomlConfig?.claudeCode) {
      if (existingTomlConfig.claudeCode.profiles) {
        tomlConfig.claudeCode.profiles = existingTomlConfig.claudeCode.profiles;
      }
      if (existingTomlConfig.claudeCode.currentProfile !== void 0) {
        tomlConfig.claudeCode.currentProfile = existingTomlConfig.claudeCode.currentProfile;
      }
      if (existingTomlConfig.claudeCode.version) {
        tomlConfig.claudeCode.version = existingTomlConfig.claudeCode.version;
      }
    }
    if (existingTomlConfig?.storage) {
      tomlConfig.storage = existingTomlConfig.storage;
    }
    writeTomlConfig(ZCF_CONFIG_FILE, tomlConfig);
  } catch {
  }
}
function updateZcfConfig(updates) {
  const existingConfig = readZcfConfig();
  const newConfig = {
    version: updates.version || existingConfig?.version || "1.0.0",
    preferredLang: updates.preferredLang || existingConfig?.preferredLang || "en",
    templateLang: updates.templateLang !== void 0 ? updates.templateLang : existingConfig?.templateLang,
    aiOutputLang: updates.aiOutputLang || existingConfig?.aiOutputLang,
    outputStyles: updates.outputStyles !== void 0 ? updates.outputStyles : existingConfig?.outputStyles,
    defaultOutputStyle: updates.defaultOutputStyle !== void 0 ? updates.defaultOutputStyle : existingConfig?.defaultOutputStyle,
    codeToolType: updates.codeToolType || existingConfig?.codeToolType || DEFAULT_CODE_TOOL_TYPE,
    lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
  };
  writeZcfConfig(newConfig);
}
function readDefaultTomlConfig() {
  return readTomlConfig(ZCF_CONFIG_FILE);
}

export { buildUpdatedTomlConfig, createDefaultTomlConfig, migrateFromJsonConfig, migrateZcfConfigIfNeeded, readDefaultTomlConfig, readTomlConfig, readZcfConfig, readZcfConfigAsync, stringifyTomlConfig, updateTomlConfig, updateZcfConfig, writeTomlConfig, writeZcfConfig };
