import { config, parse } from "dotenv";
import fs from "node:fs";
import path from "node:path";

const PROJECT_ROOT = path.resolve(__dirname, "..");

/** 与 dev:start 一致：先 .env，再 .dev/infra.env 覆盖 */
export function loadDevEnv(options?: { quiet?: boolean }): void {
  config({ path: path.join(PROJECT_ROOT, ".env"), quiet: options?.quiet });
  const infraEnvPath = path.join(PROJECT_ROOT, ".dev", "infra.env");
  if (fs.existsSync(infraEnvPath)) {
    config({ path: infraEnvPath, override: true, quiet: options?.quiet });
  }
}

/** 读取 infra.env 键值，供 spawn 子进程显式合并 */
export function readInfraEnvOverrides(): Record<string, string> {
  const infraEnvPath = path.join(PROJECT_ROOT, ".dev", "infra.env");
  if (!fs.existsSync(infraEnvPath)) {
    return {};
  }
  return parse(fs.readFileSync(infraEnvPath));
}
