import { readFileSync, existsSync } from "fs";
import { join } from "path";
function generateEnv(context) {
  const { manifest } = context;
  const envVars = aggregateEnvironmentVariables(context.implementationTypes || []);
  let parentDatabaseUrl;
  try {
    const parentEnvPath = join(process.cwd(), ".env");
    if (existsSync(parentEnvPath)) {
      const parentEnvContent = readFileSync(parentEnvPath, "utf-8");
      const match = parentEnvContent.match(/DATABASE_URL=["']?([^"'\n]+)["']?/);
      if (match) {
        parentDatabaseUrl = match[1];
      }
    }
  } catch (err) {
  }
  const byCategory = {};
  for (const envVar of envVars) {
    const category = envVar.category || "Configuration";
    if (!byCategory[category]) {
      byCategory[category] = [];
    }
    byCategory[category].push(envVar);
  }
  const lines = [];
  for (const [category, vars] of Object.entries(byCategory)) {
    lines.push(`# ${category}`);
    for (const envVar of vars) {
      if (envVar.description) {
        lines.push(`# ${envVar.description}`);
      }
      let value = envVar.example || "";
      if (envVar.name === "DATABASE_URL" && parentDatabaseUrl) {
        value = parentDatabaseUrl;
      }
      lines.push(`${envVar.name}="${value}"`);
    }
    lines.push("");
  }
  return lines.join("\n");
}
function aggregateEnvironmentVariables(implementationTypes) {
  const envVarsMap = /* @__PURE__ */ new Map();
  if (!implementationTypes || implementationTypes.length === 0) {
    return [];
  }
  for (const implType of implementationTypes) {
    if (implType.requirements?.environment) {
      for (const envVar of implType.requirements.environment) {
        if (!envVarsMap.has(envVar.name)) {
          envVarsMap.set(envVar.name, envVar);
        }
      }
    }
  }
  return Array.from(envVarsMap.values());
}
export {
  generateEnv as default
};
