import { existsSync, readFileSync } from 'node:fs';
import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { randomUUID, createHash } from 'node:crypto';
import { ensureDir, writeFileAtomic } from './fs-operations.mjs';
import { c as createConfigSnapshot } from '../shared/ccjk.BzPbSEP2.mjs';
import { d as dirname } from '../shared/ccjk.bQ7Dh1g4.mjs';
import { isCodeToolType, isClaudeFamilyCodeTool, CODEX_CONFIG_FILE, ZCF_CONFIG_FILE } from './constants.mjs';
import { i18n } from './index2.mjs';
import { readZcfConfig, buildUpdatedTomlConfig, stringifyTomlConfig } from './ccjk-config.mjs';
import { e as ensureClaudeFamilyCoreFeatures } from '../shared/ccjk.5bEolFrk.mjs';
import { r as resolveClaudeFamilySettingsTarget, a as applyTrustedOperatorPermissions, n as normalizeClaudeFamilySettings } from '../shared/ccjk.DDL-4C-k.mjs';
import { h as buildCodexGoalsFeatureConfigContent } from './codex.mjs';
import { a as addNumbersToChoices } from '../shared/ccjk.BFQ7yr5S.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:readline';
import 'stream';
import 'node:tty';
import 'node:process';
import 'node:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:path';
import 'node:os';
import 'buffer';
import 'string_decoder';
import 'node:fs/promises';
import 'node:url';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './json-config.mjs';
import '../shared/ccjk.RyizuzOI.mjs';
import './claude-config.mjs';
import 'node:child_process';
import './platform.mjs';
import './main.mjs';
import 'module';
import 'node:stream';
import '../shared/ccjk.BLsIiTqO.mjs';
import '../shared/ccjk.DFRPtmK_.mjs';
import './auto-updater.mjs';
import './index8.mjs';
import '../shared/ccjk.DeWpAShp.mjs';
import '../shared/ccjk.DZ2LLOa-.mjs';
import './version-checker.mjs';
import '../shared/ccjk.CxpGa6MC.mjs';
import '../shared/ccjk.C0WLUnFV.mjs';
import './config.mjs';
import './prompts.mjs';
import '../shared/ccjk.gDEDGD_t.mjs';

