/**
 * Debug utility for @blinksgg/canvas
 *
 * Uses the `debug` package with `canvas:*` namespaces.
 * Enable in browser: `localStorage.debug = 'canvas:*'`
 * Enable in Node:    `DEBUG=canvas:* node ...`
 *
 * Log levels:
 *   debug('message')         — verbose trace (blue)
 *   debug.warn('message')    — warnings (yellow, always stderr)
 *   debug.error('message')   — errors (red, always stderr)
 */

import debugFactory from 'debug';

const NAMESPACE = 'canvas';

export interface CanvasDebugger {
	/** Verbose trace logging (gated by DEBUG env / localStorage.debug) */
	(formatter: string, ...args: unknown[]): void;
	/** Warning logging — uses debug but with :warn suffix */
	warn: debugFactory.Debugger;
	/** Error logging — uses debug but with :error suffix */
	error: debugFactory.Debugger;
}

/**
 * Create a debug logger for a specific module.
 *
 * @example
 * ```ts
 * const debug = createDebug('graph');
 * debug('loaded %d nodes', count);        // canvas:graph
 * debug.warn('node %s not found', id);    // canvas:graph:warn
 * debug.error('sync failed: %O', err);    // canvas:graph:error
 * ```
 */
export function createDebug(module: string): CanvasDebugger {
	const base = debugFactory(`${NAMESPACE}:${module}`);
	const warn = debugFactory(`${NAMESPACE}:${module}:warn`);
	const error = debugFactory(`${NAMESPACE}:${module}:error`);

	// Warnings and errors always log (even without DEBUG=canvas:*)
	warn.enabled = true;
	error.enabled = true;

	// Color hints: warn = yellow, error = red
	warn.log = console.warn.bind(console);
	error.log = console.error.bind(console);

	// Build the debugger with warn/error sub-loggers
	const debugFn: CanvasDebugger = Object.assign(base, { warn, error });
	return debugFn;
}

// Pre-configured debug loggers
export const debug = {
	graph: {
		node: createDebug('graph:node'),
		edge: createDebug('graph:edge'),
		sync: createDebug('graph:sync'),
	},
	ui: {
		selection: createDebug('ui:selection'),
		drag: createDebug('ui:drag'),
		resize: createDebug('ui:resize'),
	},
	sync: {
		status: createDebug('sync:status'),
		mutations: createDebug('sync:mutations'),
		queue: createDebug('sync:queue'),
	},
	viewport: createDebug('viewport'),
};
