import { resolve } from 'node:path';
import { p as parse } from '../shared/ccjk.BBtCGd_g.mjs';
import { stringify } from './index3.mjs';
import { CCJK_CONFIG_FILE, SUPPORTED_LANGS, DEFAULT_CODE_TOOL_TYPE, CCJK_CONFIG_DIR, CLAUDE_DIR } from './constants.mjs';
import { exists, readFile, ensureDir, writeFileAtomic } from './fs-operations.mjs';
import { d as dirname, j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';
import 'node:os';
import './index2.mjs';
import 'node:fs';
import 'node:process';
import 'node:url';
import 'node:crypto';
import 'node:fs/promises';

const DEFAULT_CONFIG_VERSION = "4.0.0";
function createDefaultCcjkConfig(preferredLang = "en", claudeCodeInstallType = "global") {
  return {
    version: DEFAULT_CONFIG_VERSION,
    lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
    general: {
      preferredLang,
      templateLang: preferredLang,
      aiOutputLang: preferredLang === "zh-CN" ? "zh-CN" : void 0,
      currentTool: DEFAULT_CODE_TOOL_TYPE
    },
    tools: {
      claudeCode: {
        enabled: true,
        installType: claudeCodeInstallType,
        outputStyles: ["speed-coder", "senior-architect", "pair-programmer"],
        defaultOutputStyle: "senior-architect",
        currentProfile: "",
        profiles: {}
      },
      codex: {
        enabled: false,
        systemPromptStyle: "senior-architect"
      }
    },
    storage: {
      memory: {}
    }
  };
}
function readCcjkConfig(configPath = CCJK_CONFIG_FILE) {
  try {
    if (!exists(configPath)) {
      return null;
    }
    const content = readFile(configPath);
    const parsed = parse(content);
    return convertTomlToCcjkConfig(parsed);
  } catch (error) {
    console.error(`Failed to read CCJK config from ${configPath}:`, error);
    return null;
  }
}
function writeCcjkConfig(config, configPath = CCJK_CONFIG_FILE) {
  try {
    const configDir = dirname(configPath);
    ensureDir(configDir);
    config.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
    const tomlContent = stringify(config);
    writeFileAtomic(configPath, tomlContent);
  } catch (error) {
    console.error(`Failed to write CCJK config to ${configPath}:`, error);
    throw new Error(`Failed to write CCJK config: ${error instanceof Error ? error.message : String(error)}`);
  }
}
function updateCcjkConfig(updates, configPath = CCJK_CONFIG_FILE) {
  const existingConfig = readCcjkConfig(configPath) || createDefaultCcjkConfig();
  const updatedConfig = {
    version: updates.version || existingConfig.version,
    lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
    general: {
      ...existingConfig.general,
      ...updates.general
    },
    tools: {
      ...existingConfig.tools,
      ...updates.tools,
      claudeCode: {
        ...existingConfig.tools.claudeCode,
        ...updates.tools?.claudeCode
      },
      codex: {
        ...existingConfig.tools.codex,
        ...updates.tools?.codex
      }
    },
    storage: {
      ...existingConfig.storage,
      ...updates.storage,
      memory: {
        ...existingConfig.storage.memory,
        ...updates.storage?.memory
      }
    }
  };
  writeCcjkConfig(updatedConfig, configPath);
  return updatedConfig;
}
function getCcjkConfig(configPath = CCJK_CONFIG_FILE) {
  const config = readCcjkConfig(configPath);
  return config || createDefaultCcjkConfig();
}
function validateCcjkConfig(config) {
  const errors = [];
  if (!config || typeof config !== "object") {
    return { valid: false, errors: ["Configuration must be an object"] };
  }
  const cfg = config;
  if (!cfg.version || typeof cfg.version !== "string") {
    errors.push("Invalid or missing version");
  }
  if (!cfg.general || typeof cfg.general !== "object") {
    errors.push("Invalid or missing general section");
  } else {
    if (!cfg.general.preferredLang || !SUPPORTED_LANGS.includes(cfg.general.preferredLang)) {
      errors.push(`Invalid preferredLang: ${cfg.general.preferredLang}`);
    }
    if (cfg.general.templateLang && !SUPPORTED_LANGS.includes(cfg.general.templateLang)) {
      errors.push(`Invalid templateLang: ${cfg.general.templateLang}`);
    }
  }
  if (!cfg.tools || typeof cfg.tools !== "object") {
    errors.push("Invalid or missing tools section");
  } else {
    if (!cfg.tools.claudeCode || typeof cfg.tools.claudeCode !== "object") {
      errors.push("Invalid or missing claudeCode tool config");
    }
    if (!cfg.tools.codex || typeof cfg.tools.codex !== "object") {
      errors.push("Invalid or missing codex tool config");
    }
  }
  if (!cfg.storage || typeof cfg.storage !== "object") {
    errors.push("Invalid or missing storage section");
  }
  return {
    valid: errors.length === 0,
    errors
  };
}
function convertTomlToCcjkConfig(tomlConfig) {
  if (!tomlConfig) {
    return null;
  }
  return {
    version: tomlConfig.version || DEFAULT_CONFIG_VERSION,
    lastUpdated: tomlConfig.lastUpdated || (/* @__PURE__ */ new Date()).toISOString(),
    general: {
      preferredLang: tomlConfig.general?.preferredLang || "en",
      templateLang: tomlConfig.general?.templateLang,
      aiOutputLang: tomlConfig.general?.aiOutputLang,
      currentTool: tomlConfig.general?.currentTool || DEFAULT_CODE_TOOL_TYPE
    },
    tools: {
      claudeCode: {
        enabled: tomlConfig.claudeCode?.enabled ?? true,
        installType: tomlConfig.claudeCode?.installType || "global",
        installMethod: tomlConfig.claudeCode?.installMethod,
        outputStyles: tomlConfig.claudeCode?.outputStyles || [],
        defaultOutputStyle: tomlConfig.claudeCode?.defaultOutputStyle,
        currentProfile: tomlConfig.claudeCode?.currentProfile || "",
        profiles: tomlConfig.claudeCode?.profiles || {},
        version: tomlConfig.claudeCode?.version
      },
      codex: {
        enabled: tomlConfig.codex?.enabled ?? false,
        systemPromptStyle: tomlConfig.codex?.systemPromptStyle || "senior-architect",
        installMethod: tomlConfig.codex?.installMethod,
        envKeyMigrated: tomlConfig.codex?.envKeyMigrated
      }
    },
    storage: {
      memory: {
        claudeDir: tomlConfig.storage?.memory?.claudeDir,
        ccjkDir: tomlConfig.storage?.memory?.ccjkDir
      }
    }
  };
}

const config = {
  /**
   * CCJK Configuration (~/.ccjk/config.toml)
   */
  ccjk: {
    /**
     * Read CCJK configuration
     */
    read: readCcjkConfig,
    /**
     * Write CCJK configuration
     */
    write: writeCcjkConfig,
    /**
     * Update CCJK configuration with partial changes
     */
    update: updateCcjkConfig,
    /**
     * Get or create CCJK configuration (with defaults)
     */
    get: getCcjkConfig,
    /**
     * Create default CCJK configuration
     */
    createDefault: createDefaultCcjkConfig,
    /**
     * Validate CCJK configuration
     */
    validate: validateCcjkConfig
  }};

function getMemoryDirectoryOverrides() {
  const ccjkConfig = config.ccjk.read();
  return {
    claudeDir: ccjkConfig?.storage?.memory?.claudeDir,
    ccjkDir: ccjkConfig?.storage?.memory?.ccjkDir
  };
}
function resolveClaudeDir(claudeDir) {
  return normalizeProjectPath(claudeDir || getMemoryDirectoryOverrides().claudeDir || CLAUDE_DIR);
}
function resolveCcjkDir(ccjkDir) {
  return normalizeProjectPath(ccjkDir || getMemoryDirectoryOverrides().ccjkDir || CCJK_CONFIG_DIR);
}
function normalizeProjectPath(projectPath) {
  return resolve(projectPath).replace(/\\/g, "/");
}
function toClaudeProjectDirName(projectPath) {
  const normalizedPath = normalizeProjectPath(projectPath).replace(/^\/+/, "");
  return `-${normalizedPath.replace(/[:/]/g, "-")}`;
}
function getClaudeMemoryPath(projectPath, claudeDir) {
  const resolvedClaudeDir = resolveClaudeDir(claudeDir);
  if (projectPath) {
    return join(resolvedClaudeDir, "projects", toClaudeProjectDirName(projectPath), "memory", "MEMORY.md");
  }
  return join(resolvedClaudeDir, "memory", "MEMORY.md");
}
function getCcjkMemoryPath(projectPath, ccjkDir) {
  const resolvedCcjkDir = resolveCcjkDir(ccjkDir);
  if (projectPath) {
    return join(resolvedCcjkDir, "memory", "projects", toClaudeProjectDirName(projectPath), "MEMORY.md");
  }
  return join(resolvedCcjkDir, "memory", "global", "MEMORY.md");
}
function getClaudeProjectsDir(claudeDir) {
  return join(resolveClaudeDir(claudeDir), "projects");
}
function getConfiguredMemoryDirectories() {
  return {
    claudeDir: resolveClaudeDir(),
    ccjkDir: resolveCcjkDir()
  };
}

export { getCcjkMemoryPath, getClaudeMemoryPath, getClaudeProjectsDir, getConfiguredMemoryDirectories, normalizeProjectPath, toClaudeProjectDirName };
