// #region CotLogger [C:3] [TYPE Module] [SEMANTICS logging,cot,molecular,frontend]
// @BRIEF Structured Molecular CoT logger for the frontend — emits JSON lines with REASON/REFLECT/EXPLORE markers.
// @INVARIANT Every log line carries exactly one valid marker (REASON | REFLECT | EXPLORE).
// @INVARIANT trace_id propagates from HTTP response headers or is auto-generated per session.
// @RELATION CALLED_BY -> [Std.Semantics.Svelte]
// @DATA_CONTRACT LogEntry -> { ts, level, trace_id, src, marker, intent, payload?, error? }

type LogMarker = "REASON" | "REFLECT" | "EXPLORE";

/** Structured log entry matching the Molecular CoT JSON wire format. */
interface LogEntry {
  ts: string;
  level: "INFO" | "WARNING" | "ERROR";
  trace_id: string;
  src: string;
  marker: LogMarker;
  intent: string;
  payload?: Record<string, unknown>;
  error?: string;
}

// ── Trace ID (session-level, set once from API response) ──────────
let _traceId = "";

/**
 * Seed or update the session trace ID.
 * Called automatically after the first API response if the backend
 * returns an X-Trace-Id or similar header.
 */
export function setTraceId(id: string): void {
  _traceId = id;
}

/** Returns the current trace ID, or a placeholder if none set. */
export function getTraceId(): string {
  return _traceId || "no-trace";
}

/** Alias for getTraceId — used by components that call initTraceId(). */
export function initTraceId(): string {
  return getTraceId();
}

// ── Structured logger ─────────────────────────────────────────────

/**
 * Emit a single Molecular CoT log line as JSON to the browser console.
 *
 * @param src     — Qualified component/model name, e.g. "MigrationModel.executeMigration"
 * @param marker  — One of "REASON" (before operation), "REFLECT" (verify outcome), "EXPLORE" (error/fallback)
 * @param intent  — Human-readable one-line description of the step
 * @param payload — Arbitrary key-value data (params, result snippet)
 * @param error   — Error message or violated assumption (required for EXPLORE)
 *
 * @example
 *   log("MigrationModel", "REASON", "Starting migration", { taskId })
 *   log("MigrationModel", "REFLECT", "Migration completed", { taskId, status })
 *   log("MigrationModel", "EXPLORE", "Migration failed", { taskId }, "Network timeout")
 */
export function log(
  src: string,
  marker: LogMarker,
  intent: string,
  payload?: Record<string, unknown>,
  error?: string,
): void {
  const entry: LogEntry = {
    ts: new Date().toISOString(),
    level: marker === "EXPLORE" ? "WARNING" : "INFO",
    trace_id: getTraceId(),
    src,
    marker,
    intent,
  };

  if (payload !== undefined) {
    entry.payload = payload;
  }
  if (error !== undefined) {
    entry.error = error;
  }

  const line = JSON.stringify(entry);

  if (marker === "EXPLORE") {
    console.warn(line);
  } else {
    console.info(line);
  }
}
// #endregion CotLogger
