import { existsSync, mkdirSync, statSync, writeFileSync, readFileSync, readdirSync } from 'node:fs';
import process__default from 'node:process';
import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { getApiProviderPresets } from './api-providers.mjs';
import { SETTINGS_FILE, CLAUDE_DIR, CODEX_DIR, CODEX_CONFIG_FILE, getCodeToolRuntimeCommand } from './constants.mjs';
import { i18n } from './index2.mjs';
import { g as getPermissionManager } from '../shared/ccjk.DsZsc4LR.mjs';
import { i as isCcrInstalled } from '../shared/ccjk.DFRPtmK_.mjs';
import { i as inspectClaudeFamilyCoreFeatures } from '../shared/ccjk.5bEolFrk.mjs';
import { a as readCodexConfig, g as readCodexGoalsFeatureEnabled } from './codex.mjs';
import { b as backupExistingConfig, c as copyConfigFiles } from './config.mjs';
import { c as commandExists } from './platform.mjs';
import { P as ProviderHealthMonitor } from '../shared/ccjk.J8YiPsOw.mjs';
import { r as resolveClaudeFamilySettingsTarget } from '../shared/ccjk.DDL-4C-k.mjs';
import { platform, userInfo, homedir } from 'node:os';
import ora from './index8.mjs';
import { exec as q } from './main.mjs';
import { STATUS } from './banner.mjs';
import { writeFileAtomic } from './fs-operations.mjs';
import { c as resolve, j as join, d as dirname } from '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:readline';
import 'stream';
import 'node:tty';
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:crypto';
import 'buffer';
import 'string_decoder';
import 'node:url';
import 'node:child_process';
import './auto-updater.mjs';
import '../shared/ccjk.DZ2LLOa-.mjs';
import '../shared/ccjk.DeWpAShp.mjs';
import './version-checker.mjs';
import '../shared/ccjk.CxpGa6MC.mjs';
import 'module';
import 'node:stream';
import './claude-config.mjs';
import './json-config.mjs';
import '../shared/ccjk.RyizuzOI.mjs';
import 'node:fs/promises';
import '../shared/ccjk.BLsIiTqO.mjs';
import '../shared/ccjk.C0WLUnFV.mjs';
import './ccjk-config.mjs';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import '../shared/ccjk.BFQ7yr5S.mjs';
import './prompts.mjs';
import '../shared/ccjk.gDEDGD_t.mjs';

