#!/usr/bin/env node
import {
  Confirm
} from "../chunk-N6S7ZRIL.js";
import {
  INFO_MESSAGES,
  SUCCESS_MESSAGES
} from "../chunk-MR6OBL3B.js";
import {
  claudePluginUninstall,
  getProjectPluginsDir,
  isClaudeCLIAvailable,
  listPluginNames,
  loadProjectSourceConfig,
  readForkedFromMetadata
} from "../chunk-TZXYBG3R.js";
import "../chunk-OCEFD7V6.js";
import "../chunk-T4EXUIBY.js";
import {
  BaseCommand,
  EXIT_CODES
} from "../chunk-VR3CDXDT.js";
import {
  directoryExists,
  getErrorMessage,
  listDirectories,
  remove
} from "../chunk-LWXRUR6B.js";
import {
  CLAUDE_DIR,
  CLAUDE_SRC_DIR,
  CLI_COLORS,
  DEFAULT_BRANDING
} from "../chunk-6OWHQ7HM.js";
import "../chunk-EC3UJRKZ.js";
import {
  init_esm_shims
} from "../chunk-DHET7RCE.js";

// src/cli/commands/uninstall.tsx
init_esm_shims();
import { Flags } from "@oclif/core";
import { render, Box, Text, useApp } from "ink";
import path from "path";
import { jsx, jsxs } from "react/jsx-runtime";
function collectConfiguredSources(config) {
  if (!config) return [];
  return [
    ...config.source ? [config.source] : [],
    ...config.sources?.map((entry) => entry.url) ?? []
  ];
}
function collectConfiguredAgents(config) {
  if (!config) return [];
  const agents = config.agents;
  if (!Array.isArray(agents)) return [];
  return agents.map((a) => a.name);
}
async function detectUninstallTarget(projectDir) {
  const pluginsDir = getProjectPluginsDir(projectDir);
  const skillsDir = path.join(projectDir, CLAUDE_DIR, "skills");
  const agentsDir = path.join(projectDir, CLAUDE_DIR, "agents");
  const claudeDir = path.join(projectDir, CLAUDE_DIR);
  const claudeSrcDir = path.join(projectDir, CLAUDE_SRC_DIR);
  const [hasLocalSkills, hasLocalAgents, hasClaudeDir, hasClaudeSrcDir, config] = await Promise.all(
    [
      directoryExists(skillsDir),
      directoryExists(agentsDir),
      directoryExists(claudeDir),
      directoryExists(claudeSrcDir),
      loadProjectSourceConfig(projectDir)
    ]
  );
  let pluginNames = [];
  try {
    pluginNames = await listPluginNames(projectDir);
  } catch {
  }
  const configuredSources = collectConfiguredSources(config);
  const configuredAgents = collectConfiguredAgents(config);
  return {
    hasPlugins: pluginNames.length > 0,
    pluginNames,
    hasLocalSkills,
    hasLocalAgents,
    hasClaudeDir,
    hasClaudeSrcDir,
    pluginsDir,
    skillsDir,
    agentsDir,
    claudeDir,
    claudeSrcDir,
    config,
    configuredSources,
    configuredAgents
  };
}
var UninstallConfirm = ({
  target,
  removeAll,
  onConfirm,
  onCancel
}) => {
  const { exit } = useApp();
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx(Text, { bold: true, children: "The following will be removed:" }),
    /* @__PURE__ */ jsx(Text, { children: " " }),
    target.hasPlugins && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
      /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.ERROR, children: " Plugins:" }),
      /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
        " ",
        target.pluginsDir
      ] })
    ] }),
    (target.hasLocalSkills || target.hasLocalAgents) && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
      /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.ERROR, children: " CLI-managed files:" }),
      target.hasLocalSkills && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
        " ",
        target.skillsDir,
        "/ (matching sources)"
      ] }),
      target.hasLocalAgents && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
        " ",
        target.agentsDir,
        "/ (CLI-compiled)"
      ] })
    ] }),
    removeAll && target.hasClaudeSrcDir && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
      /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.ERROR, children: " Config:" }),
      /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
        " ",
        target.claudeSrcDir,
        "/"
      ] })
    ] }),
    /* @__PURE__ */ jsx(Text, { children: " " }),
    /* @__PURE__ */ jsx(
      Confirm,
      {
        message: "Are you sure you want to uninstall?",
        onConfirm: () => {
          onConfirm();
          exit();
        },
        onCancel: () => {
          onCancel();
          exit();
        },
        defaultValue: false
      }
    )
  ] });
};
async function isDirectoryEmpty(dirPath) {
  const { readdir } = await import("fs/promises");
  try {
    const allEntries = await readdir(dirPath);
    return allEntries.length === 0;
  } catch {
    return true;
  }
}
function skillMatchesConfiguredSource(forkedFromSource, configuredSources) {
  if (!forkedFromSource || configuredSources.length === 0) return false;
  return configuredSources.includes(forkedFromSource);
}
function shouldRemoveSkill(forkedFrom, configuredSources, hasConfig) {
  return forkedFrom !== null && (skillMatchesConfiguredSource(forkedFrom.source, configuredSources) || !forkedFrom.source && hasConfig);
}
var Uninstall = class _Uninstall extends BaseCommand {
  static summary = `Remove ${DEFAULT_BRANDING.NAME} from this project`;
  static description = `Uninstall ${DEFAULT_BRANDING.NAME} from this project. Removes CLI-managed skills (matched by source), compiled agents, and plugins. User-created content is preserved.`;
  static examples = [
    "<%= config.bin %> <%= command.id %>",
    "<%= config.bin %> <%= command.id %> --yes",
    "<%= config.bin %> <%= command.id %> --all"
  ];
  static flags = {
    ...BaseCommand.baseFlags,
    yes: Flags.boolean({
      char: "y",
      description: "Skip confirmation prompt",
      default: false
    }),
    all: Flags.boolean({
      description: "Also remove .claude-src/ config directory",
      default: false
    })
  };
  async run() {
    const { flags } = await this.parse(_Uninstall);
    const projectDir = process.cwd();
    this.log("");
    this.log(`${DEFAULT_BRANDING.NAME} Uninstall`);
    this.log("");
    const target = await detectUninstallTarget(projectDir);
    const hasAnythingToRemove = target.hasPlugins || target.hasLocalSkills || target.hasLocalAgents || flags.all && target.hasClaudeSrcDir;
    if (!hasAnythingToRemove) {
      this.warn("Nothing to uninstall.");
      this.log("");
      this.log(INFO_MESSAGES.NOT_INSTALLED);
      this.log("");
      this.log(INFO_MESSAGES.NO_CHANGES_MADE);
      return;
    }
    if (!flags.yes) {
      const confirmed = await new Promise((resolve) => {
        const { waitUntilExit } = render(
          /* @__PURE__ */ jsx(
            UninstallConfirm,
            {
              target,
              removeAll: flags.all,
              onConfirm: () => resolve(true),
              onCancel: () => resolve(false)
            }
          )
        );
        waitUntilExit().catch(() => resolve(false));
      });
      if (!confirmed) {
        this.log("");
        this.log("Uninstall cancelled");
        this.exit(EXIT_CODES.CANCELLED);
      }
    } else {
      this.log("The following will be removed:");
      this.log("");
      if (target.hasPlugins) {
        this.log("  Plugins:");
        this.log(`    ${target.pluginsDir}`);
      }
      if (target.hasLocalSkills || target.hasLocalAgents) {
        this.log("  CLI-managed files:");
        if (target.hasLocalSkills) {
          this.log(`    ${target.skillsDir}/ (matching sources)`);
        }
        if (target.hasLocalAgents) {
          this.log(`    ${target.agentsDir}/ (CLI-compiled)`);
        }
      }
      if (flags.all && target.hasClaudeSrcDir) {
        this.log("  Config:");
        this.log(`    ${target.claudeSrcDir}/`);
      }
      this.log("");
    }
    if (target.hasPlugins) {
      this.log("Uninstalling plugins...");
      try {
        const cliAvailable = await isClaudeCLIAvailable();
        for (const pluginName of target.pluginNames) {
          if (cliAvailable) {
            try {
              await claudePluginUninstall(pluginName, "project", projectDir);
            } catch {
            }
          }
          const pluginPath = path.join(target.pluginsDir, pluginName);
          await remove(pluginPath);
          this.log(`  Uninstalled plugin '${pluginName}'`);
        }
        this.logSuccess(
          `Uninstalled ${target.pluginNames.length} ${target.pluginNames.length === 1 ? "plugin" : "plugins"}`
        );
      } catch (error) {
        this.log("Plugin uninstall failed");
        this.error(getErrorMessage(error), {
          exit: EXIT_CODES.ERROR
        });
      }
    }
    try {
      await this.removeLocalFiles(target, flags.all);
    } catch (error) {
      this.log("Failed to remove local files");
      this.error(getErrorMessage(error), {
        exit: EXIT_CODES.ERROR
      });
    }
    this.log("");
    this.log(`${DEFAULT_BRANDING.NAME} has been uninstalled.`);
    this.log("");
    this.logSuccess(SUCCESS_MESSAGES.UNINSTALL_COMPLETE);
    this.log("");
  }
  async removeLocalFiles(target, removeAll) {
    await this.removeMatchingSkills(target);
    await this.removeMatchingAgents(target);
    if (removeAll && target.hasClaudeSrcDir) {
      await remove(target.claudeSrcDir);
      this.logSuccess(`Removed ${CLAUDE_SRC_DIR}/`);
    }
    await this.removeEmptyClaudeDir(target);
  }
  async removeMatchingSkills(target) {
    if (!target.hasLocalSkills) return;
    const skillDirNames = await listDirectories(target.skillsDir);
    let removedCount = 0;
    let skippedCount = 0;
    for (const skillDirName of skillDirNames) {
      const skillDir = path.join(target.skillsDir, skillDirName);
      const forkedFrom = await readForkedFromMetadata(skillDir);
      if (shouldRemoveSkill(forkedFrom, target.configuredSources, target.config !== null)) {
        await remove(skillDir);
        removedCount++;
        this.log(`  Uninstalled skill '${skillDirName}'`);
      } else {
        this.warn(`Skipping '${skillDirName}': not created by ${DEFAULT_BRANDING.NAME} CLI`);
        skippedCount++;
      }
    }
    if (removedCount > 0) {
      this.logSuccess(
        `Removed ${removedCount} CLI-installed ${removedCount === 1 ? "skill" : "skills"}`
      );
    }
    if (skippedCount > 0) return;
    if (!await directoryExists(target.skillsDir)) return;
    if (await isDirectoryEmpty(target.skillsDir)) {
      await remove(target.skillsDir);
    }
  }
  async removeMatchingAgents(target) {
    if (!target.hasLocalAgents) return;
    if (target.configuredAgents.length === 0) return;
    const agentFiles = await this.listAgentFiles(target.agentsDir);
    let removedCount = 0;
    for (const agentFile of agentFiles) {
      const agentName = agentFile.replace(/\.md$/, "");
      if (!target.configuredAgents.includes(agentName)) continue;
      await remove(path.join(target.agentsDir, agentFile));
      this.log(`  Uninstalled agent '${agentName}'`);
      removedCount++;
    }
    if (removedCount > 0) {
      this.logSuccess(
        `Removed ${removedCount} compiled ${removedCount === 1 ? "agent" : "agents"}`
      );
    }
    if (!await directoryExists(target.agentsDir)) return;
    if (await isDirectoryEmpty(target.agentsDir)) {
      await remove(target.agentsDir);
    }
  }
  async listAgentFiles(agentsDir) {
    try {
      const { readdir } = await import("fs/promises");
      return (await readdir(agentsDir)).filter((f) => f.endsWith(".md"));
    } catch {
      return [];
    }
  }
  async removeEmptyClaudeDir(target) {
    if (!target.hasClaudeDir) return;
    if (!await directoryExists(target.claudeDir)) return;
    if (await isDirectoryEmpty(target.claudeDir)) {
      await remove(target.claudeDir);
      this.logSuccess(`Removed ${CLAUDE_DIR}/`);
    } else {
      this.log(`Kept ${CLAUDE_DIR}/ (contains user content)`);
    }
  }
};
export {
  Uninstall as default
};
//# sourceMappingURL=uninstall.js.map