#!/usr/bin/env node
import {
  Wizard
} from "../chunk-6G3KZSO4.js";
import "../chunk-52M2XF3W.js";
import "../chunk-SZRK3VOR.js";
import "../chunk-MKCHLXMY.js";
import "../chunk-EMIUPGPL.js";
import "../chunk-MMFQNJPE.js";
import "../chunk-HGTC76BX.js";
import "../chunk-SEJF7CGJ.js";
import "../chunk-TC3NHO34.js";
import "../chunk-K77I4XGL.js";
import "../chunk-KIWFEBKH.js";
import "../chunk-O6BA7Q2B.js";
import "../chunk-7SOPVGDV.js";
import "../chunk-SDKCQXWE.js";
import "../chunk-KUV24B5M.js";
import "../chunk-BMJZBLP7.js";
import "../chunk-X5EG4EFP.js";
import "../chunk-H7WJK7NJ.js";
import "../chunk-GG4BSB6S.js";
import "../chunk-TGLRDEEL.js";
import "../chunk-BKJHAJQW.js";
import "../chunk-CIG7IKX3.js";
import "../chunk-WYVDNGJB.js";
import "../chunk-MGNYPVOJ.js";
import "../chunk-BNQ5O6LE.js";
import "../chunk-52XO4ULK.js";
import "../chunk-WF6RM73R.js";
import "../chunk-XUDTFI4M.js";
import "../chunk-U3IGFMCY.js";
import {
  getAgentDefinitions,
  recompileAgents
} from "../chunk-YHCYKUA3.js";
import {
  ERROR_MESSAGES,
  INFO_MESSAGES,
  STATUS_MESSAGES
} from "../chunk-MR6OBL3B.js";
import {
  buildAndMergeConfig,
  claudePluginInstall,
  claudePluginUninstall,
  deleteLocalSkill,
  deriveInstallMode,
  detectInstallation,
  detectMigrations,
  discoverAllPluginSkills,
  executeMigration,
  getMarketplaceLabel,
  loadProjectConfig,
  loadSkillsMatrixFromSource,
  migrateLocalSkillScope,
  splitConfigByScope,
  writeConfigFile
} from "../chunk-TZXYBG3R.js";
import "../chunk-OCEFD7V6.js";
import "../chunk-T4EXUIBY.js";
import {
  BaseCommand,
  EXIT_CODES
} from "../chunk-VR3CDXDT.js";
import {
  disableBuffering,
  drainBuffer,
  enableBuffering,
  getErrorMessage,
  pushBufferMessage,
  verbose
} from "../chunk-LWXRUR6B.js";
import {
  ASCII_LOGO,
  CLAUDE_SRC_DIR,
  CLI_BIN_NAME,
  GLOBAL_INSTALL_ROOT,
  SOURCE_DISPLAY_NAMES,
  STANDARD_FILES
} from "../chunk-6OWHQ7HM.js";
import "../chunk-EC3UJRKZ.js";
import {
  init_esm_shims
} from "../chunk-DHET7RCE.js";