const t = i18n.t.bind(i18n);
function getClaudeSettings() {
  try {
    if (existsSync(SETTINGS_FILE)) {
      return JSON.parse(readFileSync(SETTINGS_FILE, "utf-8"));
    }
  } catch {
  }
  return null;
}
function saveClaudeSettings(settings) {
  try {
    if (!existsSync(CLAUDE_DIR)) {
      mkdirSync(CLAUDE_DIR, { recursive: true });
    }
    writeFileAtomic(SETTINGS_FILE, JSON.stringify(settings, null, 2));
    return true;
  } catch {
    return false;
  }
}
async function checkWorkingDirectory(cwd) {
  try {
    if (!existsSync(cwd)) {
      return {
        name: t("workspace:checks.cwdExists"),
        status: "fail",
        message: t("workspace:status.notExists"),
        details: cwd,
        fixDescription: t("workspace:fixes.createDirectory"),
        fix: async () => {
          try {
            mkdirSync(cwd, { recursive: true });
            return true;
          } catch {
            return false;
          }
        }
      };
    }
    const stat = statSync(cwd);
    if (!stat.isDirectory()) {
      return {
        name: t("workspace:checks.cwdExists"),
        status: "fail",
        message: t("workspace:status.notDirectory"),
        details: cwd
      };
    }
    return {
      name: t("workspace:checks.cwdExists"),
      status: "pass",
      message: cwd
    };
  } catch (error) {
    return {
      name: t("workspace:checks.cwdExists"),
      status: "fail",
      message: t("workspace:status.accessError"),
      details: error instanceof Error ? error.message : String(error)
    };
  }
}
async function checkWritePermission(cwd) {
  const testFile = join(cwd, `.ccjk-write-test-${Date.now()}.tmp`);
  try {
    writeFileSync(testFile, "test", { mode: 420 });
    const content = readFileSync(testFile, "utf-8");
    if (content !== "test") {
      throw new Error("Content mismatch");
    }
    const { unlinkSync } = await import('node:fs');
    unlinkSync(testFile);
    return {
      name: t("workspace:checks.writePermission"),
      status: "pass",
      message: t("workspace:status.writable")
    };
  } catch (error) {
    try {
      const { unlinkSync } = await import('node:fs');
      if (existsSync(testFile)) {
        unlinkSync(testFile);
      }
    } catch {
    }
    const isPermissionError = error instanceof Error && (error.message.includes("EACCES") || error.message.includes("EPERM"));
    if (isPermissionError) {
      return {
        name: t("workspace:checks.writePermission"),
        status: "fail",
        message: t("workspace:status.noWritePermission"),
        details: error instanceof Error ? error.message : String(error),
        fixDescription: t("workspace:fixes.fixPermission"),
        fix: async () => {
          try {
            if (platform() !== "win32") {
              await q("chmod", ["-R", "u+w", cwd], { throwOnError: true });
              return true;
            }
            return false;
          } catch {
            return false;
          }
        }
      };
    }
    return {
      name: t("workspace:checks.writePermission"),
      status: "fail",
      message: t("workspace:status.writeTestFailed"),
      details: error instanceof Error ? error.message : String(error)
    };
  }
}
async function checkDirectoryOwnership(cwd) {
  if (platform() === "win32") {
    return {
      name: t("workspace:checks.ownership"),
      status: "info",
      message: t("workspace:status.skippedWindows")
    };
  }
  try {
    const stat = statSync(cwd);
    const currentUid = process__default.getuid?.() ?? -1;
    if (currentUid === -1) {
      return {
        name: t("workspace:checks.ownership"),
        status: "info",
        message: t("workspace:status.cannotCheck")
      };
    }
    if (stat.uid !== currentUid) {
      const user = userInfo();
      return {
        name: t("workspace:checks.ownership"),
        status: "warn",
        message: t("workspace:status.differentOwner"),
        details: t("workspace:details.ownerMismatch", { currentUser: user.username, dirUid: stat.uid }),
        fixDescription: t("workspace:fixes.changeOwner"),
        fix: async () => {
          try {
            await q("sudo", ["chown", "-R", `${currentUid}:${process__default.getgid?.() ?? currentUid}`, cwd], { throwOnError: true });
            return true;
          } catch {
            return false;
          }
        }
      };
    }
    return {
      name: t("workspace:checks.ownership"),
      status: "pass",
      message: t("workspace:status.correctOwner")
    };
  } catch (error) {
    return {
      name: t("workspace:checks.ownership"),
      status: "info",
      message: t("workspace:status.checkFailed"),
      details: error instanceof Error ? error.message : String(error)
    };
  }
}
async function checkTrustedDirectories(cwd) {
  const settings = getClaudeSettings();
  if (!settings) {
    return {
      name: t("workspace:checks.trustedDirs"),
      status: "info",
      message: t("workspace:status.noSettings"),
      fixDescription: t("workspace:fixes.createSettings"),
      fix: async () => {
        return saveClaudeSettings({
          allowedDirectories: [cwd]
        });
      }
    };
  }
  const allowedDirs = settings.allowedDirectories || [];
  const isTrusted = allowedDirs.some((dir) => {
    const normalizedDir = resolve(dir);
    const normalizedCwd = resolve(cwd);
    return normalizedCwd === normalizedDir || normalizedCwd.startsWith(`${normalizedDir}/`);
  });
  if (!isTrusted) {
    return {
      name: t("workspace:checks.trustedDirs"),
      status: "warn",
      message: t("workspace:status.notTrusted"),
      details: t("workspace:details.trustedList", { dirs: allowedDirs.join(", ") || t("workspace:status.none") }),
      fixDescription: t("workspace:fixes.addToTrusted"),
      fix: async () => {
        const newSettings = { ...settings };
        const dirs = newSettings.allowedDirectories || [];
        dirs.push(cwd);
        newSettings.allowedDirectories = dirs;
        return saveClaudeSettings(newSettings);
      }
    };
  }
  return {
    name: t("workspace:checks.trustedDirs"),
    status: "pass",
    message: t("workspace:status.trusted")
  };
}
async function checkPathCharacters(cwd) {
  const problematicChars = /[<>:"|?*\x00-\x1F]/;
  const hasSpaces = cwd.includes(" ");
  const hasUnicode = /[^\x00-\x7F]/.test(cwd);
  if (problematicChars.test(cwd)) {
    return {
      name: t("workspace:checks.pathChars"),
      status: "fail",
      message: t("workspace:status.invalidChars"),
      details: t("workspace:details.avoidChars")
    };
  }
  if (hasSpaces || hasUnicode) {
    return {
      name: t("workspace:checks.pathChars"),
      status: "warn",
      message: hasSpaces ? t("workspace:status.hasSpaces") : t("workspace:status.hasUnicode"),
      details: t("workspace:details.mayHaveIssues")
    };
  }
  return {
    name: t("workspace:checks.pathChars"),
    status: "pass",
    message: t("workspace:status.pathOk")
  };
}
async function checkHomeDirectory(cwd) {
  const home = homedir();
  const normalizedCwd = resolve(cwd);
  const normalizedHome = resolve(home);
  const isInHome = normalizedCwd.startsWith(normalizedHome);
  if (!isInHome) {
    const systemDirs = ["/usr", "/bin", "/sbin", "/etc", "/var", "/tmp", "/root"];
    const isSystemDir = systemDirs.some((dir) => normalizedCwd.startsWith(dir));
    if (isSystemDir) {
      return {
        name: t("workspace:checks.homeDir"),
        status: "fail",
        message: t("workspace:status.systemDir"),
        details: t("workspace:details.dontUseSystemDir")
      };
    }
    return {
      name: t("workspace:checks.homeDir"),
      status: "warn",
      message: t("workspace:status.outsideHome"),
      details: t("workspace:details.recommendHome", { home })
    };
  }
  return {
    name: t("workspace:checks.homeDir"),
    status: "pass",
    message: t("workspace:status.insideHome")
  };
}
async function checkDiskSpace(cwd) {
  if (platform() === "win32") {
    return {
      name: t("workspace:checks.diskSpace"),
      status: "info",
      message: t("workspace:status.skippedWindows")
    };
  }
  try {
    const result = await q("df", ["-h", cwd], { throwOnError: false });
    const lines = result.stdout.trim().split("\n");
    if (lines.length >= 2) {
      const parts = lines[1].split(/\s+/);
      const available = parts[3];
      const usePercent = Number.parseInt(parts[4]);
      if (usePercent > 95) {
        return {
          name: t("workspace:checks.diskSpace"),
          status: "fail",
          message: t("workspace:status.diskFull", { percent: usePercent }),
          details: t("workspace:details.available", { space: available })
        };
      }
      if (usePercent > 90) {
        return {
          name: t("workspace:checks.diskSpace"),
          status: "warn",
          message: t("workspace:status.diskLow", { percent: usePercent }),
          details: t("workspace:details.available", { space: available })
        };
      }
      return {
        name: t("workspace:checks.diskSpace"),
        status: "pass",
        message: t("workspace:details.available", { space: available })
      };
    }
    return {
      name: t("workspace:checks.diskSpace"),
      status: "info",
      message: t("workspace:status.cannotCheck")
    };
  } catch {
    return {
      name: t("workspace:checks.diskSpace"),
      status: "info",
      message: t("workspace:status.checkFailed")
    };
  }
}
async function checkParentDirectory(cwd) {
  const parent = dirname(cwd);
  if (parent === cwd) {
    return {
      name: t("workspace:checks.parentDir"),
      status: "info",
      message: t("workspace:status.rootDir")
    };
  }
  try {
    const stat = statSync(parent);
    if (!stat.isDirectory()) {
      return {
        name: t("workspace:checks.parentDir"),
        status: "fail",
        message: t("workspace:status.parentNotDir")
      };
    }
    const { readdirSync } = await import('node:fs');
    readdirSync(parent);
    return {
      name: t("workspace:checks.parentDir"),
      status: "pass",
      message: t("workspace:status.parentOk")
    };
  } catch (error) {
    return {
      name: t("workspace:checks.parentDir"),
      status: "warn",
      message: t("workspace:status.parentAccessIssue"),
      details: error instanceof Error ? error.message : String(error)
    };
  }
}
async function checkEnvironment() {
  const isWSL = existsSync("/proc/version") && readFileSync("/proc/version", "utf-8").toLowerCase().includes("microsoft");
  const isDocker = existsSync("/.dockerenv") || existsSync("/proc/1/cgroup") && readFileSync("/proc/1/cgroup", "utf-8").includes("docker");
  if (isWSL) {
    return {
      name: t("workspace:checks.environment"),
      status: "info",
      message: t("workspace:status.wslDetected"),
      details: t("workspace:details.wslTips")
    };
  }
  if (isDocker) {
    return {
      name: t("workspace:checks.environment"),
      status: "info",
      message: t("workspace:status.dockerDetected"),
      details: t("workspace:details.dockerTips")
    };
  }
  return {
    name: t("workspace:checks.environment"),
    status: "pass",
    message: t("workspace:status.nativeEnv")
  };
}
async function runWorkspaceCheck(targetDir) {
  const cwd = targetDir ? resolve(targetDir) : process__default.cwd();
  const spinner = ora(t("workspace:checking")).start();
  const checks = [];
  spinner.text = t("workspace:checkingCwd");
  checks.push(await checkWorkingDirectory(cwd));
  spinner.text = t("workspace:checkingWrite");
  checks.push(await checkWritePermission(cwd));
  spinner.text = t("workspace:checkingOwnership");
  checks.push(await checkDirectoryOwnership(cwd));
  spinner.text = t("workspace:checkingTrusted");
  checks.push(await checkTrustedDirectories(cwd));
  spinner.text = t("workspace:checkingPath");
  checks.push(await checkPathCharacters(cwd));
  spinner.text = t("workspace:checkingHome");
  checks.push(await checkHomeDirectory(cwd));
  spinner.text = t("workspace:checkingDisk");
  checks.push(await checkDiskSpace(cwd));
  spinner.text = t("workspace:checkingParent");
  checks.push(await checkParentDirectory(cwd));
  spinner.text = t("workspace:checkingEnv");
  checks.push(await checkEnvironment());
  spinner.stop();
  const recommendations = [];
  const hasFailures = checks.some((c) => c.status === "fail");
  const hasWarnings = checks.some((c) => c.status === "warn");
  if (hasFailures) {
    recommendations.push(t("workspace:recommendations.fixFailures"));
  }
  if (hasWarnings) {
    recommendations.push(t("workspace:recommendations.reviewWarnings"));
  }
  const trustedCheck = checks.find((c) => c.name === t("workspace:checks.trustedDirs"));
  if (trustedCheck && trustedCheck.status !== "pass") {
    recommendations.push(t("workspace:recommendations.trustDir", { cmd: `claude config add trustedDirectories "${cwd}"` }));
  }
  return {
    cwd,
    isValid: !hasFailures,
    checks,
    recommendations
  };
}
function displayWorkspaceReport(report) {
  console.log(a.green(`
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 ${t("workspace:title")} \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
`));
  console.log(a.white.bold(`${t("workspace:currentDir")}: ${a.yellow(report.cwd)}
`));
  for (const check of report.checks) {
    let icon;
    let color;
    switch (check.status) {
      case "pass":
        icon = "\u2705";
        color = a.green;
        break;
      case "warn":
        icon = "\u26A0\uFE0F";
        color = a.yellow;
        break;
      case "fail":
        icon = "\u274C";
        color = a.red;
        break;
      case "info":
      default:
        icon = "\u2139\uFE0F";
        color = a.gray;
        break;
    }
    console.log(`${icon} ${a.bold(check.name.padEnd(20))} ${color(check.message)}`);
    if (check.details) {
      console.log(a.gray(`   ${check.details}`));
    }
    if (check.fixDescription && (check.status === "fail" || check.status === "warn")) {
      console.log(a.dim(`   \u{1F4A1} ${check.fixDescription}`));
    }
  }
  console.log("");
  console.log(a.dim("\u2500".repeat(50)));
  if (report.isValid) {
    console.log(STATUS.success(t("workspace:summary.valid")));
  } else {
    console.log(STATUS.error(t("workspace:summary.invalid")));
  }
  if (report.recommendations.length > 0) {
    console.log(a.yellow(`
${t("workspace:recommendations.title")}:`));
    for (const rec of report.recommendations) {
      console.log(a.yellow(`  \u2022 ${rec}`));
    }
  }
  console.log("");
}
async function runWorkspaceWizard(targetDir) {
  const report = await runWorkspaceCheck(targetDir);
  displayWorkspaceReport(report);
  const fixableChecks = report.checks.filter(
    (c) => c.fix && (c.status === "fail" || c.status === "warn")
  );
  if (fixableChecks.length === 0) {
    if (report.isValid) {
      console.log(STATUS.success(t("workspace:wizard.allGood")));
    } else {
      console.log(STATUS.warning(t("workspace:wizard.manualFix")));
    }
    return;
  }
  console.log("");
  console.log(a.green(t("workspace:wizard.autoFixing", { count: fixableChecks.length })));
  for (const check of fixableChecks) {
    const spinner = ora(`${t("workspace:wizard.fixing")} ${check.name}...`).start();
    try {
      const success = await check.fix();
      if (success) {
        spinner.succeed(`${check.name} ${t("workspace:wizard.fixed")}`);
      } else {
        spinner.fail(`${check.name} ${t("workspace:wizard.fixFailed")}`);
      }
    } catch (error) {
      spinner.fail(`${check.name}: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  console.log("");
  console.log(a.green(t("workspace:wizard.verifying")));
  const newReport = await runWorkspaceCheck(targetDir);
  if (newReport.isValid) {
    console.log(STATUS.success(t("workspace:wizard.allFixed")));
  } else {
    console.log(STATUS.warning(t("workspace:wizard.someRemain")));
    displayWorkspaceReport(newReport);
  }
}

async function checkClaudeCode(codeType) {
  const target = resolveClaudeFamilySettingsTarget(codeType);
  const runtimeCommand = getCodeToolRuntimeCommand(target.codeTool);
  const hasCommand = await commandExists(runtimeCommand);
  if (hasCommand) {
    return { name: target.displayName, status: "ok", message: "Installed" };
  }
  return {
    name: target.displayName,
    status: "error",
    message: "Not installed",
    fix: target.codeTool === "clavue" ? "Run: npm install -g clavue" : "Run: npm install -g @anthropic-ai/claude-code"
  };
}
async function checkClaudeDir(codeType) {
  const target = resolveClaudeFamilySettingsTarget(codeType);
  if (existsSync(target.configDir)) {
    return { name: "Config Directory", status: "ok", message: target.configDir };
  }
  return {
    name: "Config Directory",
    status: "error",
    message: "Does not exist",
    fix: "Run: npx ccjk init"
  };
}
async function checkSettings(codeType) {
  const target = resolveClaudeFamilySettingsTarget(codeType);
  if (!existsSync(target.settingsFile)) {
    return {
      name: "settings.json",
      status: "warning",
      message: "Not found",
      fix: "Run: npx ccjk init"
    };
  }
  try {
    const { readFileSync } = await import('node:fs');
    const content = readFileSync(target.settingsFile, "utf-8");
    const settings = JSON.parse(content);
    const issues = [];
    if (settings.$schema && settings.$schema !== "https://json.schemastore.org/claude-code-settings.json") {
      issues.push("Invalid $schema URL");
    }
    if (typeof settings.attribution === "string") {
      issues.push("attribution should be an object, not a string");
    }
    if (settings.fileSuggestion && settings.fileSuggestion.type !== "command") {
      issues.push('fileSuggestion.type must be "command"');
    }
    if (settings.permissions?.allow) {
      const lowerCaseTools = settings.permissions.allow.filter(
        (t) => /^[a-z]/.test(t) && !t.startsWith("Allow") && !t.startsWith("mcp__")
      );
      if (lowerCaseTools.length > 0) {
        issues.push(`${lowerCaseTools.length} permission(s) with lowercase names`);
      }
    }
    if (settings.plansDirectory === null) {
      issues.push("plansDirectory should not be null");
    }
    const env = settings.env || {};
    const hasAnthropicModelVars = Boolean(
      env.ANTHROPIC_MODEL || env.ANTHROPIC_DEFAULT_OPUS_MODEL || env.ANTHROPIC_DEFAULT_SONNET_MODEL || env.ANTHROPIC_DEFAULT_HAIKU_MODEL
    );
    if (settings.model && hasAnthropicModelVars) {
      issues.push(`settings.model="${settings.model}" overrides ANTHROPIC_* env vars (custom model selection broken)`);
    }
    const sonnet = env.ANTHROPIC_DEFAULT_SONNET_MODEL;
    if (typeof sonnet === "string" && /opus/i.test(sonnet)) {
      issues.push(`ANTHROPIC_DEFAULT_SONNET_MODEL="${sonnet}" looks like an Opus model (slot misrouted)`);
    }
    const preToolUse = settings.hooks?.PreToolUse;
    if (Array.isArray(preToolUse)) {
      const hasGatekeeper = preToolUse.some(
        (h) => h?.matcher === "mcp__.*" && Array.isArray(h?.hooks) && h.hooks.some((c) => typeof c?.command === "string" && c.command.includes("mcp-gatekeeper"))
      );
      if (hasGatekeeper) {
        issues.push("mcp-gatekeeper PreToolUse hook is enabled (forks bash+node per MCP call; disabled by default)");
      }
    }
    if (issues.length > 0) {
      return {
        name: "settings.json",
        status: "error",
        message: `Validation issues: ${issues.length} problem(s)`,
        fix: "Run: npx ccjk doctor --fix-settings",
        details: issues
      };
    }
    return { name: "settings.json", status: "ok", message: "Valid configuration" };
  } catch (_error) {
    return {
      name: "settings.json",
      status: "error",
      message: "Invalid JSON",
      fix: "Run: npx ccjk init"
    };
  }
}
async function checkWorkflows(codeType) {
  const target = resolveClaudeFamilySettingsTarget(codeType);
  const commandsDir = join(target.configDir, "commands", "ccjk");
  if (existsSync(commandsDir)) {
    try {
      const files = readdirSync(commandsDir, { recursive: true });
      const mdFiles = files.filter((f) => String(f).endsWith(".md"));
      if (mdFiles.length === 0) {
        return {
          name: "Workflows",
          status: "warning",
          message: "No CCJK commands installed",
          fix: `Run: npx ccjk zero-config dev${target.codeTool === "clavue" ? " --code-type clavue" : ""}`
        };
      }
      return {
        name: "Workflows",
        status: "ok",
        message: `${mdFiles.length} commands installed`
      };
    } catch {
      return { name: "Workflows", status: "warning", message: "Cannot read directory" };
    }
  }
  return {
    name: "Workflows",
    status: "warning",
    message: "Not installed",
    fix: "Run: npx ccjk update"
  };
}
async function checkMcp(codeType) {
  const target = resolveClaudeFamilySettingsTarget(codeType);
  try {
    const state = await inspectClaudeFamilyCoreFeatures(target.codeTool);
    if (state.mcp.installed.length > 0) {
      const result = {
        name: "MCP Services",
        status: state.mcp.missing.length === 0 ? "ok" : "warning",
        message: `${state.mcp.installed.length} service(s) configured`
      };
      if (state.mcp.missing.length > 0) {
        result.fix = `Run: npx ccjk zero-config dev${target.codeTool === "clavue" ? " --code-type clavue" : ""}`;
        result.details = [`Missing core service(s): ${state.mcp.missing.join(", ")}`];
      }
      return result;
    }
  } catch {
  }
  return {
    name: "MCP Services",
    status: "warning",
    message: "Not configured",
    fix: `Run: npx ccjk zero-config dev${target.codeTool === "clavue" ? " --code-type clavue" : ""}`
  };
}
async function checkCcr() {
  const status = await isCcrInstalled();
  if (status.hasCorrectPackage) {
    return { name: "CCR Proxy", status: "ok", message: "Installed" };
  }
  if (status.isInstalled) {
    return {
      name: "CCR Proxy",
      status: "warning",
      message: "Command exists, managed package not detected",
      fix: "Run: npx ccjk zero-config dev"
    };
  }
  return {
    name: "CCR Proxy",
    status: "warning",
    message: "Not installed",
    fix: "Run: npx ccjk zero-config dev"
  };
}
async function checkDisciplineBaseline(codeType) {
  const target = resolveClaudeFamilySettingsTarget(codeType);
  const memoryFile = target.instructionsFile;
  if (!existsSync(memoryFile)) {
    return {
      name: "Discipline Baseline",
      status: "warning",
      message: "No memory file found",
      fix: "Run: npx ccjk init"
    };
  }
  const { readFileSync } = await import('node:fs');
  const text = readFileSync(memoryFile, "utf-8");
  const required = [
    "# Coding Discipline Baseline",
    "Think before coding",
    "Simplicity first",
    "Surgical changes",
    "Goal-driven execution"
  ];
  const missing = required.filter((m) => !text.includes(m));
  if (missing.length === 0) {
    return {
      name: "Discipline Baseline",
      status: "ok",
      message: "All 4 principles present"
    };
  }
  if (missing.length === required.length) {
    return {
      name: "Discipline Baseline",
      status: "warning",
      message: "Baseline not installed (memory file exists but has no discipline section)",
      fix: "Run: npx ccjk init"
    };
  }
  return {
    name: "Discipline Baseline",
    status: "error",
    message: `Baseline partially missing: ${missing.length}/${required.length} markers absent`,
    fix: "Run: npx ccjk init  (will rewrite CLAUDE.md with full baseline)",
    details: missing
  };
}
async function checkOutputStyles(codeType) {
  const target = resolveClaudeFamilySettingsTarget(codeType);
  const stylesDir = join(target.configDir, "output-styles");
  if (existsSync(stylesDir)) {
    try {
      const files = readdirSync(stylesDir).filter((f) => f.endsWith(".md"));
      if (files.length === 0) {
        return {
          name: "Output Styles",
          status: "warning",
          message: "No styles installed",
          fix: `Run: npx ccjk zero-config dev${target.codeTool === "clavue" ? " --code-type clavue" : ""}`
        };
      }
      return {
        name: "Output Styles",
        status: "ok",
        message: `${files.length} styles available`
      };
    } catch {
      return { name: "Output Styles", status: "warning", message: "Cannot read directory" };
    }
  }
  return {
    name: "Output Styles",
    status: "warning",
    message: "Not installed",
    fix: `Run: npx ccjk zero-config dev${target.codeTool === "clavue" ? " --code-type clavue" : ""}`
  };
}
async function checkCodexCli() {
  const hasCommand = await commandExists("codex");
  if (hasCommand) {
    return { name: "Codex", status: "ok", message: "Installed" };
  }
  return {
    name: "Codex",
    status: "error",
    message: "Not installed",
    fix: "Run: npm install -g @openai/codex"
  };
}
async function checkCodexDir() {
  if (existsSync(CODEX_DIR)) {
    return { name: "Config Directory", status: "ok", message: CODEX_DIR };
  }
  return {
    name: "Config Directory",
    status: "error",
    message: "Does not exist",
    fix: "Run: npx ccjk init --code-type codex"
  };
}
async function checkCodexToml() {
  if (!existsSync(CODEX_CONFIG_FILE)) {
    return {
      name: "config.toml",
      status: "warning",
      message: "Not found",
      fix: "Run: ccjk zero-config dev --code-type codex"
    };
  }
  const config = readCodexConfig();
  if (!config) {
    return {
      name: "config.toml",
      status: "error",
      message: "Invalid TOML",
      fix: "Check ~/.codex/config.toml or run: ccjk zero-config dev --code-type codex"
    };
  }
  return {
    name: "config.toml",
    status: "ok",
    message: "Valid configuration"
  };
}
async function checkCodexFieldValues() {
  if (!existsSync(CODEX_CONFIG_FILE)) {
    return { name: "Codex Field Values", status: "ok", message: "Skipped (no config)" };
  }
  const { readFileSync } = await import('node:fs');
  const text = readFileSync(CODEX_CONFIG_FILE, "utf-8");
  const issues = [];
  const validEffort = /* @__PURE__ */ new Set(["minimal", "low", "medium", "high"]);
  const validTier = /* @__PURE__ */ new Set(["default", "flex", "priority"]);
  const effortMatch = text.match(/^model_reasoning_effort\s*=\s*"([^"]+)"/m);
  if (effortMatch && !validEffort.has(effortMatch[1])) {
    issues.push(`model_reasoning_effort="${effortMatch[1]}" (valid: ${[...validEffort].join("/")})`);
  }
  const tierMatch = text.match(/^service_tier\s*=\s*"([^"]+)"/m);
  if (tierMatch && !validTier.has(tierMatch[1])) {
    issues.push(`service_tier="${tierMatch[1]}" (valid: ${[...validTier].join("/")})`);
  }
  if (issues.length === 0) {
    return { name: "Codex Field Values", status: "ok", message: "All fields valid" };
  }
  return {
    name: "Codex Field Values",
    status: "warning",
    message: `${issues.length} non-standard value(s) \u2014 Codex silently uses defaults`,
    fix: "Edit ~/.codex/config.toml",
    details: issues
  };
}
async function checkCodexTrustedProjects() {
  if (!existsSync(CODEX_CONFIG_FILE)) {
    return { name: "Codex Trusted Projects", status: "ok", message: "Skipped (no config)" };
  }
  const { readFileSync } = await import('node:fs');
  const text = readFileSync(CODEX_CONFIG_FILE, "utf-8");
  const trusted = [];
  const re = /\[projects\."([^"]+)"\]/g;
  let m;
  while ((m = re.exec(text)) !== null) {
    trusted.push(m[1]);
  }
  const stale = trusted.filter((p) => !existsSync(p));
  if (stale.length === 0) {
    return {
      name: "Codex Trusted Projects",
      status: "ok",
      message: `${trusted.length} entries, all paths exist`
    };
  }
  return {
    name: "Codex Trusted Projects",
    status: "warning",
    message: `${stale.length} of ${trusted.length} trusted paths no longer exist on disk`,
    fix: "Edit ~/.codex/config.toml to remove dead entries",
    details: stale.slice(0, 10)
  };
}
async function checkCodexMcp() {
  const config = readCodexConfig();
  const count = config?.mcpServices.length || 0;
  if (count > 0) {
    return {
      name: "MCP Services",
      status: "ok",
      message: `${count} service(s) configured`
    };
  }
  return {
    name: "MCP Services",
    status: "warning",
    message: "Not configured",
    fix: "Run: npx ccjk mcp profile use recommended --tool codex"
  };
}
async function checkCodexNativeGoals() {
  const enabled = readCodexGoalsFeatureEnabled();
  if (enabled) {
    return {
      name: "Native Goals",
      status: "ok",
      message: "Codex /goal enabled"
    };
  }
  return {
    name: "Native Goals",
    status: "warning",
    message: "Codex /goal not enabled",
    fix: "Run: ccjk zero-config dev --code-type codex"
  };
}
async function checkClavueNativeGoals() {
  const hasCommand = await commandExists("clavue");
  if (hasCommand) {
    return {
      name: "Native Goals",
      status: "ok",
      message: "Clavue /goal available"
    };
  }
  return {
    name: "Native Goals",
    status: "error",
    message: "Clavue /goal unavailable",
    fix: "Run: npm install -g clavue"
  };
}
async function checkCcjkProfiles() {
  const { homedir } = await import('node:os');
  const ccjkConfigPath = join(homedir(), ".ccjk", "config.toml");
  if (!existsSync(ccjkConfigPath)) {
    return { name: "CCJK Profiles", status: "ok", message: "Skipped (no config)" };
  }
  const { readFileSync } = await import('node:fs');
  const text = readFileSync(ccjkConfigPath, "utf-8");
  const suspicious = [];
  const sectionRe = /^\[claudeCode\.profiles\.([^\]]+)\]$([\s\S]*?)(?=^\[|\z)/gm;
  let m;
  while ((m = sectionRe.exec(text)) !== null) {
    const name = m[1];
    const body = m[2];
    const apiKey = body.match(/apiKey\s*=\s*"([^"]*)"/)?.[1] ?? "";
    const baseUrl = body.match(/baseUrl\s*=\s*"([^"]*)"/)?.[1] ?? "";
    const reasons = [];
    if (/^\d+$/.test(name)) {
      reasons.push("numeric-only name");
    }
    if (apiKey && apiKey.length < 10) {
      reasons.push(`apiKey too short (${apiKey.length} chars)`);
    }
    if (baseUrl && !/^https?:\/\/[^\s/]+\.[^\s/]/.test(baseUrl)) {
      reasons.push(`baseUrl looks invalid: ${baseUrl}`);
    }
    if (apiKey.startsWith("sk-ant-test-") || /test-?\d+/i.test(apiKey)) {
      reasons.push("apiKey looks like a test placeholder");
    }
    if (reasons.length > 0) {
      suspicious.push(`${name}: ${reasons.join("; ")}`);
    }
  }
  if (suspicious.length === 0) {
    return { name: "CCJK Profiles", status: "ok", message: "No junk profiles detected" };
  }
  return {
    name: "CCJK Profiles",
    status: "warning",
    message: `${suspicious.length} suspicious profile(s) in ~/.ccjk/config.toml`,
    fix: "Use ccjk menu to remove or rename them",
    details: suspicious
  };
}
async function checkCodexProviders() {
  const config = readCodexConfig();
  if (!config) {
    return {
      name: "API Providers",
      status: "warning",
      message: "Unable to read Codex config"
    };
  }
  if (config.modelProvider) {
    return {
      name: "API Providers",
      status: "ok",
      message: `Using ${config.modelProvider}`
    };
  }
  return {
    name: "API Providers",
    status: "ok",
    message: "Using official Codex login"
  };
}
async function checkProviders(codeType = "claude-code") {
  try {
    const providers = await getApiProviderPresets(codeType);
    if (providers.length === 0) {
      return {
        name: "API Providers",
        status: "warning",
        message: "No providers available"
      };
    }
    const monitor = new ProviderHealthMonitor({
      timeout: 3e3,
      degradedLatencyThreshold: 1e3,
      unhealthyLatencyThreshold: 3e3
    });
    monitor.setProviders(providers);
    const results = await Promise.race([
      Promise.all(
        providers.map(async (provider) => {
          const result = await monitor.checkHealth(provider);
          return { provider, result };
        })
      ),
      new Promise((resolve2) => {
        setTimeout(() => resolve2(null), 5e3);
      })
    ]);
    if (!results) {
      return {
        name: "API Providers",
        status: "warning",
        message: "Health check timeout"
      };
    }
    const healthyCount = results.filter((r) => r.result.success).length;
    if (healthyCount === 0) {
      return {
        name: "API Providers",
        status: "error",
        message: "All providers unavailable",
        fix: "Check your network connection"
      };
    }
    if (healthyCount < providers.length) {
      return {
        name: "API Providers",
        status: "warning",
        message: `${healthyCount}/${providers.length} providers healthy`
      };
    }
    return {
      name: "API Providers",
      status: "ok",
      message: `${healthyCount} providers healthy`
    };
  } catch {
    return {
      name: "API Providers",
      status: "warning",
      message: "Health check failed"
    };
  }
}
async function checkPermissionRules(codeType) {
  const isZh = i18n.language === "zh-CN";
  try {
    const target = resolveClaudeFamilySettingsTarget(codeType);
    const permissionManager = getPermissionManager(void 0, target.settingsFile);
    const unreachableRules = permissionManager.getUnreachableRules();
    const allDiagnostics = permissionManager.getAllDiagnostics();
    const conflictedRules = allDiagnostics.filter((d) => d.conflicts.length > 0);
    const problemCount = unreachableRules.length + conflictedRules.length;
    if (problemCount === 0) {
      const stats = permissionManager.getStats();
      return {
        name: "Permission Rules",
        status: "ok",
        message: `${stats.total} rules configured`
      };
    }
    const details = [];
    if (unreachableRules.length > 0) {
      details.push(isZh ? `${unreachableRules.length} unreachable rule(s)` : `${unreachableRules.length} unreachable rule(s)`);
      for (const rule of unreachableRules.slice(0, 3)) {
        details.push(`  - ${a.dim(rule.pattern)}`);
      }
      if (unreachableRules.length > 3) {
        details.push(`  ... ${isZh ? "and" : "and"} ${unreachableRules.length - 3} ${isZh ? "more" : "more"}`);
      }
    }
    if (conflictedRules.length > 0) {
      details.push(isZh ? `${conflictedRules.length} conflicted rule(s)` : `${conflictedRules.length} conflicted rule(s)`);
    }
    return {
      name: "Permission Rules",
      status: "warning",
      message: `${problemCount} ${isZh ? "problematic" : "problematic"} ${isZh ? "rule(s)" : "rule(s)"}`,
      fix: isZh ? "Run: ccjk zero-config dev" : "Run: ccjk zero-config dev",
      details
    };
  } catch {
    return {
      name: "Permission Rules",
      status: "warning",
      message: "Unable to check"
    };
  }
}
async function fixSettingsFile(codeType) {
  const isZh = i18n.language === "zh-CN";
  const target = resolveClaudeFamilySettingsTarget(codeType);
  console.log("");
  console.log(a.bold.cyan("\u{1F527} Fixing settings.json"));
  console.log(a.dim("\u2500".repeat(50)));
  console.log("");
  const backupPath = backupExistingConfig(target.codeTool);
  try {
    if (existsSync(target.settingsFile) && backupPath) {
      console.log(a.green(`\u2714 ${isZh ? "\u5DF2\u5907\u4EFD\u65E7\u8BBE\u7F6E" : "Backed up settings"}: ${backupPath}`));
    }
  } catch (_error) {
    console.log(a.yellow(`\u26A0\uFE0F ${isZh ? "\u5907\u4EFD\u5931\u8D25\uFF0C\u7EE7\u7EED..." : "Backup failed, continuing..."}`));
  }
  console.log("");
  console.log(a.dim(isZh ? "\u6B63\u5728\u5408\u5E76\u6A21\u677F\u8BBE\u7F6E..." : "Merging template settings..."));
  copyConfigFiles(false, target.codeTool);
  const checkResult = await checkSettings(target.codeTool);
  console.log("");
  if (checkResult.status === "ok") {
    console.log(a.green(`\u2705 ${isZh ? "\u8BBE\u7F6E\u5DF2\u4FEE\u590D\uFF01" : "Settings fixed successfully!"}`));
  } else {
    console.log(a.yellow(`\u26A0\uFE0F ${isZh ? "\u4ECD\u6709\u4E00\u4E9B\u95EE\u9898" : "Some issues remain"}:`));
    if (checkResult.details) {
      for (const detail of checkResult.details) {
        console.log(a.dim(`   \u2022 ${detail}`));
      }
    }
  }
  console.log("");
  console.log(a.dim(isZh ? "\u63D0\u793A: \u8BF7\u91CD\u542F Claude Code \u4EE5\u5E94\u7528\u66F4\u6539" : "Tip: Restart Claude Code to apply changes"));
  console.log("");
}
async function doctor(options = {}) {
  const isZh = i18n.language === "zh-CN";
  if (options.fixSettings) {
    await fixSettingsFile(options.codeType);
    return;
  }
  const checks = options.codeType === "codex" ? [
    checkCodexCli,
    checkCodexDir,
    checkCodexToml,
    checkCodexFieldValues,
    checkCodexTrustedProjects,
    checkCodexMcp,
    checkCodexNativeGoals,
    checkCcjkProfiles
  ] : [
    () => checkClaudeCode(options.codeType),
    () => checkClaudeDir(options.codeType),
    () => checkSettings(options.codeType),
    () => checkDisciplineBaseline(options.codeType),
    () => checkWorkflows(options.codeType),
    () => checkMcp(options.codeType),
    () => checkPermissionRules(options.codeType),
    checkCcr,
    () => checkOutputStyles(options.codeType),
    ...options.codeType === "clavue" ? [checkClavueNativeGoals] : [],
    checkCcjkProfiles
  ];
  if (options.checkProviders) {
    checks.push(options.codeType === "codex" ? checkCodexProviders : () => checkProviders(options.codeType));
  }
  const results = [];
  for (const check of checks) {
    const result = await check();
    results.push(result);
  }
  if (options.json) {
    const output = {
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      summary: {
        total: results.length,
        ok: results.filter((r) => r.status === "ok").length,
        warning: results.filter((r) => r.status === "warning").length,
        error: results.filter((r) => r.status === "error").length
      },
      checks: results.map((r) => ({
        name: r.name,
        status: r.status,
        message: r.message,
        fix: r.fix,
        details: r.details
      }))
    };
    console.log(JSON.stringify(output, null, 2));
    return;
  }
  console.log("");
  console.log(a.bold.cyan("\u{1F50D} CCJK Health Check"));
  console.log(a.dim("\u2500".repeat(50)));
  console.log("");
  let hasErrors = false;
  let hasWarnings = false;
  for (const result of results) {
    const statusIcon = result.status === "ok" ? a.green("\u2705") : result.status === "warning" ? a.yellow("\u26A0\uFE0F") : a.red("\u274C");
    const statusColor = result.status === "ok" ? a.green : result.status === "warning" ? a.yellow : a.red;
    console.log(`${statusIcon} ${a.bold(result.name)}: ${statusColor(result.message)}`);
    if (result.fix) {
      console.log(a.dim(`   \u{1F4A1} Fix: ${result.fix}`));
    }
    if (result.details && result.details.length > 0) {
      for (const detail of result.details) {
        console.log(a.dim(`   ${detail}`));
      }
    }
    if (result.status === "error")
      hasErrors = true;
    if (result.status === "warning")
      hasWarnings = true;
  }
  console.log("");
  console.log(a.dim("\u2500".repeat(50)));
  if (hasErrors) {
    console.log(a.red("\u274C Issues found - please follow the suggestions above"));
  } else if (hasWarnings) {
    console.log(a.yellow("\u26A0\uFE0F Configuration is functional, but some features may be limited"));
  } else {
    console.log(a.green("\u2705 All checks passed - CCJK is properly configured!"));
  }
  console.log("");
  if (!options.checkProviders) {
    const { checkProvidersNow } = await inquirer.prompt({
      type: "confirm",
      name: "checkProvidersNow",
      message: isZh ? "\u662F\u5426\u68C0\u67E5 API \u4F9B\u5E94\u5546\u5065\u5EB7\u72B6\u6001\uFF1F" : "Check API provider health status?",
      default: false
    });
    if (checkProvidersNow) {
      console.log("");
      console.log(a.dim(isZh ? "\u6B63\u5728\u68C0\u67E5\u4F9B\u5E94\u5546..." : "Checking providers..."));
      const providerResult = await checkProviders(options.codeType);
      const statusIcon = providerResult.status === "ok" ? a.green("\u2705") : providerResult.status === "warning" ? a.yellow("\u26A0\uFE0F") : a.red("\u274C");
      const statusColor = providerResult.status === "ok" ? a.green : providerResult.status === "warning" ? a.yellow : a.red;
      console.log(`${statusIcon} ${a.bold(providerResult.name)}: ${statusColor(providerResult.message)}`);
      if (providerResult.fix) {
        console.log(a.dim(`   \u{1F4A1} Fix: ${providerResult.fix}`));
      }
      console.log("");
    }
  }
  const { runWorkspace } = await inquirer.prompt({
    type: "confirm",
    name: "runWorkspace",
    message: isZh ? "\u662F\u5426\u68C0\u67E5\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\u7684\u6587\u4EF6\u5199\u5165\u6743\u9650\uFF1F" : "Check file write permissions for current directory?",
    default: false
  });
  if (runWorkspace) {
    console.log("");
    const report = await runWorkspaceCheck(process__default.cwd());
    displayWorkspaceReport(report);
  }
}
async function workspaceDiagnostics(targetDir) {
  const dir = targetDir ? resolve(targetDir) : process__default.cwd();
  await runWorkspaceWizard(dir);
}

export { doctor, workspaceDiagnostics };
