/**
 * The web image's own build identity.
 *
 * Same runtime-injection trick as API_ORIGIN (lib/api.ts): docker/web.Dockerfile
 * bakes APP_VERSION / GIT_SHA / BUILD_DATE as ENV, layout.tsx reads them on the
 * server per request and paints them into window.__APP_BUILD__. Reading
 * process.env directly from a client component would return undefined — Next
 * only inlines NEXT_PUBLIC_* into the browser bundle, and baking the version in
 * at build time is exactly what we are avoiding elsewhere.
 */
export interface BuildInfo {
  version: string;
  gitSha: string;
  buildDate: string;
}

export const UNKNOWN_BUILD: BuildInfo = {
  version: "dev",
  gitSha: "unknown",
  buildDate: "unknown",
};

/** Server-side read, used by layout.tsx to produce the injected payload. */
export function readBuildInfoFromEnv(): BuildInfo {
  return {
    version: process.env.APP_VERSION ?? UNKNOWN_BUILD.version,
    gitSha: process.env.GIT_SHA ?? UNKNOWN_BUILD.gitSha,
    buildDate: process.env.BUILD_DATE ?? UNKNOWN_BUILD.buildDate,
  };
}

/** Browser-side read of what layout.tsx injected. */
export function webBuildInfo(): BuildInfo {
  if (typeof window === "undefined") return readBuildInfoFromEnv();
  const injected = (window as { __APP_BUILD__?: BuildInfo }).__APP_BUILD__;
  return injected ?? UNKNOWN_BUILD;
}
