/**
 * @ai-summary Structured logging with Pino (Winston-compatible wrapper)
 * @ai-context All features use this for consistent logging. API maintains Winston compatibility.
 */
import pino from 'pino';

type LogLevel = 'debug' | 'info' | 'warn' | 'error';
const validLevels: LogLevel[] = ['debug', 'info', 'warn', 'error'];

const rawLevel = (process.env.LOG_LEVEL?.toLowerCase() || 'info') as LogLevel;
const level = validLevels.includes(rawLevel) ? rawLevel : 'info';

if (process.env.LOG_LEVEL && rawLevel !== level) {
  console.warn(`Invalid LOG_LEVEL "${process.env.LOG_LEVEL}", falling back to "info"`);
}

const pinoLogger = pino({
  level,
  formatters: {
    level: (label) => ({ level: label }),
  },
  timestamp: pino.stdTimeFunctions.isoTime,
});

// Wrapper maintains logger.info(msg, meta) API for backward compatibility
export const logger = {
  info: (msg: string, meta?: object) => pinoLogger.info(meta || {}, msg),
  warn: (msg: string, meta?: object) => pinoLogger.warn(meta || {}, msg),
  error: (msg: string, meta?: object) => pinoLogger.error(meta || {}, msg),
  debug: (msg: string, meta?: object) => pinoLogger.debug(meta || {}, msg),
  child: (bindings: object) => {
    const childPino = pinoLogger.child(bindings);
    return {
      info: (msg: string, meta?: object) => childPino.info(meta || {}, msg),
      warn: (msg: string, meta?: object) => childPino.warn(meta || {}, msg),
      error: (msg: string, meta?: object) => childPino.error(meta || {}, msg),
      debug: (msg: string, meta?: object) => childPino.debug(meta || {}, msg),
    };
  },
};

export default logger;
