import { existsSync, readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";

function resolveWorkspaceRoot() {
  return resolve(dirname(fileURLToPath(import.meta.url)), "..");
}

export function resolveWorkspaceEnvPath() {
  return resolve(resolveWorkspaceRoot(), ".env");
}

export function loadWorkspaceEnv() {
  const envPath = resolveWorkspaceEnvPath();
  if (!existsSync(envPath)) {
    return envPath;
  }

  const contents = readFileSync(envPath, "utf8");
  for (const rawLine of contents.split(/\r?\n/u)) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#")) {
      continue;
    }

    const separatorIndex = line.indexOf("=");
    if (separatorIndex <= 0) {
      continue;
    }

    const key = line.slice(0, separatorIndex).trim();
    const rawValue = line.slice(separatorIndex + 1).trim();
    const quoted =
      (rawValue.startsWith("\"") && rawValue.endsWith("\""))
      || (rawValue.startsWith("'") && rawValue.endsWith("'"));
    const value = quoted ? rawValue.slice(1, -1) : rawValue;

    if (process.env[key] == null) {
      process.env[key] = value;
    }
  }

  return envPath;
}

