"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var rc_exports = {};
__export(rc_exports, {
  buildBlock: () => buildBlock,
  clear: () => clear,
  escapeRegExp: () => escapeRegExp,
  pickRcFile: () => pickRcFile,
  shellSingleQuote: () => shellSingleQuote,
  write: () => write,
  writeRcFile: () => writeRcFile
});
module.exports = __toCommonJS(rc_exports);
var import_node_fs = require("node:fs");
var import_node_os = require("node:os");
var import_node_path = __toESM(require("node:path"));
var import_node_process = __toESM(require("node:process"));
var import_home = require("../env/home");
function buildBlock(opts) {
  const begin = `# BEGIN ${opts.service} env (managed)`;
  const end = `# END ${opts.service} env (managed)`;
  const noteLines = (opts.notes ?? []).map((line) => `# ${line}`);
  const exportLines = Object.entries(opts.exports).map(
    ([name, value]) => `export ${name}=${shellSingleQuote(value)}`
  );
  const body = [...noteLines, ...exportLines].join("\n");
  return {
    begin,
    end,
    body,
    full: `${begin}
${body}
${end}`
  };
}
function clear(service, legacySentinels = []) {
  if ((0, import_node_os.platform)() !== "darwin") {
    return false;
  }
  const rcPath = pickRcFile();
  if (!rcPath || !(0, import_node_fs.existsSync)(rcPath)) {
    return false;
  }
  let existing = (0, import_node_fs.readFileSync)(rcPath, "utf8");
  let removedAny = false;
  const sentinelsToStrip = [
    `# BEGIN ${service} env (managed)`,
    ...legacySentinels
  ];
  for (const begin of sentinelsToStrip) {
    const end = begin.replace(/\bBEGIN\b/, "END");
    const endStripped = end.replace(/\s*\(managed\)\s*$/, "");
    const endAlt = end === endStripped ? escapeRegExp(end) : `(?:${escapeRegExp(end)}|${escapeRegExp(endStripped)})`;
    const re = new RegExp(
      `
*${escapeRegExp(begin)}[\\s\\S]*?${endAlt}
?`,
      "g"
    );
    const next = existing.replace(re, "\n");
    if (next !== existing) {
      removedAny = true;
      existing = next;
    }
  }
  if (removedAny) {
    writeRcFile(rcPath, existing.replace(/\n{3,}/g, "\n\n"));
  }
  return removedAny;
}
function escapeRegExp(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function pickRcFile(shellOverride) {
  const home = (0, import_home.getHome)();
  if (!home) {
    return void 0;
  }
  const shellPath = import_node_process.default.env["SHELL"] ?? "";
  const shell = shellOverride ?? (shellPath.endsWith("zsh") ? "zsh" : shellPath.endsWith("bash") ? "bash" : shellPath.endsWith("fish") ? "fish" : void 0);
  if (shell === "zsh") {
    return import_node_path.default.join(home, ".zshenv");
  }
  if (shell === "bash") {
    const bashrc = import_node_path.default.join(home, ".bashrc");
    if ((0, import_node_fs.existsSync)(bashrc)) {
      return bashrc;
    }
    const bashProfile = import_node_path.default.join(home, ".bash_profile");
    if ((0, import_node_fs.existsSync)(bashProfile)) {
      return bashProfile;
    }
    return bashrc;
  }
  if (shell === "fish") {
    return import_node_path.default.join(home, ".config", "fish", "config.fish");
  }
  return void 0;
}
function shellSingleQuote(value) {
  return `'${value.replace(/'/g, "'\\''")}'`;
}
function write(opts) {
  if ((0, import_node_os.platform)() !== "darwin") {
    return {
      rcPath: void 0,
      outcome: "skipped",
      reason: "unsupported-platform"
    };
  }
  const rcPath = opts.rcPath ?? pickRcFile(opts.shell);
  if (!rcPath) {
    return { rcPath: void 0, outcome: "skipped", reason: "unknown-shell" };
  }
  const { begin, end, full: desiredBlock } = buildBlock(opts);
  let onDisk = "";
  if ((0, import_node_fs.existsSync)(rcPath)) {
    onDisk = (0, import_node_fs.readFileSync)(rcPath, "utf8");
  }
  let working = onDisk;
  for (const legacyBegin of opts.legacySentinels ?? []) {
    const legacyEnd = legacyBegin.replace(/\bBEGIN\b/, "END");
    const legacyEndStripped = legacyEnd.replace(/\s*\(managed\)\s*$/, "");
    const endAlt = legacyEnd === legacyEndStripped ? escapeRegExp(legacyEnd) : `(?:${escapeRegExp(legacyEnd)}|${escapeRegExp(legacyEndStripped)})`;
    const legacyRe = new RegExp(
      `
*${escapeRegExp(legacyBegin)}[\\s\\S]*?${endAlt}
?`,
      "g"
    );
    working = working.replace(legacyRe, "\n");
  }
  const blockRe = new RegExp(
    `${escapeRegExp(begin)}[\\s\\S]*?${escapeRegExp(end)}`
  );
  const match = blockRe.exec(working);
  if (match) {
    if (match[0] === desiredBlock && working === onDisk) {
      return { rcPath, outcome: "unchanged" };
    }
    const rewritten = working.slice(0, match.index) + desiredBlock + working.slice(match.index + match[0].length);
    writeRcFile(rcPath, rewritten.replace(/\n{3,}/g, "\n\n"));
    return { rcPath, outcome: "updated" };
  }
  const needsLeadingNewline = working.length > 0 && !working.endsWith("\n\n");
  const prefix = needsLeadingNewline ? working.endsWith("\n") ? "\n" : "\n\n" : "";
  const next = `${working}${prefix}${desiredBlock}
`.replace(/\n{3,}/g, "\n\n");
  writeRcFile(rcPath, next);
  return { rcPath, outcome: "inserted" };
}
function writeRcFile(rcPath, contents) {
  (0, import_node_fs.writeFileSync)(rcPath, contents, { mode: 384 });
  try {
    (0, import_node_fs.chmodSync)(rcPath, 384);
  } catch {
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildBlock,
  clear,
  escapeRegExp,
  pickRcFile,
  shellSingleQuote,
  write,
  writeRcFile
});
