/**
 * Frontend telemetry bridge.
 *
 * Provides tel.info(), tel.warn(), tel.error() convenience methods that
 * forward structured log events to the Bun process via RPC for tracing.
 * No browser OTEL SDK needed (WebKitGTK incompatible).
 */

import { appRpc } from "./rpc.ts";

type LogLevel = "info" | "warn" | "error";
type Attributes = Record<string, string | number | boolean>;

function sendLog(level: LogLevel, message: string, attributes?: Attributes): void {
  try {
    appRpc?.request["telemetry.log"]({
      level,
      message,
      attributes: attributes ?? {},
    }).catch((err: unknown) => {
      // Best-effort — never block the caller
      console.warn("[tel-bridge] RPC failed:", err);
    });
  } catch {
    // RPC not yet initialized — swallow silently
  }
}

/** Frontend telemetry API. All calls are fire-and-forget. */
export const tel = {
  /** Log an informational event. */
  info(message: string, attributes?: Attributes): void {
    sendLog("info", message, attributes);
  },

  /** Log a warning event. */
  warn(message: string, attributes?: Attributes): void {
    sendLog("warn", message, attributes);
  },

  /** Log an error event. */
  error(message: string, attributes?: Attributes): void {
    sendLog("error", message, attributes);
  },
} as const;
