import { SerializedBlockTree } from "./block-types";

const DEBUG_KEY = "lisio_reader_debug";

export function isStructureDebugEnabled(): boolean {
  try {
    return window.localStorage.getItem(DEBUG_KEY) === "1";
  } catch {
    return false;
  }
}

/**
 * Prints a console.table of the segmented block tree next to the existing
 * `console.trace` in lisioReadyChannelHandler. Also exposes the tree on
 * `window.__lisioBlocks` so testers can copy it as a fixture for
 * tests/reader/structure/fixtures. Gated by `localStorage.lisio_reader_debug`
 * so it tree-shakes away in normal production use.
 */
export function dumpBlockTree(tree: SerializedBlockTree): void {
  if (!isStructureDebugEnabled()) return;
  (window as unknown as { __lisioBlocks?: SerializedBlockTree }).__lisioBlocks = tree;
  console.groupCollapsed(
    `[reading-mode] structure: ${tree.blocks.length} blocks, ${tree.dropped.length} dropped leaves (${tree.stats.ms}ms)${tree.stats.bailed ? ` — BAILED: ${tree.stats.bailed}` : ""}`,
  );
  console.table(
    tree.blocks.map((b) => ({
      id: b.i,
      parent: b.p,
      kind: b.k,
      confidence: b.c,
      leaves: b.l.length,
      range: `${b.r[0]}-${b.r[1]}`,
      label: b.n ?? "",
    })),
  );
  console.groupEnd();
}
