import winston from 'winston';
import path from 'path';
import fs from 'fs-extra';

export const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.printf(({ timestamp, level, message, ...meta }) => {
          let msg = `${timestamp} [${level}]: ${message}`;
          if (Object.keys(meta).length > 0) {
            // Try to stringify meta, but handle circular structures
            try {
              msg += ` ${JSON.stringify(meta)}`;
            } catch (e) {
              msg += ` [circular object]`;
            }
          }
          return msg;
        })
      ),
    }),
  ],
});

// Add file transport if configured
if (process.env.LOG_FILE) {
  const logDir = path.dirname(process.env.LOG_FILE);
  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true });
  }
  logger.add(new winston.transports.File({
    filename: process.env.LOG_FILE,
    format: winston.format.combine(
      winston.format.timestamp(),
      winston.format.json()
    ),
  }));
}
