// docforge-editor — the variable catalogue client.
//
// The catalogue (key + bilingual label + namespace group) is served by the
// Go backend at GET /api/docforge/variables, built from the resolvers'
// Keys() as the single source of truth. A consumer fetches it once and uses
// labelMap() to label its sidebar form + authoring palette, instead of
// hard-coding a parallel label table that can drift from the resolvers.

export interface VariableEntry {
  key: string;
  label_de: string;
  label_en: string;
  group: string;
}

interface VariablesResponse {
  variables: VariableEntry[];
}

// fetchVariableCatalogue loads the catalogue from the backend. Throws on a
// non-2xx response so the caller can decide how to degrade.
export async function fetchVariableCatalogue(): Promise<VariableEntry[]> {
  const res = await fetch("/api/docforge/variables", {
    headers: { Accept: "application/json" },
  });
  if (!res.ok) {
    throw new Error(`docforge variables: HTTP ${res.status}`);
  }
  const body = (await res.json()) as VariablesResponse;
  return body.variables ?? [];
}

// labelMap turns a catalogue into a key → {de, en} lookup for a label
// function. Keys absent from the map fall back to the raw key at the call
// site, so a failed fetch degrades to dotted-key labels rather than a
// broken form.
export function labelMap(catalogue: VariableEntry[]): Record<string, { de: string; en: string }> {
  const out: Record<string, { de: string; en: string }> = {};
  for (const e of catalogue) {
    out[e.key] = { de: e.label_de, en: e.label_en };
  }
  return out;
}
