#!/usr/bin/env node
import {
  Wizard
} from "../chunk-XTRPYUWK.js";
import "../chunk-OEJDFGAF.js";
import "../chunk-MVEYK55V.js";
import "../chunk-JZHIF3K7.js";
import "../chunk-HPJP3HFD.js";
import "../chunk-FMQ3A7W4.js";
import "../chunk-QR2TM4OY.js";
import "../chunk-YTRFL3MR.js";
import "../chunk-VAQJLHUW.js";
import "../chunk-K77I4XGL.js";
import "../chunk-DVW6ASTO.js";
import "../chunk-KQ27IDYL.js";
import "../chunk-ZWAL2ZY7.js";
import "../chunk-FXQYEXLS.js";
import "../chunk-7SOPVGDV.js";
import "../chunk-VSZ5GDET.js";
import "../chunk-KUV24B5M.js";
import "../chunk-3APMMQUA.js";
import "../chunk-GG4BSB6S.js";
import "../chunk-HLTJK3XB.js";
import "../chunk-NRCKIHND.js";
import "../chunk-M4P5YJ45.js";
import "../chunk-B4QYXVPZ.js";
import "../chunk-N5OCAAXY.js";
import "../chunk-U3IGFMCY.js";
import {
  claudePluginInstall,
  claudePluginMarketplaceAdd,
  claudePluginMarketplaceExists
} from "../chunk-CJFWO46A.js";
import "../chunk-SPSGZWTZ.js";
import "../chunk-INKJBMPJ.js";
import {
  DRY_RUN_MESSAGES,
  INFO_MESSAGES,
  STATUS_MESSAGES,
  SUCCESS_MESSAGES
} from "../chunk-2RQYJFKA.js";
import {
  BaseCommand,
  EXIT_CODES
} from "../chunk-LNA6M2IE.js";
import {
  detectInstallation,
  getMarketplaceLabel,
  hasIndividualPlugins,
  installLocal,
  installPluginConfig,
  loadSkillsMatrixFromSource
} from "../chunk-GFDGYQ6M.js";
import "../chunk-T4EXUIBY.js";
import {
  fileExists,
  getErrorMessage,
  readFileSafe,
  settingsFileSchema,
  warn,
  warnUnknownFields
} from "../chunk-C4QI54PN.js";
import {
  ASCII_LOGO,
  CLAUDE_DIR,
  CLI_BIN_NAME,
  CLI_COLORS,
  DEFAULT_BRANDING,
  LOCAL_SKILLS_PATH,
  MAX_CONFIG_FILE_SIZE
} from "../chunk-FTD5Z6QD.js";
import {
  init_esm_shims
} from "../chunk-DHET7RCE.js";

// src/cli/commands/init.tsx
init_esm_shims();
import { Flags } from "@oclif/core";
import { render } from "ink";
import path2 from "path";

