/**
 * Debug logging, gated by the build-time `__DEBUG__` flag.
 *
 * `__DEBUG__` is set by `vite.config.js` (`define`) from the `VITE_DEBUG` env variable:
 * it is `true` only when `VITE_DEBUG=true` (the Docker dev container sets it, see
 * `compose.yaml`). Any other value, or no value, gives `false`, so a production build
 * never logs debug output.
 *
 * Use {@link createLogger} instead of `console.debug` / `console.log` / `console.table`…
 * When the flag is off, every method is a no-op.
 * `console.error` and `console.warn` are not routed through here: they stay always on.
 *
 * @module Src/Misc
 * @mergeTarget
 */

declare const __DEBUG__: boolean;

/**
 * Whether debug logging is enabled in this build.
 * The `typeof` guard keeps tools without the Vite `define` working: they see `false`.
 */
export const DEBUG: boolean = typeof __DEBUG__ !== 'undefined' && __DEBUG__;

type LogFn = (...args: unknown[]) => void;

/** Console-like logger whose output is prefixed with `[lisio:<scope>]`. */
export interface DebugLogger {
  debug: LogFn;
  log: LogFn;
  info: LogFn;
  table: (data: unknown, columns?: string[]) => void;
  group: LogFn;
  groupCollapsed: LogFn;
  groupEnd: () => void;
  trace: LogFn;
}

const noop = (): void => undefined;

const SILENT_LOGGER: DebugLogger = {
  debug: noop,
  log: noop,
  info: noop,
  table: noop,
  group: noop,
  groupCollapsed: noop,
  groupEnd: noop,
  trace: noop,
};

/**
 * Creates a logger for a feature area. The methods are `console` methods bound with the
 * prefix, so devtools still links each line to the real call site.
 *
 * @param scope Short area name, e.g. `'messages'` → `[lisio:messages] …`.
 * @returns A silent logger when {@link DEBUG} is off.
 */
export function createLogger(scope: string): DebugLogger {
  if (!DEBUG) {
    return SILENT_LOGGER;
  }
  const prefix = `[lisio:${scope}]`;
  return {
    debug: console.debug.bind(console, prefix),
    log: console.log.bind(console, prefix),
    info: console.info.bind(console, prefix),
    table: console.table.bind(console),
    group: console.group.bind(console, prefix),
    groupCollapsed: console.groupCollapsed.bind(console, prefix),
    groupEnd: console.groupEnd.bind(console),
    trace: console.trace.bind(console, prefix),
  };
}
