import { existsSync } from "node:fs";
import { resolve } from "node:path";
import { loadEnvFile } from "node:process";

/**
 * Load repository-root `.env` into `process.env` when the file exists.
 *
 * Uses Node's built-in loader (no dotenv dependency). Variables already set in
 * the process environment are left unchanged. Missing `.env` is a no-op so
 * production and CI keep working without a local file.
 *
 * @returns Absolute path loaded, or `undefined` when no file was present.
 */
export function loadProjectEnv(cwd: string = process.cwd()): string | undefined {
  const envPath = resolve(cwd, ".env");
  if (!existsSync(envPath)) {
    return undefined;
  }

  loadEnvFile(envPath);
  return envPath;
}
