import { _ as resolveConfigDir, l as escapeRegExp } from "./utils-BnlaT0eO.js";
import fs from "node:fs";
import path from "node:path";

//#region src/infra/env-file.ts
function upsertSharedEnvVar(params) {
	const dir = resolveConfigDir(params.env ?? process.env);
	const filepath = path.join(dir, ".env");
	const key = params.key.trim();
	const value = params.value;
	let raw = "";
	if (fs.existsSync(filepath)) raw = fs.readFileSync(filepath, "utf8");
	const lines = raw.length ? raw.split(/\r?\n/) : [];
	const matcher = new RegExp(`^(\\s*(?:export\\s+)?)${escapeRegExp(key)}\\s*=`);
	let updated = false;
	let replaced = false;
	const nextLines = lines.map((line) => {
		const match = line.match(matcher);
		if (!match) return line;
		replaced = true;
		const next = `${match[1] ?? ""}${key}=${value}`;
		if (next !== line) updated = true;
		return next;
	});
	if (!replaced) {
		nextLines.push(`${key}=${value}`);
		updated = true;
	}
	if (!fs.existsSync(dir)) fs.mkdirSync(dir, {
		recursive: true,
		mode: 448
	});
	const output = `${nextLines.join("\n")}\n`;
	fs.writeFileSync(filepath, output, "utf8");
	fs.chmodSync(filepath, 384);
	return {
		path: filepath,
		updated,
		created: !raw
	};
}

//#endregion
export { upsertSharedEnvVar as t };