import { existsSync, rmSync } from "node:fs";
import { resolve, parse as parsePath } from "node:path";
import { homedir } from "node:os";
import { detectInstalledHandlers } from "../../../cli/agents/registry.js";
function isUnsafeDataDir(dataDir) {
  const resolved = resolve(dataDir);
  const root = parsePath(resolved).root;
  if (resolved === root || resolved === "/") return true;
  if (resolved === resolve(homedir())) return true;
  const SYSTEM_ROOTS = [
    "/usr",
    "/bin",
    "/sbin",
    "/etc",
    "/var",
    "/lib",
    "/opt",
    "/boot",
    "/System",
    "/Library",
    "/Applications",
    "/private",
    "C:\\Windows",
    "C:\\Program Files",
    "C:\\Program Files (x86)"
  ];
  for (const sys of SYSTEM_ROOTS) {
    if (resolved === sys) return true;
  }
  return false;
}
async function uninstall(opts) {
  const { dataDir, confirmed } = opts;
  if (!confirmed) {
    return {
      ok: false,
      dataDirRemoved: false,
      agentResults: [],
      error: "Uninstall requires confirmation. Pass confirmed: true or use --yes flag."
    };
  }
  if (isUnsafeDataDir(dataDir)) {
    return {
      ok: false,
      dataDirRemoved: false,
      agentResults: [],
      error: `Refusing to uninstall: data dir "${dataDir}" resolves to a system or home root and is unsafe to delete.`
    };
  }
  const agentResults = [];
  const handlers = detectInstalledHandlers();
  for (const handler of handlers) {
    try {
      const res = await handler.uninstall();
      agentResults.push({
        agentId: handler.id,
        displayName: handler.displayName,
        removed: res.removed
      });
    } catch (err) {
      agentResults.push({
        agentId: handler.id,
        displayName: handler.displayName,
        removed: [],
        error: err instanceof Error ? err.message : String(err)
      });
    }
  }
  let dataDirRemoved = false;
  try {
    if (existsSync(dataDir)) {
      rmSync(dataDir, { recursive: true, force: true });
      dataDirRemoved = true;
    } else {
      dataDirRemoved = true;
    }
  } catch (err) {
    return {
      ok: false,
      dataDirRemoved: false,
      agentResults,
      error: err instanceof Error ? err.message : String(err)
    };
  }
  return {
    ok: true,
    dataDirRemoved,
    agentResults
  };
}
export {
  uninstall
};
//# sourceMappingURL=uninstall.js.map