import fs from "fs";
import path from "path";
import { resolveServiceCwd } from "./paths.mjs";

export function parseDotenv(filePath) {
  if (!fs.existsSync(filePath)) return {};
  return parseDotenvString(fs.readFileSync(filePath, "utf8"));
}

export function parseDotenvString(source) {
  const env = {};
  for (const line of String(source).split("\n")) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    const eq = trimmed.indexOf("=");
    if (eq === -1) continue;
    const key = trimmed.slice(0, eq).trim();
    let val = trimmed.slice(eq + 1).trim();
    if ((val.startsWith("'") && val.endsWith("'")) || (val.startsWith("\"") && val.endsWith("\""))) {
      val = val.slice(1, -1);
    }
    env[key] = val;
  }
  return env;
}

export function inferEnvFiles(productDir, explicitService, local) {
  if (explicitService.envFile || explicitService.envFiles) {
    const files = [];
    if (explicitService.envFile) files.push(explicitService.envFile);
    if (Array.isArray(explicitService.envFiles)) files.push(...explicitService.envFiles);
    return files;
  }

  const candidates = [];
  const serviceCwd = local?.cwd || ".";
  if (serviceCwd !== ".") {
    candidates.push(path.posix.join(serviceCwd, ".env.testkit"));
    candidates.push(path.posix.join(serviceCwd, ".env"));
  }
  candidates.push(".env.testkit");
  candidates.push(".env");

  return [...new Set(candidates)]
    .map((candidate) => candidate.split(path.sep).join("/"))
    .filter((candidate) => fs.existsSync(resolveServiceCwd(productDir, candidate)));
}

export function loadServiceEnv(productDir, envFiles) {
  const env = {};
  for (const envFile of envFiles) {
    Object.assign(env, parseDotenv(resolveServiceCwd(productDir, envFile)));
  }
  return env;
}
