/**
 * All logging MUST go to stderr, never stdout: the stdio MCP transport uses
 * stdout exclusively for JSON-RPC protocol messages, and writing anything
 * else there would corrupt the stream.
 */
type Level = 'debug' | 'info' | 'warn' | 'error';

function write(level: Level, message: string, meta?: unknown): void {
  const line = `[${new Date().toISOString()}] [${level.toUpperCase()}] ${message}`;
  if (meta !== undefined) {
    process.stderr.write(`${line} ${JSON.stringify(meta)}\n`);
  } else {
    process.stderr.write(`${line}\n`);
  }
}

export const logger = {
  debug: (message: string, meta?: unknown) => write('debug', message, meta),
  info: (message: string, meta?: unknown) => write('info', message, meta),
  warn: (message: string, meta?: unknown) => write('warn', message, meta),
  error: (message: string, meta?: unknown) => write('error', message, meta),
};
