import { i as inquirer } from './index6.mjs';
import { execSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { CCJK_CONFIG_DIR, CODE_TOOL_INFO, CODE_TOOL_ALIASES, DEFAULT_CODE_TOOL_TYPE, isCodeToolType } from './constants.mjs';
import { writeJsonConfig } from './json-config.mjs';
import { j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';
import { a as getPlatform, c as commandExists } from './platform.mjs';
import process__default from 'node:process';
import { i18n } from './index2.mjs';
import { readZcfConfigAsync, updateZcfConfig } from './ccjk-config.mjs';

const ORCHESTRATION_LEVELS = ["off", "minimal", "standard", "max"];
function parseOrchestrationLevel(value) {
  if (!value) {
    return "max";
  }
  const normalized = value.trim().toLowerCase();
  if (ORCHESTRATION_LEVELS.includes(normalized)) {
    return normalized;
  }
  throw new Error(`Invalid orchestration level: ${value}. Valid values: ${ORCHESTRATION_LEVELS.join(", ")}`);
}
function buildDefaults(level) {
  if (level === "off") {
    return {
      planForNonTrivial: false,
      useSubagentsForResearch: false,
      verifyBeforeDone: false,
      rootCauseFirst: true,
      lessonsLoop: false
    };
  }
  if (level === "minimal") {
    return {
      planForNonTrivial: true,
      useSubagentsForResearch: false,
      verifyBeforeDone: true,
      rootCauseFirst: true,
      lessonsLoop: false
    };
  }
  if (level === "max") {
    return {
      planForNonTrivial: true,
      useSubagentsForResearch: true,
      verifyBeforeDone: true,
      rootCauseFirst: true,
      lessonsLoop: true
    };
  }
  return {
    planForNonTrivial: true,
    useSubagentsForResearch: true,
    verifyBeforeDone: true,
    rootCauseFirst: true,
    lessonsLoop: true
  };
}
function resolveOrchestrationLevelFromRuntime(runtime) {
  if (!runtime) {
    return "max";
  }
  if (runtime.isCI || runtime.isContainer) {
    return "minimal";
  }
  if (runtime.isSSH) {
    return "minimal";
  }
  return "max";
}
function writeOrchestrationPolicy(params) {
  const filePath = join(CCJK_CONFIG_DIR, "orchestration.json");
  const policy = {
    version: "1.0.0",
    enabled: params.level !== "off",
    level: params.level,
    language: params.language,
    defaults: buildDefaults(params.level),
    generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
    source: params.source
  };
  writeJsonConfig(filePath, policy, { atomic: true });
  return filePath;
}

function scanProject(cwd) {
  const root = cwd || process__default.cwd();
  const pkg = readPackageJson(root);
  const language = detectLanguage(root, pkg);
  const secondaryLanguages = detectSecondaryLanguages(root, pkg, language);
  return {
    language,
    secondaryLanguages,
    framework: detectFramework(root, pkg),
    testRunner: detectTestRunner(root, pkg),
    packageManager: detectPackageManager(root),
    linter: detectLinter(root, pkg),
    formatter: detectFormatter(root, pkg),
    database: detectDatabase(root),
    runtime: detectRuntime(),
    isMonorepo: detectMonorepo(root, pkg),
    usesConventionalCommits: detectConventionalCommits(root, pkg),
    hasGitHooks: detectGitHooks(root, pkg),
    hasDocker: existsSync(join(root, "Dockerfile")) || existsSync(join(root, "docker-compose.yml")) || existsSync(join(root, "docker-compose.yaml")),
    hasCI: detectCI(root),
    root
  };
}
function readPackageJson(root) {
  const p = join(root, "package.json");
  if (!existsSync(p))
    return null;
  try {
    return JSON.parse(readFileSync(p, "utf-8"));
  } catch {
    return null;
  }
}
function hasDep(pkg, name) {
  if (!pkg)
    return false;
  return !!(pkg.dependencies?.[name] || pkg.devDependencies?.[name] || pkg.peerDependencies?.[name]);
}
function detectLanguage(root, pkg) {
  if (existsSync(join(root, "tsconfig.json")) || hasDep(pkg, "typescript")) {
    return "typescript";
  }
  if (existsSync(join(root, "pyproject.toml")) || existsSync(join(root, "setup.py")) || existsSync(join(root, "requirements.txt")) || existsSync(join(root, "Pipfile"))) {
    return "python";
  }
  if (existsSync(join(root, "go.mod"))) {
    return "go";
  }
  if (existsSync(join(root, "Cargo.toml"))) {
    return "rust";
  }
  if (existsSync(join(root, "pom.xml")) || existsSync(join(root, "build.gradle")) || existsSync(join(root, "build.gradle.kts"))) {
    return "java";
  }
  if (existsSync(join(root, "Gemfile"))) {
    return "ruby";
  }
  if (existsSync(join(root, "composer.json"))) {
    return "php";
  }
  if (existsSync(join(root, "Package.swift"))) {
    return "swift";
  }
  if (existsSync(join(root, "*.csproj")) || existsSync(join(root, "*.sln"))) {
    return "csharp";
  }
  if (pkg) {
    return "javascript";
  }
  return "unknown";
}
function detectSecondaryLanguages(root, pkg, primary) {
  const langs = [];
  const checks = [
    ["typescript", () => existsSync(join(root, "tsconfig.json")) || hasDep(pkg, "typescript")],
    ["javascript", () => !!pkg],
    ["python", () => existsSync(join(root, "pyproject.toml")) || existsSync(join(root, "requirements.txt"))],
    ["go", () => existsSync(join(root, "go.mod"))],
    ["rust", () => existsSync(join(root, "Cargo.toml"))]
  ];
  for (const [lang, check] of checks) {
    if (lang !== primary && check())
      langs.push(lang);
  }
  return langs;
}
function detectFramework(root, pkg) {
  if (!pkg) {
    if (existsSync(join(root, "pyproject.toml"))) {
      const content = safeRead(join(root, "pyproject.toml"));
      if (content.includes("fastapi"))
        return "fastapi";
      if (content.includes("django"))
        return "django";
      if (content.includes("flask"))
        return "flask";
    }
    if (existsSync(join(root, "requirements.txt"))) {
      const content = safeRead(join(root, "requirements.txt"));
      if (content.includes("fastapi"))
        return "fastapi";
      if (content.includes("django"))
        return "django";
      if (content.includes("flask"))
        return "flask";
    }
    return "none";
  }
  if (hasDep(pkg, "next"))
    return "next";
  if (hasDep(pkg, "nuxt"))
    return "nuxt";
  if (hasDep(pkg, "@angular/core"))
    return "angular";
  if (hasDep(pkg, "svelte") || hasDep(pkg, "@sveltejs/kit"))
    return "svelte";
  if (hasDep(pkg, "@nestjs/core"))
    return "nest";
  if (hasDep(pkg, "@tauri-apps/api") || hasDep(pkg, "@tauri-apps/cli"))
    return "tauri";
  if (hasDep(pkg, "electron"))
    return "electron";
  if (hasDep(pkg, "vue"))
    return "vue";
  if (hasDep(pkg, "react"))
    return "react";
  if (hasDep(pkg, "fastify"))
    return "fastify";
  if (hasDep(pkg, "express"))
    return "express";
  return "none";
}
function detectTestRunner(root, pkg) {
  if (hasDep(pkg, "vitest"))
    return "vitest";
  if (hasDep(pkg, "jest") || hasDep(pkg, "@jest/core"))
    return "jest";
  if (hasDep(pkg, "mocha"))
    return "mocha";
  if (existsSync(join(root, "pytest.ini")) || existsSync(join(root, "conftest.py")))
    return "pytest";
  if (existsSync(join(root, "pyproject.toml"))) {
    const content = safeRead(join(root, "pyproject.toml"));
    if (content.includes("[tool.pytest") || content.includes("pytest"))
      return "pytest";
  }
  if (existsSync(join(root, "go.mod")))
    return "go-test";
  if (existsSync(join(root, "Cargo.toml")))
    return "cargo-test";
  if (existsSync(join(root, "pom.xml")) || existsSync(join(root, "build.gradle")))
    return "junit";
  if (existsSync(join(root, "Gemfile"))) {
    const content = safeRead(join(root, "Gemfile"));
    if (content.includes("rspec"))
      return "rspec";
  }
  if (hasDep(pkg, "phpunit") || existsSync(join(root, "phpunit.xml")))
    return "phpunit";
  return "none";
}
function detectPackageManager(root) {
  if (existsSync(join(root, "pnpm-lock.yaml")) || existsSync(join(root, "pnpm-workspace.yaml")))
    return "pnpm";
  if (existsSync(join(root, "bun.lockb")) || existsSync(join(root, "bun.lock")))
    return "bun";
  if (existsSync(join(root, "yarn.lock")))
    return "yarn";
  if (existsSync(join(root, "package-lock.json")))
    return "npm";
  if (existsSync(join(root, "poetry.lock")))
    return "poetry";
  if (existsSync(join(root, "Pipfile.lock")) || existsSync(join(root, "requirements.txt")))
    return "pip";
  if (existsSync(join(root, "Cargo.lock")))
    return "cargo";
  if (existsSync(join(root, "go.sum")))
    return "go";
  if (existsSync(join(root, "pom.xml")))
    return "maven";
  if (existsSync(join(root, "build.gradle")) || existsSync(join(root, "build.gradle.kts")))
    return "gradle";
  return "none";
}
function detectLinter(root, pkg) {
  if (hasDep(pkg, "@biomejs/biome") || existsSync(join(root, "biome.json")) || existsSync(join(root, "biome.jsonc")))
    return "biome";
  if (hasDep(pkg, "oxlint") || hasDep(pkg, "oxc"))
    return "oxlint";
  if (hasDep(pkg, "eslint") || existsSync(join(root, ".eslintrc.json")) || existsSync(join(root, ".eslintrc.js")) || existsSync(join(root, "eslint.config.js")) || existsSync(join(root, "eslint.config.mjs")))
    return "eslint";
  if (existsSync(join(root, "ruff.toml")) || existsSync(join(root, ".ruff.toml")))
    return "ruff";
  if (existsSync(join(root, "pyproject.toml"))) {
    const content = safeRead(join(root, "pyproject.toml"));
    if (content.includes("[tool.ruff"))
      return "ruff";
    if (content.includes("[tool.pylint") || content.includes("pylint"))
      return "pylint";
    if (content.includes("flake8"))
      return "flake8";
  }
  if (existsSync(join(root, ".golangci.yml")) || existsSync(join(root, ".golangci.yaml")))
    return "golangci-lint";
  if (existsSync(join(root, "Cargo.toml")))
    return "clippy";
  if (existsSync(join(root, ".rubocop.yml")))
    return "rubocop";
  return "none";
}
function detectFormatter(root, pkg) {
  if (hasDep(pkg, "@biomejs/biome") || existsSync(join(root, "biome.json")))
    return "biome";
  if (hasDep(pkg, "prettier") || existsSync(join(root, ".prettierrc")) || existsSync(join(root, ".prettierrc.json")) || existsSync(join(root, "prettier.config.js")) || existsSync(join(root, "prettier.config.mjs")))
    return "prettier";
  if (existsSync(join(root, "pyproject.toml"))) {
    const content = safeRead(join(root, "pyproject.toml"));
    if (content.includes("[tool.ruff") && content.includes("format"))
      return "ruff";
    if (content.includes("[tool.black") || content.includes("black"))
      return "black";
  }
  if (existsSync(join(root, "go.mod")))
    return "gofmt";
  if (existsSync(join(root, "Cargo.toml")))
    return "rustfmt";
  return "none";
}
function detectDatabase(root) {
  for (const f of ["docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"]) {
    const content = safeRead(join(root, f));
    if (!content)
      continue;
    if (content.includes("postgres"))
      return "postgresql";
    if (content.includes("mysql") || content.includes("mariadb"))
      return "mysql";
    if (content.includes("mongo"))
      return "mongodb";
    if (content.includes("redis"))
      return "redis";
  }
  for (const f of [".env", ".env.local", ".env.development"]) {
    const content = safeRead(join(root, f));
    if (!content)
      continue;
    if (content.includes("postgres"))
      return "postgresql";
    if (content.includes("mysql"))
      return "mysql";
    if (content.includes("mongodb") || content.includes("mongo+srv"))
      return "mongodb";
    if (content.includes("redis://"))
      return "redis";
  }
  if (existsSync(join(root, "prisma", "schema.prisma"))) {
    const content = safeRead(join(root, "prisma", "schema.prisma"));
    if (content.includes("postgresql"))
      return "postgresql";
    if (content.includes("mysql"))
      return "mysql";
    if (content.includes("sqlite"))
      return "sqlite";
    if (content.includes("mongodb"))
      return "mongodb";
  }
  if (existsSync(join(root, "db.sqlite")) || existsSync(join(root, "database.sqlite")) || existsSync(join(root, "dev.db"))) {
    return "sqlite";
  }
  return "none";
}
function detectRuntime() {
  const isContainer = existsSync("/.dockerenv") || existsSync("/run/.containerenv") || safeRead("/proc/1/cgroup").includes("docker");
  const isSSH = !!process__default.env.SSH_CLIENT || !!process__default.env.SSH_TTY || !!process__default.env.SSH_CONNECTION;
  const isCI = !!(process__default.env.CI || process__default.env.GITHUB_ACTIONS || process__default.env.GITLAB_CI || process__default.env.JENKINS_URL || process__default.env.CIRCLECI || process__default.env.TRAVIS || process__default.env.BUILDKITE);
  const isWSL = safeRead("/proc/version").toLowerCase().includes("microsoft");
  const isMac = process__default.platform === "darwin";
  const hasDisplay = !!(process__default.env.DISPLAY || process__default.env.WAYLAND_DISPLAY || process__default.env.TERM_PROGRAM);
  const isHeadless = !isMac && !hasDisplay && !isWSL;
  const hasBrowser = isMac || hasDisplay || isWSL;
  return {
    isContainer,
    isHeadless,
    isSSH,
    isCI,
    isWSL,
    hasBrowser
  };
}
function detectMonorepo(root, pkg) {
  if (pkg?.workspaces)
    return true;
  if (existsSync(join(root, "pnpm-workspace.yaml")))
    return true;
  if (existsSync(join(root, "lerna.json")))
    return true;
  if (existsSync(join(root, "nx.json")))
    return true;
  if (existsSync(join(root, "turbo.json")))
    return true;
  return false;
}
function detectConventionalCommits(root, pkg) {
  if (existsSync(join(root, ".commitlintrc.json")) || existsSync(join(root, ".commitlintrc.js")) || existsSync(join(root, "commitlint.config.js")) || existsSync(join(root, "commitlint.config.mjs"))) {
    return true;
  }
  if (hasDep(pkg, "@commitlint/cli") || hasDep(pkg, "@commitlint/config-conventional"))
    return true;
  try {
    const log = execSync("git log --oneline -10 2>/dev/null", { cwd: root, encoding: "utf-8", timeout: 3e3 });
    const conventionalPattern = /^[a-f0-9]+ (feat|fix|chore|docs|style|refactor|perf|test|build|ci|revert)(\(.+\))?!?:/m;
    const lines = log.trim().split("\n").filter(Boolean);
    const matches = lines.filter((l) => conventionalPattern.test(l));
    return lines.length > 0 && matches.length / lines.length > 0.5;
  } catch {
    return false;
  }
}
function detectGitHooks(root, pkg) {
  if (existsSync(join(root, ".husky")))
    return true;
  if (hasDep(pkg, "husky") || hasDep(pkg, "simple-git-hooks") || hasDep(pkg, "lefthook"))
    return true;
  if (existsSync(join(root, ".lefthook.yml")))
    return true;
  return false;
}
function detectCI(root) {
  return existsSync(join(root, ".github", "workflows")) || existsSync(join(root, ".gitlab-ci.yml")) || existsSync(join(root, ".circleci")) || existsSync(join(root, "Jenkinsfile")) || existsSync(join(root, ".travis.yml")) || existsSync(join(root, "bitbucket-pipelines.yml"));
}
function safeRead(path) {
  try {
    if (!existsSync(path))
      return "";
    return readFileSync(path, "utf-8");
  } catch {
    return "";
  }
}

class SmartDefaultsDetector {
  /**
   * Detect environment and generate smart defaults
   */
  async detect(cwd) {
    const platform = getPlatform();
    const apiKey = this.detectApiKey();
    const apiProvider = this.detectApiProvider(apiKey);
    const codeToolType = this.detectCodeToolType();
    const ccVersion = await this.detectClaudeCodeVersion(codeToolType);
    const projectContext = scanProject(cwd);
    return {
      // Environment detection
      platform,
      homeDir: homedir(),
      // API configuration
      apiKey,
      apiProvider,
      // Recommended MCP services based on platform + project
      mcpServices: this.getRecommendedMcpServices(platform, projectContext),
      // Essential skills — reduced in CI/container (non-interactive)
      skills: projectContext.runtime.isCI || projectContext.runtime.isContainer ? ["ccjk:git-commit"] : [
        "ccjk:git-commit",
        "ccjk:feat",
        "ccjk:workflow",
        "ccjk:init-project",
        "ccjk:git-worktree"
      ],
      // Core agents — skip in CI/container (non-interactive)
      agents: projectContext.runtime.isCI || projectContext.runtime.isContainer ? [] : [
        "typescript-cli-architect",
        "ccjk-testing-specialist"
      ],
      // Code tool detection
      codeToolType,
      // Workflow preferences
      workflows: {
        outputStyle: "engineer-professional",
        gitWorkflow: projectContext.usesConventionalCommits ? "conventional-commits" : "conventional-commits",
        sixStepWorkflow: true,
        orchestrationLevel: resolveOrchestrationLevelFromRuntime(projectContext.runtime)
      },
      // Tool integrations
      tools: {
        ccr: this.shouldEnableCCR(),
        cometix: this.shouldEnableCometix(),
        ccusage: this.shouldEnableCCUsage()
      },
      // Claude Code native features
      claudeCodeVersion: ccVersion,
      nativeFeatures: this.detectNativeFeatures(ccVersion),
      // Project context
      projectContext,
      // Recommended hooks based on project toolchain
      recommendedHooks: this.getRecommendedHooks(projectContext),
      // SSH session flag for quick-setup notice
      sshDetected: projectContext.runtime.isSSH || void 0
    };
  }
  /**
   * Detect installed Claude Code version
   */
  async detectClaudeCodeVersion(preferredCodeTool) {
    const preferredCommand = preferredCodeTool && preferredCodeTool in CODE_TOOL_INFO ? CODE_TOOL_INFO[preferredCodeTool].runtimeCommand : void 0;
    const candidateCommands = [
      preferredCommand,
      CODE_TOOL_INFO["claude-code"].runtimeCommand,
      CODE_TOOL_INFO.clavue.runtimeCommand
    ].filter((command, index, commands) => Boolean(command) && commands.indexOf(command) === index);
    for (const command of candidateCommands) {
      try {
        if (!await commandExists(command)) {
          continue;
        }
        const output = execSync(`${command} --version 2>/dev/null || echo ""`, {
          encoding: "utf-8",
          timeout: 5e3
        }).trim();
        const match = output.match(/(\d+\.\d+\.\d+)/);
        if (match) {
          return match[1];
        }
      } catch {
      }
    }
    return void 0;
  }
  /**
   * Detect which Claude Code native features are available
   * based on installed version
   */
  detectNativeFeatures(version) {
    return {
      hooks: this.versionSupports(version, "1.0.6"),
      plansDirectory: this.versionSupports(version, "1.0.10"),
      memory: this.versionSupports(version, "1.0.12"),
      subagents: this.versionSupports(version, "1.0.3"),
      toolSearch: this.versionSupports(version, "1.0.10"),
      statusLine: this.versionSupports(version, "1.0.8")
    };
  }
  /**
   * Check if a version meets the minimum requirement
   */
  versionSupports(version, minVersion) {
    if (!version)
      return false;
    const parts = version.split(".").map(Number);
    const minParts = minVersion.split(".").map(Number);
    for (let i = 0; i < 3; i++) {
      if ((parts[i] || 0) > (minParts[i] || 0))
        return true;
      if ((parts[i] || 0) < (minParts[i] || 0))
        return false;
    }
    return true;
  }
  /**
   * Detect API key from environment variables
   */
  detectApiKey() {
    const envVars = [
      "ANTHROPIC_API_KEY",
      "CLAUDE_API_KEY",
      "API_KEY"
    ];
    for (const envVar of envVars) {
      const value = process.env[envVar];
      if (value && value.length >= 10) {
        return value;
      }
    }
    const claudeConfigPath = join(homedir(), ".config", "claude", "config.json");
    if (existsSync(claudeConfigPath)) {
      try {
        const configContent = readFileSync(claudeConfigPath, "utf-8");
        const config = JSON.parse(configContent);
        if (config.apiKey && config.apiKey.length >= 10) {
          return config.apiKey;
        }
      } catch {
      }
    }
    return void 0;
  }
  /**
   * Detect API provider based on API key pattern
   */
  detectApiProvider(apiKey) {
    if (!apiKey) {
      return void 0;
    }
    if (apiKey.startsWith("sk-ant-")) {
      return "anthropic";
    }
    return void 0;
  }
  /**
   * Detect installed code tool type (instance method delegates to static)
   */
  detectCodeToolType() {
    return SmartDefaultsDetector.detectCodeToolType();
  }
  /**
   * Detect installed code tool type by checking filesystem markers.
   * This is a static method so it can be called without instantiating the full detector.
   */
  static detectCodeToolType() {
    const clavueMarkers = [
      join(homedir(), ".clavue", ".clavue.json"),
      join(homedir(), ".clavue", "settings.json")
    ];
    try {
      if (clavueMarkers.some((p) => existsSync(p))) {
        const globalConfigPath = join(homedir(), ".clavue", ".clavue.json");
        if (existsSync(globalConfigPath)) {
          const configContent = readFileSync(globalConfigPath, "utf-8");
          const config = JSON.parse(configContent);
          if (config.clavueActiveProviderProfileId || config.clavueProviderProfiles || config.myclaudeActiveProviderProfileId || config.myclaudeProviderProfiles) {
            return "clavue";
          }
        }
        return "clavue";
      }
    } catch {
    }
    const claudeCodePaths = [
      join(homedir(), ".claude"),
      join(homedir(), ".config", "claude")
    ];
    if (claudeCodePaths.some((p) => existsSync(p))) {
      return "claude-code";
    }
    const codexPath = join(homedir(), ".codex");
    if (existsSync(codexPath)) {
      return "codex";
    }
    return "clavue";
  }
  /**
   * Check if CCR (Claude Code Router) should be enabled
   */
  shouldEnableCCR() {
    const ccrPaths = [
      join(homedir(), ".local", "bin", "ccr"),
      join(homedir(), ".cargo", "bin", "ccr"),
      "/usr/local/bin/ccr"
    ];
    return ccrPaths.some((path) => existsSync(path));
  }
  /**
   * Check if Cometix should be enabled
   */
  shouldEnableCometix() {
    const cometixPaths = [
      join(homedir(), ".local", "bin", "cometix"),
      join(homedir(), ".cargo", "bin", "cometix"),
      "/usr/local/bin/cometix"
    ];
    return cometixPaths.some((path) => existsSync(path));
  }
  /**
   * Check if CCUsage should be enabled
   */
  shouldEnableCCUsage() {
    const ccusagePaths = [
      join(homedir(), ".local", "bin", "ccusage"),
      join(homedir(), ".cargo", "bin", "ccusage"),
      "/usr/local/bin/ccusage"
    ];
    return ccusagePaths.some((path) => existsSync(path));
  }
  /**
   * Get recommended MCP services based on environment + project context
   */
  getRecommendedMcpServices(platform, project) {
    return ["context7"];
  }
  /**
   * Get recommended hook template IDs based on project toolchain
   */
  getRecommendedHooks(project) {
    const runtime = project.runtime;
    if (runtime.isCI) {
      const hooks2 = [];
      if (project.linter !== "none")
        hooks2.push("pre-commit-lint-check");
      if (project.testRunner !== "none")
        hooks2.push("test-before-commit");
      return hooks2;
    }
    if (runtime.isContainer) {
      const hooks2 = [];
      if (project.linter !== "none")
        hooks2.push("pre-commit-lint-check");
      if (project.testRunner !== "none")
        hooks2.push("test-before-commit");
      return hooks2;
    }
    const hooks = [];
    if (!runtime.isHeadless) {
      hooks.push("block-dev-server");
    }
    hooks.push("git-push-confirm");
    const jsLangs = ["typescript", "javascript"];
    if (jsLangs.includes(project.language)) {
      hooks.push("warn-console-log");
    }
    hooks.push("block-unwanted-docs");
    if (project.testRunner !== "none") {
      hooks.push("test-before-commit");
    }
    if (project.formatter !== "none") {
      hooks.push("auto-format-on-save");
    }
    if (project.linter !== "none") {
      hooks.push("pre-commit-lint-check");
    }
    return hooks;
  }
  /**
   * Get recommended skills based on user type
   */
  getRecommendedSkills(userType = "intermediate") {
    const core = [
      "ccjk:git-commit",
      "ccjk:init-project"
    ];
    if (userType === "beginner") {
      return [...core, "ccjk:workflow"];
    }
    if (userType === "intermediate") {
      return [...core, "ccjk:feat", "ccjk:workflow", "ccjk:git-worktree"];
    }
    if (userType === "advanced") {
      return [
        ...core,
        "ccjk:feat",
        "ccjk:workflow",
        "ccjk:git-worktree",
        "ccjk:git-rollback",
        "ccjk:git-cleanBranches"
      ];
    }
    return core;
  }
  /**
   * Validate detected defaults
   */
  validateDefaults(defaults) {
    const issues = [];
    if (defaults.apiKey) {
      if (defaults.apiKey.length < 10) {
        issues.push("API key appears too short to be valid");
      } else if (defaults.apiProvider === "anthropic" && !defaults.apiKey.startsWith("sk-ant-")) {
        issues.push("API key format appears invalid (should start with sk-ant-)");
      }
    }
    if (!["darwin", "linux", "win32"].includes(defaults.platform)) {
      issues.push(`Platform ${defaults.platform} may not be fully supported`);
    }
    if (!existsSync(defaults.homeDir)) {
      issues.push("Home directory is not accessible");
    }
    return {
      valid: issues.length === 0,
      issues
    };
  }
}
async function detectSmartDefaults() {
  const detector = new SmartDefaultsDetector();
  return detector.detect();
}
function detectCodeToolType() {
  return SmartDefaultsDetector.detectCodeToolType();
}

const smartDefaults = {
  __proto__: null,
  SmartDefaultsDetector: SmartDefaultsDetector,
  detectCodeToolType: detectCodeToolType,
  detectSmartDefaults: detectSmartDefaults
};

const CODE_TYPE_ABBREVIATIONS = {
  cc: "claude-code",
  mc: "clavue",
  mycode: "clavue",
  cx: "codex"
};
const STARTUP_CODE_TOOL_CHOICES = ["clavue", "claude-code", "codex"];
async function resolveCodeType(codeTypeParam) {
  if (codeTypeParam) {
    const normalizedParam = codeTypeParam.toLowerCase().trim();
    if (normalizedParam in CODE_TYPE_ABBREVIATIONS) {
      return CODE_TYPE_ABBREVIATIONS[normalizedParam];
    }
    if (normalizedParam in CODE_TOOL_ALIASES) {
      return CODE_TOOL_ALIASES[normalizedParam];
    }
    if (isValidCodeType(normalizedParam)) {
      return normalizedParam;
    }
    const validAbbreviations = Object.keys(CODE_TYPE_ABBREVIATIONS);
    const validFullTypes = Object.values(CODE_TYPE_ABBREVIATIONS);
    const validOptions = [...validAbbreviations, ...validFullTypes].join(", ");
    let defaultValue = DEFAULT_CODE_TOOL_TYPE;
    try {
      const config = await readZcfConfigAsync();
      if (config?.codeToolType && isValidCodeType(config.codeToolType)) {
        defaultValue = config.codeToolType;
      }
    } catch {
    }
    throw new Error(
      i18n.t("errors:invalidCodeType", { value: codeTypeParam, validOptions, defaultValue })
    );
  }
  const storedType = await getStoredCodeType();
  if (storedType) {
    return storedType;
  }
  try {
    const freshDetected = detectCodeToolType();
    if (isValidCodeType(freshDetected)) {
      return freshDetected;
    }
  } catch {
  }
  return DEFAULT_CODE_TOOL_TYPE;
}
function isValidCodeType(value) {
  return isCodeToolType(value);
}
async function getStoredCodeType() {
  try {
    const config = await readZcfConfigAsync();
    if (config?.codeToolType && isValidCodeType(config.codeToolType)) {
      return config.codeToolType;
    }
  } catch {
  }
  return null;
}
function persistCodeType(codeToolType) {
  updateZcfConfig({ codeToolType });
}
async function promptStartupCodeType() {
  const isZh = i18n.language === "zh-CN";
  const { codeToolType } = await inquirer.prompt({
    type: "list",
    name: "codeToolType",
    message: isZh ? "\u9009\u62E9\u4EE3\u7801\u5DE5\u5177" : "Choose your code tool",
    choices: STARTUP_CODE_TOOL_CHOICES.map((tool) => {
      if (tool === "clavue") {
        return {
          name: isZh ? `${tool} - Provider-first \u63A7\u5236\u4E2D\u5FC3\uFF08\u9ED8\u8BA4\u63A8\u8350\uFF09` : `${tool} - Provider-first control center (recommended default)`,
          value: tool
        };
      }
      if (tool === "claude-code") {
        return {
          name: isZh ? "Claude Code - Claude \u5BB6\u65CF\u7ECF\u5178\u63A7\u5236\u4E2D\u5FC3" : "Claude Code - Classic Claude-family control center",
          value: tool
        };
      }
      return {
        name: isZh ? "Codex - Codex \u4E13\u5C5E\u63A7\u5236\u4E2D\u5FC3\u3001Provider / MCP / Memory \u914D\u7F6E" : "Codex - Codex-specific control center for provider, MCP, and memory setup",
        value: tool
      };
    }),
    default: 0
  });
  persistCodeType(codeToolType);
  return codeToolType;
}
async function resolveStartupCodeType(options = {}) {
  if (options.codeTypeParam) {
    const resolvedType = await resolveCodeType(options.codeTypeParam);
    persistCodeType(resolvedType);
    return resolvedType;
  }
  const storedType = await getStoredCodeType();
  if (storedType) {
    return storedType;
  }
  if (options.interactive) {
    return await promptStartupCodeType();
  }
  return await resolveCodeType();
}

export { STARTUP_CODE_TOOL_CHOICES as S, resolveStartupCodeType as a, smartDefaults as b, detectSmartDefaults as d, parseOrchestrationLevel as p, resolveCodeType as r, scanProject as s, writeOrchestrationPolicy as w };
