import { readFileSync } from "node:fs";

const readJsonFile = (fileUrl) => {
  try {
    return JSON.parse(readFileSync(fileUrl, "utf8"));
  } catch {
    return {};
  }
};

const packageJsonUrl = new URL("../package.json", import.meta.url);
const buildInfoUrl = new URL("./buildInfo.json", import.meta.url);

export const getServerVersionInfo = () => {
  if (process.env.FC_PACKAGE_VERSION && process.env.FC_BUILD_NUMBER) {
    return {
      version: process.env.FC_PACKAGE_VERSION,
      buildNumber: process.env.FC_BUILD_NUMBER,
    };
  }

  const packageJson = readJsonFile(packageJsonUrl);
  const buildInfo = readJsonFile(buildInfoUrl);

  return {
    version: packageJson.version ?? "dev",
    buildNumber: buildInfo.buildNumber ?? "dev",
  };
};