function generateDiff(oldContent, newContent, contextLines = 3) {
  const oldLines = oldContent.split("\n");
  const newLines = newContent.split("\n");
  const lcs = computeLCS(oldLines, newLines);
  const hunks = generateHunks(oldLines, newLines, lcs, contextLines);
  let additions = 0;
  let deletions = 0;
  for (const hunk of hunks) {
    for (const line of hunk.lines) {
      if (line.type === "add")
        additions++;
      if (line.type === "remove")
        deletions++;
    }
  }
  return {
    hunks,
    additions,
    deletions,
    hasChanges: additions > 0 || deletions > 0
  };
}
function computeLCS(oldLines, newLines) {
  const m = oldLines.length;
  const n = newLines.length;
  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (oldLines[i - 1] === newLines[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1;
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
      }
    }
  }
  return dp;
}
function generateHunks(oldLines, newLines, dp, contextLines) {
  const changes = [];
  let i = oldLines.length;
  let j = newLines.length;
  while (i > 0 || j > 0) {
    if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {
      changes.unshift({ type: "same", oldIdx: i - 1, newIdx: j - 1 });
      i--;
      j--;
    } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
      changes.unshift({ type: "add", newIdx: j - 1 });
      j--;
    } else {
      changes.unshift({ type: "remove", oldIdx: i - 1 });
      i--;
    }
  }
  const hunks = [];
  let currentHunk = null;
  let contextCount = 0;
  for (let idx = 0; idx < changes.length; idx++) {
    const change = changes[idx];
    const isChange = change.type !== "same";
    const needsNewHunk = isChange && (!currentHunk || contextCount > contextLines * 2);
    if (needsNewHunk) {
      const startIdx = Math.max(0, idx - contextLines);
      currentHunk = {
        oldStart: changes[startIdx].oldIdx ?? 0,
        oldLines: 0,
        newStart: changes[startIdx].newIdx ?? 0,
        newLines: 0,
        lines: []
      };
      for (let c = startIdx; c < idx; c++) {
        const ctx = changes[c];
        if (ctx.type === "same" && ctx.oldIdx !== void 0) {
          currentHunk.lines.push({
            type: "context",
            content: oldLines[ctx.oldIdx],
            oldLineNumber: ctx.oldIdx + 1,
            newLineNumber: ctx.newIdx + 1
          });
          currentHunk.oldLines++;
          currentHunk.newLines++;
        }
      }
      hunks.push(currentHunk);
      contextCount = 0;
    }
    if (currentHunk) {
      if (change.type === "same") {
        contextCount++;
        if (contextCount <= contextLines) {
          currentHunk.lines.push({
            type: "context",
            content: oldLines[change.oldIdx],
            oldLineNumber: change.oldIdx + 1,
            newLineNumber: change.newIdx + 1
          });
          currentHunk.oldLines++;
          currentHunk.newLines++;
        } else if (contextCount > contextLines * 2) {
          currentHunk = null;
        }
      } else {
        contextCount = 0;
        if (change.type === "remove") {
          currentHunk.lines.push({
            type: "remove",
            content: oldLines[change.oldIdx],
            oldLineNumber: change.oldIdx + 1
          });
          currentHunk.oldLines++;
        } else {
          currentHunk.lines.push({
            type: "add",
            content: newLines[change.newIdx],
            newLineNumber: change.newIdx + 1
          });
          currentHunk.newLines++;
        }
      }
    }
  }
  return hunks;
}
function formatDiff(diff, filePath, options = {}) {
  const { color = true, lineNumbers = true } = options;
  const lines = [];
  if (filePath) {
    lines.push(color ? a.bold(`--- a/${filePath}`) : `--- a/${filePath}`);
    lines.push(color ? a.bold(`+++ b/${filePath}`) : `+++ b/${filePath}`);
  }
  for (const hunk of diff.hunks) {
    const hunkHeader = `@@ -${hunk.oldStart + 1},${hunk.oldLines} +${hunk.newStart + 1},${hunk.newLines} @@`;
    lines.push(color ? a.cyan(hunkHeader) : hunkHeader);
    for (const line of hunk.lines) {
      let lineStr = line.content;
      if (line.type === "add") {
        if (color)
          lineStr = a.green(`+${line.content}`);
        else lineStr = `+${line.content}`;
      } else if (line.type === "remove") {
        if (color)
          lineStr = a.red(`-${line.content}`);
        else lineStr = `-${line.content}`;
      } else {
        lineStr = ` ${line.content}`;
      }
      if (lineNumbers) {
        const oldNum = line.oldLineNumber?.toString().padStart(4, " ") ?? "    ";
        const newNum = line.newLineNumber?.toString().padStart(4, " ") ?? "    ";
        const numPrefix = color ? a.dim(`${oldNum} ${newNum} \u2502`) : `${oldNum} ${newNum} \u2502`;
        lines.push(`${numPrefix}${lineStr}`);
      } else {
        lines.push(lineStr);
      }
    }
  }
  return lines.join("\n");
}

