#!/usr/bin/env node
import {
  getAgentDefinitions,
  recompileAgents
} from "../chunk-SYGEV3KV.js";
import {
  Wizard
} from "../chunk-Q5BSIARS.js";
import "../chunk-DAVOSI4M.js";
import "../chunk-3S4GIO4B.js";
import "../chunk-ELRGSZHZ.js";
import "../chunk-KVHLKPYB.js";
import "../chunk-VTDEENSP.js";
import "../chunk-ENWMWIHP.js";
import "../chunk-WWSKP5SR.js";
import "../chunk-KCYNTAAF.js";
import "../chunk-K77I4XGL.js";
import "../chunk-M3AGB4TR.js";
import "../chunk-YRVTXSXP.js";
import "../chunk-NTPHCNJO.js";
import "../chunk-YQFU2KZ5.js";
import "../chunk-7SOPVGDV.js";
import "../chunk-F3O5YHSI.js";
import "../chunk-KUV24B5M.js";
import "../chunk-ABE55TEU.js";
import "../chunk-GG4BSB6S.js";
import "../chunk-5BDYODWP.js";
import "../chunk-GUIRWCKI.js";
import "../chunk-KWWLPPHF.js";
import "../chunk-OALQWRLG.js";
import "../chunk-HKRLWERR.js";
import "../chunk-U3IGFMCY.js";
import {
  claudePluginInstall,
  claudePluginUninstall
} from "../chunk-CLHBKFHU.js";
import "../chunk-FYNMNY4P.js";
import "../chunk-KZNPPUQG.js";
import {
  ERROR_MESSAGES,
  INFO_MESSAGES,
  STATUS_MESSAGES
} from "../chunk-V43QDMYQ.js";
import {
  BaseCommand,
  EXIT_CODES
} from "../chunk-SRFNNOLC.js";
import {
  archiveLocalSkill,
  detectInstallation,
  discoverAllPluginSkills,
  getMarketplaceLabel,
  loadProjectConfig,
  loadSkillsMatrixFromSource,
  restoreArchivedSkill
} from "../chunk-ZECXM7LP.js";
import {
  typedEntries
} from "../chunk-T4EXUIBY.js";
import {
  getErrorMessage
} from "../chunk-473YHDYQ.js";
import {
  ASCII_LOGO,
  CLI_BIN_NAME
} from "../chunk-FVN5PFFY.js";
import {
  init_esm_shims
} from "../chunk-DHET7RCE.js";

// src/cli/commands/edit.tsx
init_esm_shims();
import { Flags } from "@oclif/core";
import { render } from "ink";
import { jsx } from "react/jsx-runtime";
var SOURCE_DISPLAY_NAMES = {
  public: "Public",
  local: "Local"
};
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 = process.cwd();
    const isPluginMode = installation.mode === "plugin";
    const modeLabel = installation.mode === "local" ? "Local" : "Plugin";
    this.log(`Edit ${modeLabel} Skills
`);
    this.log(STATUS_MESSAGES.LOADING_MARKETPLACE_SOURCE);
    let sourceResult;
    try {
      sourceResult = await loadSkillsMatrixFromSource({
        sourceFlag: flags.source,
        projectDir,
        forceRefresh: flags.refresh
      });
      const sourceInfo = sourceResult.isLocal ? "local" : sourceResult.sourceConfig.sourceOrigin;
      this.log(
        `\u2713 Loaded ${Object.keys(sourceResult.matrix.skills).length} skills (${sourceInfo})
`
      );
    } catch (error) {
      this.handleError(error);
    }
    const projectConfig = await loadProjectConfig(projectDir);
    this.log("Reading current skills...");
    let currentSkillIds;
    try {
      const discoveredSkills = await discoverAllPluginSkills(projectDir);
      currentSkillIds = Object.keys(discoveredSkills);
      if (currentSkillIds.length === 0 && projectConfig?.config?.skills?.length) {
        currentSkillIds = projectConfig.config.skills;
        this.log(`\u2713 Found ${currentSkillIds.length} skills from project config
`);
      } else {
        this.log(`\u2713 Current plugin has ${currentSkillIds.length} skills
`);
      }
    } catch (error) {
      this.handleError(error);
    }
    let wizardResult = null;
    const marketplaceLabel = getMarketplaceLabel(sourceResult);
    const savedInstallMode = projectConfig?.config?.installMode;
    const initialInstallMode = savedInstallMode ?? (sourceResult.marketplace ? "plugin" : "local");
    const { waitUntilExit } = render(
      /* @__PURE__ */ jsx(
        Wizard,
        {
          matrix: sourceResult.matrix,
          version: this.config.version,
          marketplaceLabel,
          logo: ASCII_LOGO,
          initialStep: "build",
          initialInstallMode,
          initialExpertMode: projectConfig?.config?.expertMode,
          initialDomains: projectConfig?.config?.domains,
          initialAgents: projectConfig?.config?.selectedAgents,
          installedSkillIds: currentSkillIds,
          projectDir: process.cwd(),
          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 addedSkills = result.selectedSkills.filter((id) => !currentSkillIds.includes(id));
    const removedSkills = currentSkillIds.filter((id) => !result.selectedSkills.includes(id));
    const sourceChanges = /* @__PURE__ */ new Map();
    for (const [skillId, selectedSource] of typedEntries(
      result.sourceSelections
    )) {
      const skill = sourceResult.matrix.skills[skillId];
      if (skill?.activeSource && skill.activeSource.name !== selectedSource) {
        sourceChanges.set(skillId, {
          from: skill.activeSource.name,
          to: selectedSource
        });
      }
    }
    const hasSourceChanges = sourceChanges.size > 0;
    const hasSkillChanges = addedSkills.length > 0 || removedSkills.length > 0;
    if (result.validation.warnings.length > 0) {
      this.log("\nWarnings:");
      for (const warning of result.validation.warnings) {
        this.warn(`  ! ${warning.message}`);
      }
      this.log("");
    }
    if (!hasSkillChanges && !hasSourceChanges) {
      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})`);
    }
    this.log("");
    for (const [skillId, change] of sourceChanges) {
      if (change.from === "local") {
        await archiveLocalSkill(projectDir, skillId);
      }
      if (change.to === "local") {
        await restoreArchivedSkill(projectDir, skillId);
      }
    }
    if (isPluginMode && sourceResult.marketplace) {
      for (const skillId of addedSkills) {
        const pluginRef = `${skillId}@${sourceResult.marketplace}`;
        this.log(`Installing plugin: ${pluginRef}...`);
        try {
          await claudePluginInstall(pluginRef, "project", projectDir);
        } catch (error) {
          this.warn(`Failed to install plugin ${pluginRef}: ${getErrorMessage(error)}`);
        }
      }
      for (const skillId of removedSkills) {
        this.log(`Uninstalling plugin: ${skillId}...`);
        try {
          await claudePluginUninstall(skillId, "project", projectDir);
        } catch (error) {
          this.warn(`Failed to uninstall plugin ${skillId}: ${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
      });
      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`);
    }
    this.log(`
\u2713 Plugin updated! (${summaryParts.join(", ")})
`);
  }
};
export {
  Edit as default
};
//# sourceMappingURL=edit.js.map