// src/cli/lib/permission-checker.tsx
init_esm_shims();
import { Text, Box } from "ink";
import path from "path";
import { jsx, jsxs } from "react/jsx-runtime";
async function checkPermissions(projectRoot) {
  const settingsPath = path.join(projectRoot, CLAUDE_DIR, "settings.json");
  const localSettingsPath = path.join(projectRoot, CLAUDE_DIR, "settings.local.json");
  let permissions;
  for (const filePath of [localSettingsPath, settingsPath]) {
    if (await fileExists(filePath)) {
      try {
        const content = await readFileSafe(filePath, MAX_CONFIG_FILE_SIZE);
        const raw = JSON.parse(content);
        if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
          const EXPECTED_SETTINGS_KEYS = [
            "permissions",
            "enabledPlugins",
            "env",
            "allowedTools",
            "customInstructions",
            "defaultModel"
          ];
          warnUnknownFields(
            raw,
            EXPECTED_SETTINGS_KEYS,
            `settings file '${filePath}'`
          );
        }
        const result = settingsFileSchema.safeParse(raw);
        const parsed = result.success ? result.data : {};
        if (parsed.permissions) {
          permissions = parsed.permissions;
          break;
        }
      } catch {
        warn(`Malformed settings file at '${filePath}' \u2014 skipping`);
      }
    }
  }
  if (!permissions) {
    return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: CLI_COLORS.WARNING, padding: 1, children: [
      /* @__PURE__ */ jsx(Text, { bold: true, color: CLI_COLORS.WARNING, children: "Permission Notice" }),
      /* @__PURE__ */ jsx(Text, { children: "No permissions configured in .claude/settings.json" }),
      /* @__PURE__ */ jsx(Text, { children: "Agents will prompt for approval on each tool use." }),
      /* @__PURE__ */ jsx(Text, { children: " " }),
      /* @__PURE__ */ jsx(Text, { children: "For autonomous operation, add to .claude/settings.json:" }),
      /* @__PURE__ */ jsx(Text, { children: " " }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: "{" }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: '  "permissions": {' }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: '    "allow": [' }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: '      "Read(*)",' }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: '      "Bash(git *)",' }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: '      "Bash(bun *)"' }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: "    ]" }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: "  }" }),
      /* @__PURE__ */ jsx(Text, { color: "dim", children: "}" })
    ] });
  }
  const hasRestrictiveBash = permissions.deny?.some(
    (rule) => rule === "Bash(*)" || rule === "Bash"
  );
  const hasNoAllows = !permissions.allow || permissions.allow.length === 0;
  if (hasRestrictiveBash || hasNoAllows) {
    return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: CLI_COLORS.WARNING, padding: 1, children: [
      /* @__PURE__ */ jsx(Text, { bold: true, color: CLI_COLORS.WARNING, children: "Permission Warnings" }),
      hasRestrictiveBash && /* @__PURE__ */ jsx(Text, { children: "\u26A0 Bash is denied in permissions. Some agents require Bash for git, testing, and build commands." }),
      hasNoAllows && /* @__PURE__ */ jsx(Text, { children: "\u26A0 No allow rules configured. Agents will prompt for each tool use." })
    ] });
  }
  return null;
}

