import pino from 'pino';

// Browser-safe logger that falls back to console if Pino isn't available
const createBrowserLogger = () => ({
  debug: (...args: any[]) => console.debug(...args),
  info: (...args: any[]) => console.info(...args),
  warn: (...args: any[]) => console.warn(...args),
  error: (...args: any[]) => console.error(...args),
  fatal: (...args: any[]) => console.error(...args),
  trace: (...args: any[]) => console.debug(...args),
  child: () => createBrowserLogger(),
});

// Create logger based on environment
const createLogger = () => {
  // Check if we're in a browser environment
  if (typeof window !== 'undefined') {
    return createBrowserLogger();
  }

  // Server-side Pino configuration
  const isDevelopment = process.env.NODE_ENV === 'development';
  const isTest = process.env.NODE_ENV === 'test';

  const baseConfig = {
    name: 'atproto-app',
    level: process.env.LOG_LEVEL || (isDevelopment ? 'debug' : 'info'),
    // Lower level for tests to reduce noise
    ...(isTest && { level: 'warn' }),
  };

  // Pretty print in development
  if (isDevelopment) {
    return pino({
      ...baseConfig,
      transport: {
        target: 'pino-pretty',
        options: {
          colorize: true,
          ignore: 'pid,hostname',
          translateTime: 'SYS:HH:MM:ss',
        },
      },
    });
  }

  // Structured JSON logging in production
  return pino(baseConfig);
};

export const logger = createLogger();

// Convenience function to create child loggers with context
export const createChildLogger = (context: Record<string, any>) => {
  return logger.child(context);
};

// Utility function to log errors with full context
export const logError = (error: Error | unknown, context?: Record<string, any>) => {
  const errorLogger = context ? logger.child(context) : logger;
  
  if (error instanceof Error) {
    errorLogger.error({
      err: error,
      stack: error.stack,
      message: error.message,
    }, 'Error occurred');
  } else {
    errorLogger.error({ error }, 'Unknown error occurred');
  }
};

// Performance logging utility
export const logPerformance = (operation: string, startTime: number, context?: Record<string, any>) => {
  const duration = Date.now() - startTime;
  const perfLogger = context ? logger.child(context) : logger;
  
  perfLogger.info({
    operation,
    duration,
    ...context,
  }, `Operation ${operation} completed in ${duration}ms`);
};
