import * as plugins from './plugins.js';
import { randomUUID } from 'node:crypto';
import { SmartlogDestinationBuffer } from '@push.rocks/smartlog/destination-buffer';

// Map NODE_ENV to valid TEnvironment
const nodeEnv = process.env.NODE_ENV || 'production';
const envMap: Record<string, 'local' | 'test' | 'staging' | 'production'> = {
  'development': 'local',
  'test': 'test',
  'staging': 'staging',
  'production': 'production'
};

// In-memory log buffer for the OpsServer UI
export const logBuffer = new SmartlogDestinationBuffer({ maxEntries: 2000 });

// Default Smartlog instance (exported so OpsServer can add push destinations)
export const baseLogger = new plugins.smartlog.Smartlog({
  logContext: {
    environment: envMap[nodeEnv] || 'production',
    runtime: 'node',
    zone: 'serve.zone',
  }
});

// Wire the buffer destination so all logs are captured
baseLogger.addLogDestination(logBuffer);

// Extended logger compatible with the original enhanced logger API
class StandardLogger {
  private defaultContext: Record<string, any> = {};
  private correlationId: string | null = null;

  constructor() {}

  // Log methods
  public log(level: 'error' | 'warn' | 'info' | 'success' | 'debug', message: string, context: Record<string, any> = {}) {
    const combinedContext = {
      ...this.defaultContext,
      ...context
    };
    
    if (this.correlationId) {
      combinedContext.correlation_id = this.correlationId;
    }
    
    baseLogger.log(level, message, combinedContext);
  }

  public error(message: string, context: Record<string, any> = {}) {
    this.log('error', message, context);
  }

  public warn(message: string, context: Record<string, any> = {}) {
    this.log('warn', message, context);
  }

  public info(message: string, context: Record<string, any> = {}) {
    this.log('info', message, context);
  }

  public success(message: string, context: Record<string, any> = {}) {
    this.log('success', message, context);
  }

  public debug(message: string, context: Record<string, any> = {}) {
    this.log('debug', message, context);
  }

  // Context management
  public setContext(context: Record<string, any>, overwrite: boolean = false) {
    if (overwrite) {
      this.defaultContext = context;
    } else {
      this.defaultContext = {
        ...this.defaultContext,
        ...context
      };
    }
  }

  // Correlation ID management
  public setCorrelationId(id: string | null = null): string {
    this.correlationId = id || randomUUID();
    return this.correlationId;
  }

  public getCorrelationId(): string | null {
    return this.correlationId;
  }

  public clearCorrelationId(): void {
    this.correlationId = null;
  }
}

// Export a singleton instance
export const logger = new StandardLogger();