function hashContent(content) {
  return createHash("sha256").update(content).digest("hex");
}
function readFileContentIfExists(path) {
  if (!existsSync(path)) {
    return "";
  }
  try {
    return readFileSync(path, "utf-8");
  } catch {
    return "";
  }
}
function getPlanRisk(changes) {
  if (changes.some((change) => change.risk === "dangerous")) {
    return "dangerous";
  }
  if (changes.some((change) => change.risk === "medium")) {
    return "medium";
  }
  return "safe";
}
function createFileChange(input) {
  const beforeExists = existsSync(input.file);
  const beforeContent = input.beforeContent ?? readFileContentIfExists(input.file);
  const afterContent = input.afterContent;
  return {
    id: randomUUID(),
    target: input.target,
    file: input.file,
    operation: input.operation,
    risk: input.risk,
    reason: input.reason,
    beforeHash: hashContent(beforeContent),
    afterHash: hashContent(afterContent),
    beforeExists,
    reversible: true,
    rollbackCommand: "ccjk rollback <snapshot-id>",
    beforeContent,
    afterContent
  };
}
function createConfigPlan(input) {
  return {
    id: randomUUID(),
    title: input.title,
    description: input.description,
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    risk: getPlanRisk(input.changes),
    requiresApproval: input.requiresApproval ?? false,
    changes: input.changes
  };
}
function hasConfigChange(change) {
  return change.beforeHash !== change.afterHash;
}
function getChangedConfigChanges(plan) {
  return plan.changes.filter(hasConfigChange);
}
function formatConfigPlan(plan, options = {}) {
  const { color = true, includeDiff = true } = options;
  const changed = getChangedConfigChanges(plan);
  const lines = [];
  const riskLabel = color ? colorRisk(plan.risk) : plan.risk;
  lines.push(color ? a.bold.cyan("Configuration Plan") : "Configuration Plan");
  lines.push(`Plan: ${plan.title}`);
  if (plan.description) {
    lines.push(`Reason: ${plan.description}`);
  }
  lines.push(`Risk: ${riskLabel}`);
  lines.push(`Changes: ${changed.length}/${plan.changes.length}`);
  for (const change of plan.changes) {
    const status = hasConfigChange(change) ? "change" : "no-op";
    const target = color ? a.green(change.target) : change.target;
    const statusText = color && status === "change" ? a.yellow(status) : status;
    lines.push("");
    lines.push(`${statusText}: ${target} ${change.operation}`);
    lines.push(`  File: ${change.file}`);
    lines.push(`  Why: ${change.reason}`);
    if (includeDiff && hasConfigChange(change) && change.beforeContent !== void 0 && change.afterContent !== void 0) {
      const diff = generateDiff(change.beforeContent, change.afterContent, 3);
      if (diff.hasChanges) {
        lines.push(formatDiff(diff, change.file, { color, lineNumbers: false }));
      }
    }
  }
  return lines.join("\n");
}
function applyConfigPlan(plan, options = {}) {
  const changed = getChangedConfigChanges(plan);
  const skippedChanges = plan.changes.filter((change) => !hasConfigChange(change));
  let snapshotId;
  let snapshotPath;
  if (options.createSnapshot !== false && changed.length > 0) {
    const snapshot = createConfigSnapshot(plan);
    snapshotId = snapshot.id;
    snapshotPath = snapshot.path;
  }
  for (const change of changed) {
    if (change.operation === "delete-file") {
      continue;
    }
    if (change.afterContent === void 0) {
      throw new Error(`Missing afterContent for config change: ${change.file}`);
    }
    ensureDir(dirname(change.file));
    writeFileAtomic(change.file, change.afterContent);
  }
  return {
    appliedChanges: changed,
    skippedChanges,
    snapshotId,
    snapshotPath
  };
}
function colorRisk(risk) {
  if (risk === "dangerous") {
    return a.red(risk);
  }
  if (risk === "medium") {
    return a.yellow(risk);
  }
  return a.green(risk);
}

