import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

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

interface LogEntry {
  timestamp: string;
  level: LogLevel;
  message: string;
  data?: unknown;
}

export class Logger {
  private logFilePath: string;

  constructor(logFileName = 'txnbot.log') {
    this.logFilePath = path.resolve(__dirname, '..', logFileName);
  }

  private writeLog(level: LogLevel, message: string, data?: unknown): void {
    const logEntry: LogEntry = {
      timestamp: new Date().toISOString(),
      level,
      message,
      ...(data !== undefined && { data }),
    };

    const logLine = JSON.stringify(logEntry) + '\n';

    try {
      fs.appendFileSync(this.logFilePath, logLine, 'utf8');
    } catch (error) {
      // Fallback to stderr if file write fails
      process.stderr.write(`Failed to write log: ${error}\n`);
      process.stderr.write(logLine);
    }
  }

  info(message: string, data?: unknown): void {
    this.writeLog('info', message, data);
  }

  warn(message: string, data?: unknown): void {
    this.writeLog('warn', message, data);
  }

  error(message: string, data?: unknown): void {
    this.writeLog('error', message, data);
  }
}

export const logger = new Logger();
