import { apiGet } from "./client";

/**
 * What `/api/version` answers — the client's half of `build_version_payload`
 * (`src/scribe/routes/api.py`), which is where the reasoning for the shape is
 * written down.
 *
 * EVERY FIELD BUT `version` IS OPTIONAL, and an absent one means "this build
 * does not know", not "empty". A local build has no ordering key and no
 * channel, and the server says so by omitting the keys rather than sending
 * `""` — emitting a placeholder would let it claim a position in an update
 * order it is not part of.
 *
 * So a renderer must read ABSENCE, never falsiness. `build` is a number and
 * `0` is a legitimate ordering key, so `v.build || "unknown"` would report a
 * real value as unknown; `v.build ?? "unknown"` is the correct form.
 */
export interface VersionPayload {
  /** The NAME — `YYYY.MM.DD.HHMM` from commit time. Answers "is this the same code?" */
  version: string;
  /** The ORDERING KEY — minutes since 2020-01-01, from build time. Absent on a local build. */
  build?: number;
  /** `dev` / `main` / a tag. Its own field, never folded into the name. */
  channel?: string;
  /** The commit the artifact was published under, so its claim can be checked against the registry. */
  commit?: string;
}

/**
 * SHORTER than the client's 30s default, deliberately.
 *
 * This readout answers "what is running?" during an incident, which is exactly
 * when the server may be the thing that is unwell — and it is one static field
 * off a route that does no work, so a healthy instance answers it immediately.
 * Waiting the full default before saying so would leave a person staring at
 * "still loading" for half a minute in the moment they are trying to find out
 * whether the instance is alive at all. Eight seconds clears a slow-but-alive
 * instance and tells them something quickly when it is not.
 */
const VERSION_TIMEOUT_MS = 8000;

export function fetchVersion(): Promise<VersionPayload> {
  return apiGet<VersionPayload>("/api/version", { timeoutMs: VERSION_TIMEOUT_MS });
}
