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

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

export function loadWorkspaceEnv() {
  const envPath = resolve(resolveWorkspaceRoot(), ".env");

  try {
    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;
      }
    }
  } catch {
    // Leave environment untouched when .env is not present in the workspace.
  }
}

export function resolveWorkspacePath(...segments: string[]) {
  return resolve(resolveWorkspaceRoot(), ...segments);
}
