import fs from "fs";
import path from "path";

let cached: string | null = null;

export function getBackendVersion(): string {
  if (cached) {
    return cached;
  }
  const fromEnv = process.env.APP_VERSION?.trim();
  if (fromEnv) {
    cached = fromEnv;
    return cached;
  }
  try {
    const pkgPath = path.join(__dirname, "..", "package.json");
    const raw = fs.readFileSync(pkgPath, "utf-8");
    cached = (JSON.parse(raw) as { version: string }).version;
    return cached;
  } catch {
    cached = "0.0.0";
    return cached;
  }
}
