#!/usr/bin/env node
import {
  Wizard
} from "./chunk-6G3KZSO4.js";
import {
  STATUS_MESSAGES,
  SUCCESS_MESSAGES
} from "./chunk-MR6OBL3B.js";
import {
  claudePluginInstall,
  claudePluginMarketplaceAdd,
  claudePluginMarketplaceExists,
  deriveInstallMode,
  detectGlobalInstallation,
  detectProjectInstallation,
  ensureBlankGlobalConfig,
  getInstallationInfo,
  getMarketplaceLabel,
  hasIndividualPlugins,
  installLocal,
  installPluginConfig,
  loadProjectConfig,
  loadSkillsMatrixFromSource
} from "./chunk-TZXYBG3R.js";
import {
  BaseCommand,
  EXIT_CODES
} from "./chunk-VR3CDXDT.js";
import {
  disableBuffering,
  drainBuffer,
  enableBuffering,
  fileExists,
  getErrorMessage,
  readFileSafe,
  settingsFileSchema,
  warn,
  warnUnknownFields
} from "./chunk-LWXRUR6B.js";
import {
  ASCII_LOGO,
  CLAUDE_DIR,
  CLAUDE_SRC_DIR,
  CLI_BIN_NAME,
  CLI_COLORS,
  DEFAULT_BRANDING,
  GLOBAL_INSTALL_ROOT,
  MAX_CONFIG_FILE_SIZE
} from "./chunk-6OWHQ7HM.js";
import {
  init_esm_shims
} from "./chunk-DHET7RCE.js";