function isZeroConfigCodeTool(value) {
  return value === "claude-code" || value === "clavue" || value === "codex";
}
const MAX_PRESET = {
  id: "max",
  name: "Maximum Permissions",
  description: "All common commands, file operations, and MCP servers",
  permissions: [
    "Bash(*)",
    "Bash(sips *)",
    // Package managers
    "Bash(pnpm *)",
    "Bash(npm *)",
    "Bash(npx *)",
    "Bash(NODE_ENV=* pnpm *)",
    "Bash(yarn *)",
    "Bash(bun *)",
    "Bash(deno *)",
    // Version control
    "Bash(git *)",
    // Build tools
    "Bash(make *)",
    "Bash(cmake *)",
    "Bash(cargo *)",
    "Bash(go *)",
    "Bash(rustc *)",
    // Container tools
    "Bash(docker *)",
    "Bash(docker-compose *)",
    "Bash(podman *)",
    // Programming languages
    "Bash(python *)",
    "Bash(python3 *)",
    "Bash(node *)",
    "Bash(ruby *)",
    "Bash(php *)",
    "Bash(java *)",
    "Bash(javac *)",
    // Shell utilities
    "Bash(which *)",
    "Bash(cat *)",
    "Bash(ls *)",
    "Bash(echo *)",
    "Bash(grep *)",
    "Bash(find *)",
    "Bash(head *)",
    "Bash(tail *)",
    "Bash(wc *)",
    "Bash(sort *)",
    "Bash(uniq *)",
    "Bash(cut *)",
    "Bash(sed *)",
    "Bash(awk *)",
    "Bash(tr *)",
    "Bash(xargs *)",
    // File operations
    "Bash(mkdir *)",
    "Bash(touch *)",
    "Bash(cp *)",
    "Bash(mv *)",
    "Bash(chmod *)",
    "Bash(chown *)",
    "Bash(ln *)",
    // Network tools
    "Bash(curl *)",
    "Bash(wget *)",
    "Bash(ping *)",
    "Bash(netstat *)",
    "Bash(ss *)",
    // System info
    "Bash(ps *)",
    "Bash(top *)",
    "Bash(htop *)",
    "Bash(df *)",
    "Bash(du *)",
    "Bash(free *)",
    "Bash(uname *)",
    // Text editors
    "Bash(vim *)",
    "Bash(nano *)",
    "Bash(emacs *)",
    "Bash(code *)",
    // Compression
    "Bash(tar *)",
    "Bash(gzip *)",
    "Bash(gunzip *)",
    "Bash(zip *)",
    "Bash(unzip *)",
    // Package managers (system)
    "Bash(brew *)",
    "Bash(apt *)",
    "Bash(apt-get *)",
    "Bash(yum *)",
    "Bash(dnf *)",
    "Bash(pacman *)",
    // File operations (Claude Code tools)
    "Read(*)",
    "Edit(*)",
    "Write(*)",
    "NotebookEdit(*)",
    // Web access
    "WebFetch(*)",
    // MCP servers (wildcard for all)
    "MCP(*)"
  ],
  env: {
    ANTHROPIC_MODEL: "",
    ANTHROPIC_DEFAULT_HAIKU_MODEL: "",
    ANTHROPIC_DEFAULT_SONNET_MODEL: "",
    ANTHROPIC_DEFAULT_OPUS_MODEL: ""
  }
};
const DEV_PRESET = {
  id: "dev",
  name: "Developer Preset",
  description: "Build tools, git, package managers, and file operations",
  permissions: [
    "Bash(*)",
    "Bash(sips *)",
    // Package managers
    "Bash(pnpm *)",
    "Bash(npm *)",
    "Bash(npx *)",
    "Bash(NODE_ENV=* pnpm *)",
    "Bash(yarn *)",
    "Bash(bun *)",
    // Version control
    "Bash(git *)",
    // Build tools
    "Bash(make *)",
    "Bash(cargo *)",
    "Bash(go *)",
    // Programming languages
    "Bash(python *)",
    "Bash(python3 *)",
    "Bash(node *)",
    // Shell utilities
    "Bash(which *)",
    "Bash(cat *)",
    "Bash(ls *)",
    "Bash(echo *)",
    "Bash(grep *)",
    "Bash(find *)",
    "Bash(head *)",
    "Bash(tail *)",
    "Bash(wc *)",
    "Bash(sort *)",
    // File operations
    "Bash(mkdir *)",
    "Bash(touch *)",
    "Bash(cp *)",
    "Bash(mv *)",
    "Bash(chmod *)",
    // File operations (Claude Code tools)
    "Read(*)",
    "Edit(*)",
    "Write(*)",
    "NotebookEdit(*)",
    // Web access for docs
    "WebFetch(*)"
  ],
  env: {
    ANTHROPIC_MODEL: ""
  }
};
const SAFE_PRESET = {
  id: "safe",
  name: "Safe Preset",
  description: "Read-only commands, no file modifications",
  permissions: [
    // Read-only shell utilities
    "Bash(which *)",
    "Bash(cat *)",
    "Bash(ls *)",
    "Bash(echo *)",
    "Bash(grep *)",
    "Bash(find *)",
    "Bash(head *)",
    "Bash(tail *)",
    "Bash(wc *)",
    "Bash(sort *)",
    "Bash(uniq *)",
    "Bash(cut *)",
    // System info (read-only)
    "Bash(ps *)",
    "Bash(df *)",
    "Bash(du *)",
    "Bash(uname *)",
    // Git read operations
    "Bash(git status *)",
    "Bash(git log *)",
    "Bash(git diff *)",
    "Bash(git show *)",
    "Bash(git branch *)",
    // File operations (read-only)
    "Read(*)",
    // Web access
    "WebFetch(*)"
  ]
};
const PRESETS = [MAX_PRESET, DEV_PRESET, SAFE_PRESET];
function getArchetypeProfile(archetype = "pc-dev") {
  switch (archetype) {
    case "app-dev":
      return {
        id: "app-dev",
        name: "Application Development",
        goal: "Plan, build, verify, and ship application features with a product-focused workflow"
      };
    case "text-studio":
      return {
        id: "text-studio",
        name: "Text Studio",
        goal: "Research, draft, edit, and review text-heavy work with a documentation-first workflow"
      };
    case "service-ops":
      return {
        id: "service-ops",
        name: "Service Operations",
        goal: "Inspect, operate, and maintain services safely with verification and controlled changes"
      };
    case "research":
      return {
        id: "research",
        name: "Research and Analysis",
        goal: "Investigate code, docs, and technical options before applying targeted changes"
      };
    case "automation":
      return {
        id: "automation",
        name: "Automation and Scripting",
        goal: "Automate repetitive development and operations tasks with reliable execution flows"
      };
    case "custom":
      return {
        id: "custom",
        name: "Custom Workflow",
        goal: "Adapt CCJK to a custom working style and toolchain combination"
      };
    case "pc-dev":
    default:
      return {
        id: "pc-dev",
        name: "PC Software Development",
        goal: "Build, debug, test, and ship software efficiently"
      };
  }
}
function getCapabilityProfile(archetype = "pc-dev") {
  return {
    coding: archetype !== "text-studio" && archetype !== "research",
    planning: true,
    taskTracking: true,
    memory: true,
    browserAutomation: false,
    research: true,
    documentAuthoring: archetype === "text-studio" || archetype === "research",
    serviceOps: archetype === "service-ops",
    multiAgent: archetype !== "custom"
  };
}
function getOperatorMode(archetype = "pc-dev") {
  if (archetype === "research" || archetype === "text-studio") {
    return "planning-first";
  }
  if (archetype === "custom") {
    return "conversational";
  }
  return "execution-first";
}
function loadCurrentSettings(target = resolveClaudeFamilySettingsTarget()) {
  if (!existsSync(target.settingsFile)) {
    return {};
  }
  try {
    const content = readFileSync(target.settingsFile, "utf-8");
    return JSON.parse(content);
  } catch {
    return {};
  }
}
function stringifySettings(settings) {
  normalizeClaudeFamilySettings(settings);
  return JSON.stringify(settings, null, 2);
}
function applyPreset(preset, currentSettings) {
  const newSettings = structuredClone(currentSettings || {});
  if (!newSettings.permissions) {
    newSettings.permissions = { allow: [] };
  }
  const existingPermissions = Array.isArray(newSettings.permissions.allow) ? newSettings.permissions.allow.filter((permission) => typeof permission === "string") : [];
  newSettings.permissions.allow = [
    ...existingPermissions,
    ...preset.permissions.filter((permission) => !existingPermissions.includes(permission))
  ];
  if (preset.id === "dev" || preset.id === "max") {
    applyTrustedOperatorPermissions(newSettings);
  }
  if (preset.env) {
    newSettings.env = { ...newSettings.env };
    for (const [key, value] of Object.entries(preset.env)) {
      if (value === "") {
        continue;
      }
      if (newSettings.env[key] === void 0 || newSettings.env[key] === "") {
        newSettings.env[key] = value;
      }
    }
  }
  return newSettings;
}
function buildAdaptationPresetUpdates(preset, archetype = "pc-dev") {
  const safetyLevel = preset.id === "safe" ? "safe" : preset.id === "max" ? "max" : "dev";
  return {
    codex: {
      goalsFeatureEnabled: true
    },
    adaptation: {
      archetypeProfile: getArchetypeProfile(archetype),
      capabilityProfile: getCapabilityProfile(archetype),
      policyProfile: {
        permissionPreset: safetyLevel,
        verificationMode: safetyLevel === "safe" ? "manual" : "required",
        destructiveActionPolicy: safetyLevel === "max" ? "confirm" : "confirm",
        workflowFallbackMode: "graceful"
      },
      contextProfile: {
        memoryMode: archetype === "custom" ? "session-only" : "project-aware",
        compressionMode: "runtime-native",
        instructionLayering: "runtime-first"
      },
      profileSelection: {
        workflowPack: archetype === "service-ops" ? "service-operations" : "desktop-engineering",
        toolPack: archetype === "text-studio" ? "document-authoring" : "typescript-node-react"
      },
      uiProfile: {
        language: i18n.language === "zh-CN" ? "zh-CN" : "en",
        outputStyle: "concise",
        operatorMode: getOperatorMode(archetype)
      }
    }
  };
}
function createZeroConfigPlan(preset, target, codeTool, currentSettings, archetype = "pc-dev") {
  const adaptationUpdates = buildAdaptationPresetUpdates(preset, archetype);
  const nextToml = buildUpdatedTomlConfig(ZCF_CONFIG_FILE, adaptationUpdates);
  const nextTomlContent = stringifyTomlConfig(nextToml);
  const changes = [];
  if (target) {
    const nextSettings = applyPreset(preset, currentSettings);
    const nextSettingsContent = stringifySettings(nextSettings);
    changes.push(
      createFileChange({
        target: target.codeTool,
        file: target.settingsFile,
        operation: existsSync(target.settingsFile) ? "merge-json" : "create-file",
        risk: preset.id === "max" ? "medium" : "safe",
        reason: `Merge ${preset.name} permissions into ${target.displayName} settings.`,
        afterContent: nextSettingsContent
      })
    );
  }
  if (codeTool === "codex") {
    const currentCodexContent = existsSync(CODEX_CONFIG_FILE) ? readFileSync(CODEX_CONFIG_FILE, "utf-8") : "";
    const nextCodexContent = buildCodexGoalsFeatureConfigContent(currentCodexContent);
    changes.push(
      createFileChange({
        target: "codex",
        file: CODEX_CONFIG_FILE,
        operation: existsSync(CODEX_CONFIG_FILE) ? "merge-toml" : "create-file",
        risk: "safe",
        reason: "Enable Codex native /goal support for planning and task-tracking workflows.",
        beforeContent: currentCodexContent,
        afterContent: nextCodexContent
      })
    );
  }
  changes.push(
    createFileChange({
      target: "ccjk",
      file: ZCF_CONFIG_FILE,
      operation: existsSync(ZCF_CONFIG_FILE) ? "merge-toml" : "create-file",
      risk: "safe",
      reason: "Record the selected zero-config product profile and runtime-native goal support for future diagnostics.",
      afterContent: nextTomlContent
    })
  );
  return createConfigPlan({
    title: `Apply zero-config preset: ${preset.name}`,
    description: `Configure ${codeTool === "codex" ? "Codex" : target?.displayName} with the ${getArchetypeProfile(archetype).name} product profile.`,
    changes
  });
}
function showPresetDiff(preset, currentSettings) {
  const isZh = i18n.language === "zh-CN";
  const currentPermissions = new Set(currentSettings.permissions?.allow || []);
  const newPermissions = preset.permissions.filter((p) => !currentPermissions.has(p));
  console.log("");
  console.log(a.bold.cyan(isZh ? "\u{1F4CB} \u9884\u8BBE\u8BE6\u60C5" : "\u{1F4CB} Preset Details"));
  console.log(a.dim("\u2500".repeat(60)));
  console.log(`${a.green("Name:")} ${preset.name}`);
  console.log(`${a.green("Description:")} ${preset.description}`);
  console.log("");
  if (newPermissions.length > 0) {
    console.log(a.bold.yellow(isZh ? "\u2728 \u5C06\u6DFB\u52A0\u7684\u6743\u9650:" : "\u2728 Permissions to be added:"));
    console.log(a.dim(`  ${isZh ? "\u603B\u8BA1" : "Total"}: ${newPermissions.length} ${isZh ? "\u9879" : "items"}`));
    const bashPerms = newPermissions.filter((p) => p.startsWith("Bash("));
    const filePerms = newPermissions.filter((p) => ["Read", "Edit", "Write", "NotebookEdit"].some((t) => p.startsWith(t)));
    const otherPerms = newPermissions.filter((p) => !bashPerms.includes(p) && !filePerms.includes(p));
    if (bashPerms.length > 0) {
      console.log(`  ${a.cyan("Bash:")} ${bashPerms.length} ${isZh ? "\u4E2A\u547D\u4EE4" : "commands"}`);
    }
    if (filePerms.length > 0) {
      console.log(`  ${a.cyan("File:")} ${filePerms.length} ${isZh ? "\u4E2A\u64CD\u4F5C" : "operations"}`);
    }
    if (otherPerms.length > 0) {
      console.log(`  ${a.cyan("Other:")} ${otherPerms.length} ${isZh ? "\u9879" : "items"}`);
    }
  } else {
    console.log(a.yellow(isZh ? "\u2713 \u6240\u6709\u6743\u9650\u5DF2\u5B58\u5728" : "\u2713 All permissions already exist"));
  }
  console.log(a.dim("\u2500".repeat(60)));
  console.log("");
}
async function zeroConfig(options = {}) {
  const isZh = i18n.language === "zh-CN";
  const requestedCodeTool = isCodeToolType(options.codeTool) ? options.codeTool : void 0;
  const savedCodeTool = readZcfConfig()?.codeToolType;
  const codeTool = isZeroConfigCodeTool(requestedCodeTool) ? requestedCodeTool : isZeroConfigCodeTool(savedCodeTool) ? savedCodeTool : "claude-code";
  const target = isClaudeFamilyCodeTool(codeTool) ? resolveClaudeFamilySettingsTarget(codeTool) : null;
  if (options.list) {
    console.log("");
    console.log(a.bold.cyan(isZh ? "\u{1F4E6} \u53EF\u7528\u7684\u6743\u9650\u9884\u8BBE" : "\u{1F4E6} Available Permission Presets"));
    console.log(a.dim("\u2500".repeat(60)));
    for (const preset of PRESETS) {
      console.log(`  ${a.green(preset.id.padEnd(8))} - ${preset.name}`);
      console.log(`  ${a.dim(" ".repeat(10))}${preset.description}`);
      console.log(`  ${a.dim(" ".repeat(10))}${preset.permissions.length} ${isZh ? "\u9879\u6743\u9650" : "permissions"}`);
      console.log("");
    }
    console.log(a.dim("\u2500".repeat(60)));
    console.log(a.gray(isZh ? "\u4F7F\u7528: npx ccjk zc --preset=<id>" : "Usage: npx ccjk zc --preset=<id>"));
    console.log("");
    return;
  }
  let selectedPreset;
  if (options.preset) {
    selectedPreset = PRESETS.find((p) => p.id === options.preset);
    if (!selectedPreset) {
      console.error(a.red(isZh ? `\u9519\u8BEF: \u672A\u627E\u5230\u9884\u8BBE "${options.preset}"` : `Error: Preset "${options.preset}" not found`));
      console.log(a.gray(isZh ? "\u4F7F\u7528 --list \u67E5\u770B\u53EF\u7528\u9884\u8BBE" : "Use --list to see available presets"));
      return;
    }
  } else {
    const { presetId } = await inquirer.prompt({
      type: "list",
      name: "presetId",
      message: isZh ? "\u9009\u62E9\u6743\u9650\u9884\u8BBE:" : "Select permission preset:",
      choices: addNumbersToChoices(
        PRESETS.map((p) => ({
          name: `${p.name} - ${a.gray(p.description)}`,
          value: p.id,
          short: p.name
        }))
      )
    });
    selectedPreset = PRESETS.find((p) => p.id === presetId);
    if (!selectedPreset) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return;
    }
  }
  const currentSettings = target ? loadCurrentSettings(target) : {};
  const plan = createZeroConfigPlan(
    selectedPreset,
    target,
    codeTool,
    currentSettings,
    options.archetype
  );
  showPresetDiff(selectedPreset, currentSettings);
  if (options.dryRun) {
    console.log(formatConfigPlan(plan));
    return;
  }
  if (!options.preset) {
    const { confirm } = await inquirer.prompt({
      type: "confirm",
      name: "confirm",
      message: isZh ? "\u786E\u8BA4\u5E94\u7528\u6B64\u9884\u8BBE?" : "Confirm applying this preset?",
      default: true
    });
    if (!confirm) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return;
    }
  }
  const applyResult = applyConfigPlan(plan, { createSnapshot: !options.skipBackup });
  if (applyResult.snapshotId) {
    console.log(a.gray(`\u2714 ${isZh ? "\u5DF2\u521B\u5EFA\u5FEB\u7167" : "Snapshot created"}: ${applyResult.snapshotId}`));
  }
  console.log("");
  console.log(a.green(`\u2705 ${isZh ? "\u6743\u9650\u9884\u8BBE\u5DF2\u5E94\u7528" : "Permission preset applied"}: ${selectedPreset.name}`));
  if (target) {
    console.log(a.gray(`   ${isZh ? "\u914D\u7F6E\u6587\u4EF6" : "Config file"}: ${target.settingsFile}`));
  }
  if (codeTool === "codex") {
    console.log(a.gray(`   ${isZh ? "Codex \u914D\u7F6E" : "Codex config"}: ${CODEX_CONFIG_FILE}`));
    console.log(a.gray(`   ${isZh ? "\u5DF2\u542F\u7528" : "Enabled"}: [features].goals = true`));
  }
  if (applyResult.snapshotId) {
    console.log(a.gray(`   ${isZh ? "\u56DE\u6EDA\u547D\u4EE4" : "Rollback"}: npx ccjk rollback ${applyResult.snapshotId}`));
  }
  if (target) {
    const featureResults = await ensureClaudeFamilyCoreFeatures({
      codeTool: target.codeTool,
      configLang: "en",
      installCcr: options.installCcr !== false
    });
    console.log(a.bold.cyan(isZh ? "\u6838\u5FC3\u529F\u80FD\u68C0\u67E5" : "Core feature check"));
    for (const result of featureResults) {
      const ok = result.status !== "failed";
      const marker = ok ? a.green("\u2714") : a.red("\u2716");
      console.log(`${marker} ${result.feature}: ${result.message}`);
      if (result.error) {
        console.log(a.dim(`  ${result.error}`));
      }
    }
  }
  console.log("");
}

export { zeroConfig };
