import { writeSync } from 'node:fs';

type Level = 'debug' | 'info' | 'warn' | 'error';

function emit(level: Level, msg: string, meta?: Record<string, unknown>): void {
  const line = { ts: new Date().toISOString(), level, msg, ...(meta ?? {}) };
  // Write straight to the fd (1=stdout, 2=stderr). The buffered process.std*
  // streams block-buffer to a pipe (systemd journal), so low-volume logs never
  // flush and stay invisible; writeSync emits each line immediately.
  const fd = level === 'error' || level === 'warn' ? 2 : 1;
  writeSync(fd, `${JSON.stringify(line)}\n`);
}

export const logger = {
  debug: (msg: string, meta?: Record<string, unknown>): void => emit('debug', msg, meta),
  info: (msg: string, meta?: Record<string, unknown>): void => emit('info', msg, meta),
  warn: (msg: string, meta?: Record<string, unknown>): void => emit('warn', msg, meta),
  error: (msg: string, meta?: Record<string, unknown>): void => emit('error', msg, meta),
};