// src/cli/commands/init.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var Init = class _Init extends BaseCommand {
  static summary = `Initialize ${DEFAULT_BRANDING.NAME} in this project`;
  static description = "Interactive wizard to set up skills and agents. Supports Plugin Mode (native install) and Local Mode (copy to .claude/).";
  static examples = [
    {
      description: "Start the setup wizard",
      command: "<%= config.bin %> <%= command.id %>"
    },
    {
      description: "Initialize from a custom marketplace",
      command: "<%= config.bin %> <%= command.id %> --source github:org/marketplace"
    },
    {
      description: "Preview without creating files",
      command: "<%= config.bin %> <%= command.id %> --dry-run"
    },
    {
      description: "Force refresh skills from remote",
      command: "<%= config.bin %> <%= command.id %> --refresh"
    }
  ];
  static flags = {
    ...BaseCommand.baseFlags,
    refresh: Flags.boolean({
      description: "Force refresh from remote source",
      default: false
    })
  };
  async run() {
    const { flags } = await this.parse(_Init);
    const projectDir = process.cwd();
    if (flags["dry-run"]) {
      this.log(`${DRY_RUN_MESSAGES.PREVIEW_NO_FILES_CREATED}
`);
    }
    const individualPluginsExist = await hasIndividualPlugins(projectDir);
    const existingInstallation = await detectInstallation(projectDir);
    if (individualPluginsExist || existingInstallation) {
      const location = individualPluginsExist ? `.claude/settings.json` : existingInstallation?.configPath ?? projectDir;
      this.warn(`${DEFAULT_BRANDING.NAME} is already initialized at ${location}`);
      this.log(`Use '${CLI_BIN_NAME} edit' to modify skills.`);
      this.log(INFO_MESSAGES.NO_CHANGES_MADE);
      return;
    }
    let sourceResult;
    try {
      sourceResult = await loadSkillsMatrixFromSource({
        sourceFlag: flags.source,
        projectDir,
        forceRefresh: flags.refresh
      });
    } catch (error) {
      this.error(getErrorMessage(error), {
        exit: EXIT_CODES.ERROR
      });
    }
    let wizardResult = null;
    const marketplaceLabel = getMarketplaceLabel(sourceResult);
    const { waitUntilExit } = render(
      /* @__PURE__ */ jsx2(
        Wizard,
        {
          matrix: sourceResult.matrix,
          version: this.config.version,
          marketplaceLabel,
          logo: ASCII_LOGO,
          projectDir: process.cwd(),
          initialInstallMode: sourceResult.marketplace ? "plugin" : "local",
          initialExpertMode: !!flags.source,
          onComplete: (result2) => {
            wizardResult = result2;
          },
          onCancel: () => {
            this.log("Setup cancelled");
          }
        }
      )
    );
    await waitUntilExit();
    const result = wizardResult;
    if (!result || result.cancelled) {
      this.exit(EXIT_CODES.CANCELLED);
    }
    if (result.selectedSkills.length === 0) {
      this.error("No skills selected", { exit: EXIT_CODES.ERROR });
    }
    await this.handleInstallation(result, sourceResult, flags);
  }
  async handleInstallation(result, sourceResult, flags) {
    const projectDir = process.cwd();
    const dryRun = flags["dry-run"];
    this.log("\n");
    this.log(`Selected ${result.selectedSkills.length} skills`);
    this.log(
      `Install mode: ${result.installMode === "plugin" ? "Plugin (native install)" : "Local (copy to .claude/skills/)"}`
    );
    if (dryRun) {
      if (result.installMode === "plugin" && result.selectedStackId) {
        const useMarketplace = !!sourceResult.marketplace;
        if (useMarketplace) {
          this.log(
            `[dry-run] Would install stack "${result.selectedStackId}" from marketplace "${sourceResult.marketplace}"`
          );
          this.log(
            `[dry-run]   claude plugin install ${result.selectedStackId}@${sourceResult.marketplace} --scope project`
          );
        } else {
          this.log(
            `[dry-run] Would compile and install stack "${result.selectedStackId}" as a native plugin`
          );
          this.log(
            `[dry-run]   claude plugin install ./compiled-stack/${result.selectedStackId} --scope project`
          );
          this.log(
            `[dry-run] Stack includes ${result.selectedSkills.length} skills and agents bundled together`
          );
        }
      } else if (result.installMode === "plugin" && sourceResult.marketplace) {
        this.log(
          `[dry-run] Would install ${result.selectedSkills.length} skills as individual plugins from "${sourceResult.marketplace}"`
        );
        for (const skillId of result.selectedSkills) {
          this.log(
            `[dry-run]   claude plugin install ${skillId}@${sourceResult.marketplace} --scope project`
          );
        }
        const localAgentsDir = path2.join(projectDir, CLAUDE_DIR, "agents");
        this.log(`[dry-run] Would compile agents to ${localAgentsDir}`);
        this.log(`[dry-run] Would save config to .claude-src/config.yaml`);
      } else {
        if (result.installMode === "plugin") {
          this.log(
            `[dry-run] Plugin Mode requires a marketplace for individual skills \u2014 would fall back to Local Mode`
          );
        }
        const localSkillsDir = path2.join(projectDir, LOCAL_SKILLS_PATH);
        const localAgentsDir = path2.join(projectDir, CLAUDE_DIR, "agents");
        this.log(
          `[dry-run] Would copy ${result.selectedSkills.length} skills to ${localSkillsDir}`
        );
        this.log(`[dry-run] Would compile agents to ${localAgentsDir}`);
        this.log(`[dry-run] Would save config to .claude-src/config.yaml`);
      }
      this.log(`
${DRY_RUN_MESSAGES.COMPLETE_NO_FILES_CREATED}`);
      return;
    }
    if (result.installMode === "plugin") {
      if (sourceResult.marketplace) {
        await this.installIndividualPlugins(result, sourceResult, flags);
      } else {
        this.warn("Plugin Mode requires a marketplace for individual skill installation.");
        this.log(`Falling back to Local Mode (copying to .claude/skills/)...`);
        this.log("To use Plugin Mode, either select a stack or configure a marketplace source.\n");
        await this.installLocalMode(result, sourceResult, flags);
      }
      return;
    }
    await this.installLocalMode(result, sourceResult, flags);
  }
  async installIndividualPlugins(result, sourceResult, flags) {
    const projectDir = process.cwd();
    if (sourceResult.marketplace) {
      const marketplaceExists = await claudePluginMarketplaceExists(sourceResult.marketplace);
      if (!marketplaceExists) {
        this.log(`Registering marketplace "${sourceResult.marketplace}"...`);
        try {
          const marketplaceSource = sourceResult.sourceConfig.source.replace(/^github:/, "");
          await claudePluginMarketplaceAdd(marketplaceSource);
          this.log(`Registered marketplace: ${sourceResult.marketplace}`);
        } catch (error) {
          this.error(getErrorMessage(error), {
            exit: EXIT_CODES.ERROR
          });
        }
      }
    }
    this.log("Installing skill plugins...");
    for (const skillId of result.selectedSkills) {
      const pluginRef = `${skillId}@${sourceResult.marketplace}`;
      try {
        await claudePluginInstall(pluginRef, "project", projectDir);
        this.log(`  Installed ${pluginRef}`);
      } catch (error) {
        this.error(`Failed to install plugin ${pluginRef}: ${getErrorMessage(error)}`, {
          exit: EXIT_CODES.ERROR
        });
      }
    }
    this.log(`Installed ${result.selectedSkills.length} skill plugins
`);
    this.log("Generating configuration...");
    try {
      const configResult = await installPluginConfig({
        wizardResult: result,
        sourceResult,
        projectDir,
        sourceFlag: flags.source
      });
      if (configResult.wasMerged) {
        this.log(`Merged with existing config at ${configResult.mergedConfigPath}`);
      }
      this.log(`Configuration saved (${configResult.config.agents.length} agents)
`);
      this.log(STATUS_MESSAGES.COMPILING_AGENTS);
      this.log(`Compiled ${configResult.compiledAgents.length} agents to .claude/agents/
`);
      this.log(`${SUCCESS_MESSAGES.INIT_SUCCESS}
`);
      this.log("Agents compiled to:");
      this.log(`  ${configResult.agentsDir}`);
      for (const agentName of configResult.compiledAgents) {
        this.log(`    ${agentName}.md`);
      }
      this.log("");
      this.log("Configuration:");
      this.log(`  ${configResult.configPath}`);
      this.log("");
      this.log("To customize agent-skill assignments:");
      this.log(`  1. Edit .claude-src/config.yaml`);
      this.log(`  2. Run '${CLI_BIN_NAME} compile' to regenerate agents`);
      this.log("");
      const permissionWarning = await checkPermissions(projectDir);
      if (permissionWarning) {
        const { waitUntilExit } = render(permissionWarning);
        await waitUntilExit();
      }
    } catch (error) {
      this.handleError(error);
    }
  }
  async installLocalMode(result, sourceResult, flags) {
    const projectDir = process.cwd();
    const matrix = sourceResult.matrix;
    this.log("Copying skills to local directory...");
    try {
      const installResult = await installLocal({
        wizardResult: result,
        sourceResult,
        projectDir,
        sourceFlag: flags.source
      });
      this.log(`Copied ${installResult.copiedSkills.length} skills to .claude/skills/
`);
      this.log("Generating configuration...");
      if (installResult.wasMerged) {
        this.log(`Merged with existing config at ${installResult.mergedConfigPath}`);
      }
      this.log(`Configuration saved (${installResult.config.agents.length} agents)
`);
      this.log(STATUS_MESSAGES.COMPILING_AGENTS);
      this.log(`Compiled ${installResult.compiledAgents.length} agents to .claude/agents/
`);
      this.log(`${SUCCESS_MESSAGES.INIT_SUCCESS}
`);
      this.log("Skills copied to:");
      this.log(`  ${installResult.skillsDir}`);
      for (const copiedSkill of installResult.copiedSkills) {
        const skill = matrix.skills[copiedSkill.skillId];
        const displayName = skill?.displayName || copiedSkill.skillId;
        this.log(`    ${displayName}/`);
      }
      this.log("");
      this.log("Agents compiled to:");
      this.log(`  ${installResult.agentsDir}`);
      for (const agentName of installResult.compiledAgents) {
        this.log(`    ${agentName}.md`);
      }
      this.log("");
      this.log("Configuration:");
      this.log(`  ${installResult.configPath}`);
      this.log("");
      this.log("To customize agent-skill assignments:");
      this.log(`  1. Edit .claude-src/config.yaml`);
      this.log(`  2. Run '${CLI_BIN_NAME} compile' to regenerate agents`);
      this.log("");
      const permissionWarning = await checkPermissions(projectDir);
      if (permissionWarning) {
        const { waitUntilExit } = render(permissionWarning);
        await waitUntilExit();
      }
    } catch (error) {
      this.handleError(error);
    }
  }
};
export {
  Init as default
};
//# sourceMappingURL=init.js.map