// SPEC: PJ2026-0104010803 Workbench composable realtime capabilities.
// Responsibility: validate YAML-owned capability switches without code defaults or implied mode selection.

export const WORKBENCH_REALTIME_CAPABILITY_ENVS = Object.freeze({
  directPublish: "HWLAB_KAFKA_DIRECT_PUBLISH_ENABLED",
  liveKafkaSse: "HWLAB_WORKBENCH_LIVE_KAFKA_SSE_ENABLED",
  kafkaRefreshReplay: "HWLAB_WORKBENCH_KAFKA_REFRESH_REPLAY_ENABLED",
  transactionalProjector: "HWLAB_KAFKA_TRANSACTIONAL_PROJECTOR_ENABLED",
  projectionOutboxRelay: "HWLAB_KAFKA_PROJECTION_OUTBOX_RELAY_ENABLED",
  projectionRealtime: "HWLAB_WORKBENCH_PROJECTION_REALTIME_ENABLED"
});

export function workbenchRealtimeCapabilities(env = process.env) {
  return Object.fromEntries(Object.entries(WORKBENCH_REALTIME_CAPABILITY_ENVS).map(([key, name]) => [key, requiredBooleanEnv(env, name)]));
}

export function requiredBooleanEnv(env, name) {
  const value = String(env?.[name] ?? "").trim().toLowerCase();
  if (value === "true" || value === "1") return true;
  if (value === "false" || value === "0") return false;
  throw capabilityError(
    "hwlab_workbench_realtime_capability_invalid",
    `${name} is required and must be explicitly true or false in the owning YAML.`,
    name
  );
}

function capabilityError(code, message, envName) {
  return Object.assign(new Error(message), {
    code,
    envName,
    statusCode: 503,
    valuesRedacted: true
  });
}
