const path = require("path");
const { buildUninstallPlan, executeUninstall } = require("../lib/uninstall");

module.exports = async function uninstall(flags = {}) {
  const rootDir = process.cwd();
  const dryRun = Boolean(flags["dry-run"]);
  const keepAgent = Boolean(flags["keep-agent"]);
  const keepIde = Boolean(flags["keep-ide"]);
  const includeSidecars = Boolean(flags["include-sidecars"]);
  const yes = Boolean(flags.yes || flags.y);

  const plan = buildUninstallPlan(rootDir, { keepAgent, keepIde, includeSidecars });

  if (flags.json) {
    console.log(JSON.stringify({ dry_run: dryRun, plan: plan.map((p) => p.path) }, null, 2));
    if (dryRun) return;
  } else {
    console.log("\n## CapInt Uninstall\n");
    if (!plan.length) {
      console.log("Nothing to remove.\n");
      return;
    }
    console.log("Will remove:");
    for (const p of plan) console.log(`  - ${p.path}`);
    if (keepAgent) console.log("\nKeeping: AGENT.md, design.md, AGENTS.md (--keep-agent)");
    if (keepIde) console.log("Keeping: IDE projections (--keep-ide)");
    console.log("");
  }

  if (dryRun) {
    if (!flags.json) console.log("Dry-run — no files deleted.\n");
    return;
  }

  if (!yes && !flags.json) {
    console.error("Add --yes to confirm removal.");
    process.exit(1);
  }

  const result = executeUninstall(rootDir, plan, false);
  if (!flags.json) {
    for (const p of result.removed) console.log(`  removed ${p}`);
    for (const p of result.skipped) console.log(`  skipped ${p}`);
    console.log("\nDone. Global CLI: npm uninstall -g @bcelep/capint\n");
  }
};