// src/cli/commands/init.tsx
init_esm_shims();
import { useState } from "react";
import { Flags } from "@oclif/core";
import { render, Box as Box2, Text as Text2, useApp, useInput } from "ink";
import os from "os";
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, jsxs as jsxs2 } from "react/jsx-runtime";
var DASHBOARD_OPTIONS = [
  { label: "Edit", command: "edit" },
  { label: "Compile", command: "compile" },
  { label: "Doctor", command: "doctor" },
  { label: "List", command: "list" }
];
var Dashboard = ({
  skillCount,
  agentCount,
  source,
  mode,
  onSelect,
  onCancel
}) => {
  const { exit } = useApp();
  const [focusIndex, setFocusIndex] = useState(0);
  useInput((_input, key) => {
    if (key.escape) {
      onCancel();
      exit();
      return;
    }
    if (key.return) {
      onSelect(DASHBOARD_OPTIONS[focusIndex].command);
      exit();
      return;
    }
    if (key.leftArrow) {
      setFocusIndex((i) => i > 0 ? i - 1 : DASHBOARD_OPTIONS.length - 1);
    }
    if (key.rightArrow) {
      setFocusIndex((i) => i < DASHBOARD_OPTIONS.length - 1 ? i + 1 : 0);
    }
  });
  return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx2(Text2, { bold: true, children: DEFAULT_BRANDING.NAME }),
    /* @__PURE__ */ jsx2(Text2, { children: " " }),
    /* @__PURE__ */ jsxs2(Text2, { children: [
      " Skills: ",
      skillCount,
      " installed"
    ] }),
    /* @__PURE__ */ jsxs2(Text2, { children: [
      " Agents: ",
      agentCount,
      " compiled"
    ] }),
    /* @__PURE__ */ jsxs2(Text2, { children: [
      " Mode: ",
      mode === "plugin" ? "Plugin" : "Local"
    ] }),
    source && /* @__PURE__ */ jsxs2(Text2, { children: [
      " Source: ",
      source
    ] }),
    /* @__PURE__ */ jsx2(Text2, { children: " " }),
    /* @__PURE__ */ jsxs2(Box2, { children: [
      /* @__PURE__ */ jsx2(Text2, { children: " " }),
      DASHBOARD_OPTIONS.map((option, index) => /* @__PURE__ */ jsx2(Box2, { marginRight: 1, children: /* @__PURE__ */ jsxs2(
        Text2,
        {
          color: index === focusIndex ? CLI_COLORS.FOCUS : void 0,
          bold: index === focusIndex,
          children: [
            "[",
            option.label,
            "]"
          ]
        }
      ) }, option.command))
    ] }),
    /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: " Use arrow keys to select, Enter to confirm, Esc to exit" })
  ] });
};
var GLOBAL_CONFIG_OPTIONS = [
  { label: "Edit global installation", choice: "edit-global" },
  { label: "Create new project installation", choice: "create-project" }
];
var GlobalConfigPrompt = ({
  globalConfigDir,
  onSelect,
  onCancel
}) => {
  const { exit } = useApp();
  const [focusIndex, setFocusIndex] = useState(0);
  useInput((_input, key) => {
    if (key.escape) {
      onCancel();
      exit();
      return;
    }
    if (key.return) {
      onSelect(GLOBAL_CONFIG_OPTIONS[focusIndex].choice);
      exit();
      return;
    }
    if (key.leftArrow) {
      setFocusIndex((i) => i > 0 ? i - 1 : GLOBAL_CONFIG_OPTIONS.length - 1);
    }
    if (key.rightArrow) {
      setFocusIndex((i) => i < GLOBAL_CONFIG_OPTIONS.length - 1 ? i + 1 : 0);
    }
  });
  return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", children: [
    /* @__PURE__ */ jsxs2(Text2, { children: [
      "A global installation was found at ",
      globalConfigDir
    ] }),
    /* @__PURE__ */ jsx2(Text2, { children: "What would you like to do?" }),
    /* @__PURE__ */ jsx2(Text2, { children: " " }),
    /* @__PURE__ */ jsxs2(Box2, { children: [
      /* @__PURE__ */ jsx2(Text2, { children: " " }),
      GLOBAL_CONFIG_OPTIONS.map((option, index) => /* @__PURE__ */ jsx2(Box2, { marginRight: 1, children: /* @__PURE__ */ jsxs2(
        Text2,
        {
          color: index === focusIndex ? CLI_COLORS.FOCUS : void 0,
          bold: index === focusIndex,
          children: [
            "[",
            option.label,
            "]"
          ]
        }
      ) }, option.choice))
    ] }),
    /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: " Use arrow keys to select, Enter to confirm, Esc to exit" })
  ] });
};
async function getDashboardData(projectDir) {
  const [info, loaded] = await Promise.all([getInstallationInfo(), loadProjectConfig(projectDir)]);
  const skillCount = loaded?.config?.skills?.length ?? 0;
  const agentCount = info?.agentCount ?? 0;
  const mode = info?.mode ?? (loaded?.config?.skills ? deriveInstallMode(loaded.config.skills) : "local");
  const source = loaded?.config?.source;
  return { skillCount, agentCount, mode, source };
}
function formatDashboardText(data) {
  const modeLabel = data.mode === "plugin" ? "Plugin" : "Local";
  const lines = [
    DEFAULT_BRANDING.NAME,
    "",
    `  Skills:  ${data.skillCount} installed`,
    `  Agents:  ${data.agentCount} compiled`,
    `  Mode:    ${modeLabel}`
  ];
  if (data.source) {
    lines.push(`  Source:  ${data.source}`);
  }
  lines.push("");
  lines.push(`  [Edit]  [Compile]  [Doctor]  [List]`);
  return lines.join("\n");
}
async function showDashboard(projectDir, log) {
  const data = await getDashboardData(projectDir);
  if (!process.stdin.isTTY) {
    const output = log ?? console.log;
    output(formatDashboardText(data));
    return null;
  }
  let selectedCommand = null;
  const { waitUntilExit } = render(
    /* @__PURE__ */ jsx2(
      Dashboard,
      {
        skillCount: data.skillCount,
        agentCount: data.agentCount,
        source: data.source,
        mode: data.mode,
        onSelect: (command) => {
          selectedCommand = command;
        },
        onCancel: () => {
          selectedCommand = null;
        }
      }
    )
  );
  await waitUntilExit();
  return selectedCommand;
}
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: "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();
    const individualPluginsExist = await hasIndividualPlugins(projectDir);
    const existingInstallation = await detectProjectInstallation(projectDir);
    if (individualPluginsExist || existingInstallation) {
      const selectedCommand = await showDashboard(projectDir, (msg) => this.log(msg));
      if (selectedCommand) {
        await this.config.runCommand(selectedCommand);
      }
      return;
    }
    const globalInstallation = await detectGlobalInstallation();
    if (globalInstallation) {
      const globalConfigDir = path2.join(os.homedir(), CLAUDE_SRC_DIR);
      if (process.stdin.isTTY) {
        let globalChoice = null;
        const { waitUntilExit: waitForPrompt } = render(
          /* @__PURE__ */ jsx2(
            GlobalConfigPrompt,
            {
              globalConfigDir,
              onSelect: (choice) => {
                globalChoice = choice;
              },
              onCancel: () => {
                globalChoice = null;
              }
            }
          )
        );
        await waitForPrompt();
        if (globalChoice === "edit-global") {
          const selectedCommand = await showDashboard(os.homedir(), (msg) => this.log(msg));
          if (selectedCommand) {
            await this.config.runCommand(selectedCommand);
          }
          return;
        }
        if (globalChoice === null) {
          return;
        }
      }
    }
    if (projectDir !== GLOBAL_INSTALL_ROOT) {
      const created = await ensureBlankGlobalConfig();
      if (created) {
        this.log("Created blank global config at ~/" + CLAUDE_SRC_DIR);
      }
    }
    enableBuffering();
    let sourceResult;
    let startupMessages = [];
    try {
      sourceResult = await loadSkillsMatrixFromSource({
        sourceFlag: flags.source,
        projectDir,
        forceRefresh: flags.refresh
      });
    } catch (error) {
      disableBuffering();
      this.error(getErrorMessage(error), {
        exit: EXIT_CODES.ERROR
      });
    }
    startupMessages = drainBuffer();
    disableBuffering();
    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,
          startupMessages,
          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.skills.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 installMode = deriveInstallMode(result.skills);
    this.log("\n");
    this.log(`Selected ${result.skills.length} skills`);
    this.log(
      `Install mode: ${installMode === "plugin" ? "Plugin (native install)" : "Local (copy to .claude/skills/)"}`
    );
    if (installMode === "plugin") {
      if (sourceResult.marketplace) {
        await this.installIndividualPlugins(result, sourceResult, flags, projectDir);
      } 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, projectDir);
      }
      return;
    }
    await this.installLocalMode(result, sourceResult, flags, projectDir);
  }
  async installIndividualPlugins(result, sourceResult, flags, projectDir) {
    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 skill of result.skills.filter((s) => s.source !== "local")) {
      const pluginRef = `${skill.id}@${sourceResult.marketplace}`;
      const pluginScope = skill.scope === "global" ? "user" : "project";
      try {
        await claudePluginInstall(pluginRef, pluginScope, projectDir);
        this.log(`  Installed ${pluginRef}`);
      } catch (error) {
        this.error(`Failed to install plugin ${pluginRef}: ${getErrorMessage(error)}`, {
          exit: EXIT_CODES.ERROR
        });
      }
    }
    const pluginSkillCount = result.skills.filter((s) => s.source !== "local").length;
    this.log(`Installed ${pluginSkillCount} 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.ts`);
      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, projectDir) {
    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.ts`);
      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 {
  getDashboardData,
  formatDashboardText,
  showDashboard,
  Init
};
//# sourceMappingURL=chunk-G6WHCALR.js.map