// src/cli/commands/edit.tsx
init_esm_shims();
import os from "os";
import path from "path";
import { Flags } from "@oclif/core";
import { render } from "ink";
import { jsx } from "react/jsx-runtime";
function formatSourceDisplayName(sourceName) {
  return SOURCE_DISPLAY_NAMES[sourceName] ?? sourceName;
}
var Edit = class _Edit extends BaseCommand {
  static summary = "Edit skills in the plugin";
  static description = "Modify the currently installed skills via interactive wizard";
  static examples = [
    {
      description: "Open the edit wizard",
      command: "<%= config.bin %> <%= command.id %>"
    },
    {
      description: "Edit with a custom source",
      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 sources",
      default: false
    }),
    "agent-source": Flags.string({
      description: "Remote agent partials source (default: local CLI)"
    })
  };
  async run() {
    const { flags } = await this.parse(_Edit);
    const installation = await detectInstallation();
    if (!installation) {
      this.error(ERROR_MESSAGES.NO_INSTALLATION, {
        exit: EXIT_CODES.ERROR
      });
    }
    const projectDir = installation.projectDir;
    enableBuffering();
    if (installation.projectDir === os.homedir()) {
      pushBufferMessage(
        "info",
        "No project installation found. Using global installation from ~/.claude-src/"
      );
    }
    let sourceResult;
    let startupMessages = [];
    try {
      sourceResult = await loadSkillsMatrixFromSource({
        sourceFlag: flags.source,
        projectDir,
        forceRefresh: flags.refresh
      });
      const sourceInfo = sourceResult.isLocal ? "local" : sourceResult.sourceConfig.sourceOrigin;
      pushBufferMessage(
        "info",
        `Loaded ${Object.keys(sourceResult.matrix.skills).length} skills (${sourceInfo})`
      );
    } catch (error) {
      disableBuffering();
      this.handleError(error);
    }
    const projectConfig = await loadProjectConfig(projectDir);
    let currentSkillIds;
    try {
      const discoveredSkills = await discoverAllPluginSkills(projectDir);
      currentSkillIds = Object.keys(discoveredSkills);
      if (currentSkillIds.length === 0 && projectConfig?.config?.skills?.length) {
        currentSkillIds = projectConfig.config.skills.map((s) => s.id);
        pushBufferMessage("info", `Found ${currentSkillIds.length} skills from project config`);
      } else {
        pushBufferMessage("info", `Current plugin has ${currentSkillIds.length} skills`);
      }
    } catch (error) {
      disableBuffering();
      this.handleError(error);
    }
    startupMessages = drainBuffer();
    disableBuffering();
    let wizardResult = null;
    const marketplaceLabel = getMarketplaceLabel(sourceResult);
    const isGlobalDir = projectDir === GLOBAL_INSTALL_ROOT;
    const lockedSkillIds = isGlobalDir ? void 0 : projectConfig?.config?.skills?.filter((s) => s.scope === "global").map((s) => s.id);
    const lockedAgentNames = isGlobalDir ? void 0 : projectConfig?.config?.agents?.filter((a) => a.scope === "global").map((a) => a.name);
    const { waitUntilExit } = render(
      /* @__PURE__ */ jsx(
        Wizard,
        {
          matrix: sourceResult.matrix,
          version: this.config.version,
          marketplaceLabel,
          logo: ASCII_LOGO,
          initialStep: "build",
          initialDomains: projectConfig?.config?.domains,
          initialAgents: projectConfig?.config?.selectedAgents,
          installedSkillIds: currentSkillIds,
          installedSkillConfigs: projectConfig?.config?.skills,
          lockedSkillIds,
          lockedAgentNames,
          projectDir,
          startupMessages,
          onComplete: (result2) => {
            wizardResult = result2;
          },
          onCancel: () => {
            this.log("\nEdit cancelled");
          }
        }
      )
    );
    await waitUntilExit();
    const result = wizardResult;
    if (!result || result.cancelled) {
      this.error("Cancelled", { exit: EXIT_CODES.CANCELLED });
    }
    if (!result.validation.valid) {
      const errorMessages = result.validation.errors.map((e) => e.message).join("\n  ");
      this.error(`Selection has validation errors:
  ${errorMessages}`, {
        exit: EXIT_CODES.ERROR
      });
    }
    const newSkillIds = result.skills.map((s) => s.id);
    const addedSkills = newSkillIds.filter((id) => !currentSkillIds.includes(id));
    const removedSkills = currentSkillIds.filter((id) => !newSkillIds.includes(id));
    const sourceChanges = /* @__PURE__ */ new Map();
    const scopeChanges = /* @__PURE__ */ new Map();
    if (projectConfig?.config?.skills) {
      for (const newSkill of result.skills) {
        const oldSkill = projectConfig.config.skills.find((s) => s.id === newSkill.id);
        if (oldSkill && oldSkill.source !== newSkill.source) {
          sourceChanges.set(newSkill.id, {
            from: oldSkill.source,
            to: newSkill.source
          });
        }
        if (oldSkill && oldSkill.scope !== newSkill.scope) {
          scopeChanges.set(newSkill.id, {
            from: oldSkill.scope,
            to: newSkill.scope
          });
        }
      }
    }
    const hasSourceChanges = sourceChanges.size > 0;
    const hasScopeChanges = scopeChanges.size > 0;
    const hasSkillChanges = addedSkills.length > 0 || removedSkills.length > 0;
    if (!hasSkillChanges && !hasSourceChanges && !hasScopeChanges) {
      this.log(INFO_MESSAGES.NO_CHANGES_MADE);
      this.log("Plugin unchanged\n");
      return;
    }
    this.log("\nChanges:");
    for (const skillId of addedSkills) {
      const skill = sourceResult.matrix.skills[skillId];
      this.log(`  + ${skill?.displayName || skillId}`);
    }
    for (const skillId of removedSkills) {
      const skill = sourceResult.matrix.skills[skillId];
      this.log(`  - ${skill?.displayName || skillId}`);
    }
    for (const [skillId, change] of sourceChanges) {
      const fromLabel = formatSourceDisplayName(change.from);
      const toLabel = formatSourceDisplayName(change.to);
      this.log(`  ~ ${skillId} (${fromLabel} \u2192 ${toLabel})`);
    }
    for (const [skillId, change] of scopeChanges) {
      const fromLabel = change.from === "global" ? "[G]" : "[P]";
      const toLabel = change.to === "global" ? "[G]" : "[P]";
      this.log(`  ~ ${skillId} (${fromLabel} \u2192 ${toLabel})`);
    }
    this.log("");
    const oldSkills = projectConfig?.config?.skills ?? [];
    const migrationPlan = detectMigrations(oldSkills, result.skills);
    const hasMigrations = migrationPlan.toLocal.length > 0 || migrationPlan.toPlugin.length > 0;
    if (hasMigrations) {
      if (migrationPlan.toLocal.length > 0) {
        this.log(`Switching ${migrationPlan.toLocal.length} skill(s) to local:`);
        for (const migration of migrationPlan.toLocal) {
          this.log(`  - ${migration.id}`);
        }
      }
      if (migrationPlan.toPlugin.length > 0) {
        this.log(`Switching ${migrationPlan.toPlugin.length} skill(s) to plugin:`);
        for (const migration of migrationPlan.toPlugin) {
          this.log(`  - ${migration.id}`);
        }
      }
      const migrationResult = await executeMigration(migrationPlan, projectDir, sourceResult);
      for (const warning of migrationResult.warnings) {
        this.warn(warning);
      }
    }
    const migratedSkillIds = /* @__PURE__ */ new Set([
      ...migrationPlan.toLocal.map((m) => m.id),
      ...migrationPlan.toPlugin.map((m) => m.id)
    ]);
    for (const [skillId, change] of scopeChanges) {
      const skillConfig = result.skills.find((s) => s.id === skillId);
      if (skillConfig?.source === "local") {
        await migrateLocalSkillScope(skillId, change.from, projectDir);
      } else if (sourceResult.marketplace && skillConfig) {
        const oldPluginScope = change.from === "global" ? "user" : "project";
        const newPluginScope = change.to === "global" ? "user" : "project";
        try {
          await claudePluginUninstall(skillId, oldPluginScope, projectDir);
          const pluginRef = `${skillId}@${sourceResult.marketplace}`;
          await claudePluginInstall(pluginRef, newPluginScope, projectDir);
        } catch (error) {
          this.warn(`Failed to migrate plugin scope for ${skillId}: ${getErrorMessage(error)}`);
        }
      }
    }
    for (const [skillId, change] of sourceChanges) {
      if (migratedSkillIds.has(skillId)) {
        continue;
      }
      if (change.from === "local") {
        await deleteLocalSkill(projectDir, skillId);
      }
    }
    if (sourceResult.marketplace) {
      for (const skillId of addedSkills) {
        const skillConfig = result.skills.find((s) => s.id === skillId);
        if (!skillConfig || skillConfig.source === "local") continue;
        const pluginRef = `${skillId}@${sourceResult.marketplace}`;
        const pluginScope = skillConfig.scope === "global" ? "user" : "project";
        this.log(`Installing plugin: ${pluginRef}...`);
        try {
          await claudePluginInstall(pluginRef, pluginScope, projectDir);
        } catch (error) {
          this.warn(`Failed to install plugin ${pluginRef}: ${getErrorMessage(error)}`);
        }
      }
      for (const skillId of removedSkills) {
        const oldSkill = projectConfig?.config?.skills?.find((s) => s.id === skillId);
        const pluginScope = oldSkill?.scope === "global" ? "user" : "project";
        this.log(`Uninstalling plugin: ${skillId}...`);
        try {
          await claudePluginUninstall(skillId, pluginScope, projectDir);
        } catch (error) {
          this.warn(`Failed to uninstall plugin ${skillId}: ${getErrorMessage(error)}`);
        }
      }
    }
    const isGlobalContext = projectDir === GLOBAL_INSTALL_ROOT;
    try {
      const mergeResult = await buildAndMergeConfig(result, sourceResult, projectDir, flags.source);
      if (isGlobalContext) {
        await writeConfigFile(mergeResult.config, installation.configPath);
        verbose(`Updated global config at ${installation.configPath}`);
      } else {
        const { global: globalConfig, project: projectSplitConfig } = splitConfigByScope(
          mergeResult.config
        );
        const globalConfigPath = path.join(
          GLOBAL_INSTALL_ROOT,
          CLAUDE_SRC_DIR,
          STANDARD_FILES.CONFIG_TS
        );
        await writeConfigFile(globalConfig, globalConfigPath);
        verbose(`Updated global config at ${globalConfigPath}`);
        await writeConfigFile(projectSplitConfig, installation.configPath, {
          isProjectConfig: true
        });
        verbose(`Updated project config at ${installation.configPath}`);
      }
    } catch (error) {
      this.warn(`Could not update config: ${getErrorMessage(error)}`);
    }
    let sourcePath;
    this.log(
      flags["agent-source"] ? STATUS_MESSAGES.FETCHING_AGENT_PARTIALS : STATUS_MESSAGES.LOADING_AGENT_PARTIALS
    );
    try {
      const agentDefs = await getAgentDefinitions(flags["agent-source"], {
        forceRefresh: flags.refresh
      });
      sourcePath = agentDefs.sourcePath;
      this.log(flags["agent-source"] ? "\u2713 Agent partials fetched\n" : "\u2713 Agent partials loaded\n");
    } catch (error) {
      this.handleError(error);
    }
    this.log(STATUS_MESSAGES.RECOMPILING_AGENTS);
    try {
      const recompileSkills = await discoverAllPluginSkills(projectDir);
      const recompileResult = await recompileAgents({
        pluginDir: projectDir,
        sourcePath,
        skills: recompileSkills,
        projectDir,
        outputDir: installation.agentsDir,
        installMode: deriveInstallMode(result.skills)
      });
      if (recompileResult.failed.length > 0) {
        this.log(
          `\u2713 Recompiled ${recompileResult.compiled.length} agents (${recompileResult.failed.length} failed)
`
        );
        for (const warning of recompileResult.warnings) {
          this.warn(warning);
        }
      } else if (recompileResult.compiled.length > 0) {
        this.log(`\u2713 Recompiled ${recompileResult.compiled.length} agents
`);
      } else {
        this.log("\u2713 No agents to recompile\n");
      }
    } catch (error) {
      this.warn(`Agent recompilation failed: ${getErrorMessage(error)}`);
      this.log(`You can manually recompile with '${CLI_BIN_NAME} compile'.
`);
    }
    const summaryParts = [`${addedSkills.length} added`, `${removedSkills.length} removed`];
    if (hasSourceChanges) {
      summaryParts.push(`${sourceChanges.size} source${sourceChanges.size > 1 ? "s" : ""} changed`);
    }
    if (hasScopeChanges) {
      summaryParts.push(`${scopeChanges.size} scope${scopeChanges.size > 1 ? "s" : ""} changed`);
    }
    this.log(`
\u2713 Plugin updated! (${summaryParts.join(", ")})
`);
  }
};
export {
  Edit as default
};
//# sourceMappingURL=edit.js.map