/**
 * WP-13 — HostEvent → RuntimeEvent mapper.
 * Unknown event types remain displayable and never throw.
 */

import {
  SWITCHBOARD_OBSERVATION_EVENT_SET,
} from "./SwitchboardObservationEvents.js";

export interface RuntimeObservationEvent {
  event_type: string;
  at: string;
  payload: Record<string, unknown>;
  known: boolean;
  /** True when type is in the WP-13 switchboard catalog. */
  switchboard: boolean;
}

export function mapHostEventToRuntimeEvent(input: {
  event_type: string;
  payload?: unknown;
  at?: string;
}): RuntimeObservationEvent {
  const event_type = String(input.event_type ?? "unknown").trim() || "unknown";
  const payload =
    input.payload && typeof input.payload === "object"
      ? (input.payload as Record<string, unknown>)
      : { value: input.payload };
  return {
    event_type,
    at: input.at ?? new Date().toISOString(),
    payload,
    known:
      SWITCHBOARD_OBSERVATION_EVENT_SET.has(event_type) ||
      event_type.startsWith("sdk.") ||
      event_type.startsWith("wake_agent.") ||
      event_type.startsWith("runtime.") ||
      event_type.startsWith("codeflowmu."),
    switchboard: SWITCHBOARD_OBSERVATION_EVENT_SET.has(event_type),
  };
}

/**
 * Safe UI projection: never throws; unknown events get a readable label.
 */
export function toPanelDisplayRow(
  event: RuntimeObservationEvent,
): {
  event_type: string;
  label: string;
  at: string;
  unknown: boolean;
} {
  return {
    event_type: event.event_type,
    label: event.known
      ? event.event_type
      : `unknown:${event.event_type || "empty"}`,
    at: event.at,
    unknown: !event.known,
  };
}
