/**
 * Unified host event envelope. Unknown vendor events stay opaque (WP-01).
 */

export interface HostEventEnvelope {
  schema: "codeflowmu.host-event/v1";

  eventId: string;
  at: string;

  hostId: string;
  workerId: string;
  runId: string;

  /** Open string; Core depends on a small stable prefix set only. */
  type: string;

  payload?: unknown;
  /** Preserve unrecognized vendor payload when type is opaque. */
  raw?: unknown;
}

export type HostEventInput = {
  eventId: string;
  at: string;
  hostId: string;
  workerId: string;
  runId: string;
  type?: string;
  payload?: unknown;
  raw?: unknown;
};

/**
 * Build an envelope for any host event. Missing/unknown types become opaque
 * and original material is retained in `raw` so nothing is dropped.
 */
export function toHostEventEnvelope(input: HostEventInput): HostEventEnvelope {
  const type =
    typeof input.type === "string" && input.type.trim().length > 0
      ? input.type
      : "host.event.opaque";
  const envelope: HostEventEnvelope = {
    schema: "codeflowmu.host-event/v1",
    eventId: input.eventId,
    at: input.at,
    hostId: input.hostId,
    workerId: input.workerId,
    runId: input.runId,
    type,
  };
  if (input.payload !== undefined) {
    envelope.payload = input.payload;
  }
  if (input.raw !== undefined) {
    envelope.raw = input.raw;
  } else if (type === "host.event.opaque" && input.payload !== undefined) {
    envelope.raw = input.payload;
  }
  return envelope;
}
