type LogLevel = 'log' | 'warn' | 'error';

type LogEntry = {
  level: LogLevel;
  message: string;
  timestamp: number;
};

const MAX_ENTRIES = 100;
const buffer: LogEntry[] = [];

const originalLog = console.log;
const originalWarn = console.warn;
const originalError = console.error;

function pushEntry(level: LogLevel, args: unknown[]) {
  const message = args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ');
  buffer.push({ level, message, timestamp: Date.now() });
  if (buffer.length > MAX_ENTRIES) buffer.shift();
}

console.log = (...args: unknown[]) => {
  pushEntry('log', args);
  originalLog.apply(console, args);
};

console.warn = (...args: unknown[]) => {
  pushEntry('warn', args);
  originalWarn.apply(console, args);
};

console.error = (...args: unknown[]) => {
  pushEntry('error', args);
  originalError.apply(console, args);
};

export const getConsoleBuffer = (): LogEntry[] => [...buffer];
