import pino from 'pino';

export const logger = pino({
  level: process.env.LOG_LEVEL || 'info',
  transport: { target: 'pino-pretty', options: { colorize: true } },
});

// Route uncaught errors through pino so they get timestamps in stderr
process.on('uncaughtException', (err) => {
  logger.fatal({ err }, 'Uncaught exception');
  process.exit(1);
});

process.on('unhandledRejection', (reason) => {
  logger.error({ err: reason }, 'Unhandled rejection');
});

/**
 * Lightweight per-request timing helper.
 * All output is at `debug` level — set LOG_LEVEL=debug to enable.
 *
 * Usage:
 *   const perf = perfTimer(myFunction, { group: group.name });
 *   await something();
 *   perf.step(something);
 *   perf.done();
 */
export function perfTimer(label: string, meta?: Record<string, unknown>) {
  const t0 = Date.now();
  let last = t0;
  return {
    step(name: string, extra?: Record<string, unknown>) {
      const now = Date.now();
      logger.debug({ label, step: name, stepMs: now - last, totalMs: now - t0, ...meta, ...extra }, `perf › ${name}`);
      last = now;
    },
    done(extra?: Record<string, unknown>) {
      const now = Date.now();
      logger.debug({ label, totalMs: now - t0, ...meta, ...extra }, `perf › done`);
    },
  };
}
