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

const LEVEL_ORDER: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };

function parseLevel(raw: string | undefined): Level {
  const v = (raw ?? 'info').toLowerCase();
  if (v === 'debug' || v === 'info' || v === 'warn' || v === 'error') return v;
  return 'info';
}

const minLevel = LEVEL_ORDER[parseLevel(process.env.LOG_LEVEL)];

function emit(level: Level, msg: string, meta?: Record<string, unknown>): void {
  if (LEVEL_ORDER[level] < minLevel) return;
  const line = { ts: new Date().toISOString(), level, msg, ...(meta ?? {}) };
  const stream = level === 'error' || level === 'warn' ? process.stderr : process.stdout;
  stream.write(`${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),
};
