// src/util/env.ts
import fs from "fs";
import path from "path";
function readEnvValue(envPath, key) {
  if (!fs.existsSync(envPath)) return void 0;
  const content = fs.readFileSync(envPath, "utf-8");
  const re = new RegExp(`^(?:export\\s+)?${escapeRegex(key)}=(.*)$`, "gm");
  let last;
  let match;
  while ((match = re.exec(content)) !== null) {
    let val = match[1].trim();
    if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
      val = val.slice(1, -1);
    }
    last = val;
  }
  return last;
}
function upsertEnvLine(envPath, key, value) {
  const line = `${key}=${value}`;
  if (!fs.existsSync(envPath)) {
    fs.mkdirSync(path.dirname(envPath), { recursive: true });
    fs.writeFileSync(envPath, `${line}
`, "utf-8");
    return;
  }
  const content = fs.readFileSync(envPath, "utf-8");
  const re = new RegExp(`^(?:export\\s+)?${escapeRegex(key)}=.*$`, "m");
  let updated;
  if (re.test(content)) {
    updated = content.replace(re, line);
    let seen = false;
    updated = updated.split("\n").filter((l) => {
      if (re.test(l)) {
        if (seen) return false;
        seen = true;
      }
      return true;
    }).join("\n");
  } else {
    updated = content.trimEnd() + `
${line}`;
  }
  updated = updated.trimEnd() + "\n";
  atomicWrite(envPath, updated);
}
function ensureEnvLine(envPath, key, value) {
  if (fs.existsSync(envPath)) {
    const content = fs.readFileSync(envPath, "utf-8");
    const re = new RegExp(`^(?:export\\s+)?${escapeRegex(key)}=`, "m");
    if (re.test(content)) return;
  }
  upsertEnvLine(envPath, key, value);
}
function findDuplicateKeys(envPath) {
  if (!fs.existsSync(envPath)) return [];
  const content = fs.readFileSync(envPath, "utf-8");
  const counts = /* @__PURE__ */ new Map();
  for (const line of content.split("\n")) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=/.exec(trimmed);
    if (match) {
      counts.set(match[1], (counts.get(match[1]) ?? 0) + 1);
    }
  }
  return Array.from(counts.entries()).filter(([, count]) => count > 1).map(([key]) => key);
}
function escapeRegex(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function atomicWrite(filePath, content) {
  const tmp = `${filePath}.tmp`;
  fs.writeFileSync(tmp, content, "utf-8");
  fs.renameSync(tmp, filePath);
}

export {
  readEnvValue,
  upsertEnvLine,
  ensureEnvLine,
  findDuplicateKeys
};
